mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 01:49:19 +08:00
Compare commits
24
Commits
master
...
f11b0b1d2f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f11b0b1d2f | ||
|
|
2d1290f726 | ||
|
|
21efea8334 | ||
|
|
af0fec790c | ||
|
|
a162c5dd9c | ||
|
|
874851a22a | ||
|
|
7c7e271f05 | ||
|
|
4e956eadcd | ||
|
|
3e49d6e9c9 | ||
|
|
59881dcb68 | ||
|
|
e136084794 | ||
|
|
92b6026b48 | ||
|
|
370ead39a1 | ||
|
|
5567b6d281 | ||
|
|
85bac4f710 | ||
|
|
13a2bd9274 | ||
|
|
883a1d0cfe | ||
|
|
67d01c678a | ||
|
|
a72a43cffc | ||
|
|
0b460e22b0 | ||
|
|
41f022bd63 | ||
|
|
71eca63461 | ||
|
|
d20c6a1302 | ||
|
|
9c2c1ed061 |
+22
-1
@@ -125,6 +125,7 @@ apps/agent/
|
|||||||
| `summary` | 会话滚动摘要(可选) |
|
| `summary` | 会话滚动摘要(可选) |
|
||||||
| `llm_provider_id` | 会话选用的提供商 id |
|
| `llm_provider_id` | 会话选用的提供商 id |
|
||||||
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
||||||
|
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
|
||||||
| `created_at`, `updated_at`, `last_message_at` | |
|
| `created_at`, `updated_at`, `last_message_at` | |
|
||||||
|
|
||||||
唯一索引:`(company_id, user_id, thread_id)`
|
唯一索引:`(company_id, user_id, thread_id)`
|
||||||
@@ -225,6 +226,7 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model
|
|||||||
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
||||||
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
||||||
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
||||||
|
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
|
||||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
||||||
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
||||||
@@ -363,6 +365,25 @@ apps/agent/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 11. 文档维护
|
## 11. Responses API 分期(多提供商)
|
||||||
|
|
||||||
|
原则:**Mongo 仍是对话真相源**;Responses 链(`previous_response_id`)只是同提供商同模型下的加速缓存,切换选型即作废并全量 rebuild。
|
||||||
|
|
||||||
|
### Responses-P0 / P1(已落地)— 运行时探测,不写死主机
|
||||||
|
|
||||||
|
原则:优先新协议;能力靠探测 + Redis 缓存(`agent:llm:cap:*`),按错误回退,不按 OpenAI/DeepSeek 主机写死。
|
||||||
|
|
||||||
|
同轮未产出 token 前的阶梯:
|
||||||
|
|
||||||
|
1. **Responses + `store=true`**(语义证实后;有会话链则只发增量 + `previous_response_id`)
|
||||||
|
2. store 未知:Responses + `store=true` + **Mongo 全量历史**,成功后再做语义探测
|
||||||
|
3. **store 证伪**:先 **无状态 Responses + Mongo 全量**,接口失败再 **Completions + Mongo 全量**
|
||||||
|
4. Responses 端点不可用 → Completions
|
||||||
|
|
||||||
|
成功后写入能力缓存。**`store=true` 认定**:独立语义探测——先让模型记住密钥,再仅用 `previous_response_id`(不带历史)追问;答对才记 true。未证实前禁止只发增量。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 文档维护
|
||||||
|
|
||||||
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
|
落地后同步:根目录 `AGENTS.md` 增加 `apps/agent`;`apps/server/docs/Agent与MCP接入及Boot升级说明.md` 勾选 LangGraph 项并注明多租户 MCP 与租户 LLM Key 约定。
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
|
|||||||
健康检查:`GET http://localhost:8200/health`
|
健康检查:`GET http://localhost:8200/health`
|
||||||
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
||||||
|
|
||||||
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(凭证 + 多模型勾选;`POST .../probe-models` 拉目录);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉**默认模型**明文注入。
|
**模型 API 配置不在本服务**:浏览器走 Java 提供商 CRUD(含 `apiStyle`);Agent 拉 runtime 后**运行时探测** Responses/store,结果缓存 Redis `agent:llm:cap:*`,失败阶梯为 Responses+store → Responses → Completions(见 DESIGN §11)。
|
||||||
|
|
||||||
## 分环境配置
|
## 分环境配置
|
||||||
|
|
||||||
|
|||||||
+14
-3
@@ -19,7 +19,11 @@ from infrastructure.persistence.mongo.repositories import (
|
|||||||
MongoMessageRepository,
|
MongoMessageRepository,
|
||||||
MongoSessionRepository,
|
MongoSessionRepository,
|
||||||
)
|
)
|
||||||
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
|
from infrastructure.persistence.redis.cache import (
|
||||||
|
RedisLlmProtocolCapabilityCache,
|
||||||
|
RedisLlmRuntimeCache,
|
||||||
|
get_redis,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def current_actor(
|
async def current_actor(
|
||||||
@@ -46,7 +50,11 @@ async def session_service(
|
|||||||
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
||||||
) -> SessionService:
|
) -> SessionService:
|
||||||
db = await get_db(settings)
|
db = await get_db(settings)
|
||||||
return SessionService(MongoSessionRepository(db), llm_runtime=llm_svc)
|
return SessionService(
|
||||||
|
MongoSessionRepository(db),
|
||||||
|
llm_runtime=llm_svc,
|
||||||
|
messages=MongoMessageRepository(db),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
||||||
@@ -68,5 +76,8 @@ async def chat_service(
|
|||||||
messages=MongoMessageRepository(db),
|
messages=MongoMessageRepository(db),
|
||||||
llm_runtime=llm_svc,
|
llm_runtime=llm_svc,
|
||||||
memory=mem_svc,
|
memory=mem_svc,
|
||||||
streamer=OpenAICompatibleStreamer(),
|
streamer=OpenAICompatibleStreamer(
|
||||||
|
RedisLlmProtocolCapabilityCache(get_redis(settings)),
|
||||||
|
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -120,3 +120,17 @@ async def archive_session(
|
|||||||
except LookupError as e:
|
except LookupError as e:
|
||||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||||
return ok(_session_vo(s))
|
return ok(_session_vo(s))
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{thread_id}")
|
||||||
|
async def delete_session(
|
||||||
|
thread_id: str,
|
||||||
|
actor: Actor = Depends(current_actor),
|
||||||
|
svc: SessionService = Depends(session_service),
|
||||||
|
):
|
||||||
|
"""软删会话并级联软删消息;列表与聊天不再可见。"""
|
||||||
|
try:
|
||||||
|
s = await svc.delete(actor, thread_id)
|
||||||
|
except LookupError as e:
|
||||||
|
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||||
|
return ok(_session_vo(s))
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ from application.memory_service import MemoryService
|
|||||||
from application.session_service import SessionService
|
from application.session_service import SessionService
|
||||||
from application.system_prompt import build_system_prompt
|
from application.system_prompt import build_system_prompt
|
||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import Actor, ChatMessage, MessageRole, StreamEvent
|
from domain.models import (
|
||||||
|
Actor,
|
||||||
|
ChatMessage,
|
||||||
|
LlmResponseChain,
|
||||||
|
MessageRole,
|
||||||
|
StreamEvent,
|
||||||
|
)
|
||||||
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
from domain.ports import ChatStreamer, MessageRepository, SessionRepository
|
||||||
|
|
||||||
|
|
||||||
@@ -63,7 +69,6 @@ class ChatService:
|
|||||||
provider_id=session.llm_provider_id,
|
provider_id=session.llm_provider_id,
|
||||||
model=session.llm_model,
|
model=session.llm_model,
|
||||||
)
|
)
|
||||||
# 回落默认或消歧后写回会话,保证列表/选框稳定
|
|
||||||
changed = False
|
changed = False
|
||||||
if session.llm_model != llm.model:
|
if session.llm_model != llm.model:
|
||||||
session.llm_model = llm.model
|
session.llm_model = llm.model
|
||||||
@@ -72,6 +77,13 @@ class ChatService:
|
|||||||
session.llm_provider_id = llm.provider_id
|
session.llm_provider_id = llm.provider_id
|
||||||
changed = True
|
changed = True
|
||||||
if changed:
|
if changed:
|
||||||
|
session.llm_response_chain = None
|
||||||
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
|
# 链是否可用由 streamer 按 store 能力决定;此处只做选型匹配
|
||||||
|
chain_id = _usable_chain_id(session.llm_response_chain, llm)
|
||||||
|
if session.llm_response_chain and not chain_id:
|
||||||
|
session.llm_response_chain = None
|
||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
just_saved = None
|
just_saved = None
|
||||||
@@ -120,7 +132,6 @@ class ChatService:
|
|||||||
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
||||||
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
||||||
)
|
)
|
||||||
# 本轮 tool 结果字符上限(与预留 tool token 粗对齐)
|
|
||||||
max_tool_chars = max(
|
max_tool_chars = max(
|
||||||
500, self._settings.context_reserve_tool_tokens * 2
|
500, self._settings.context_reserve_tool_tokens * 2
|
||||||
)
|
)
|
||||||
@@ -142,6 +153,7 @@ class ChatService:
|
|||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
|
new_response_id: str | None = None
|
||||||
async for event in self._streamer.stream_reply(
|
async for event in self._streamer.stream_reply(
|
||||||
llm=llm,
|
llm=llm,
|
||||||
history=history,
|
history=history,
|
||||||
@@ -149,7 +161,11 @@ class ChatService:
|
|||||||
system_prompt=system_prompt,
|
system_prompt=system_prompt,
|
||||||
tools=tools or None,
|
tools=tools or None,
|
||||||
max_tool_result_chars=max_tool_chars,
|
max_tool_result_chars=max_tool_chars,
|
||||||
|
previous_response_id=chain_id,
|
||||||
):
|
):
|
||||||
|
if event.kind == "response_chain" and event.response_id:
|
||||||
|
new_response_id = event.response_id
|
||||||
|
continue
|
||||||
if event.kind == "token" and event.text:
|
if event.kind == "token" and event.text:
|
||||||
parts.append(event.text)
|
parts.append(event.text)
|
||||||
yield event
|
yield event
|
||||||
@@ -167,4 +183,26 @@ class ChatService:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
session.last_message_at = datetime.utcnow()
|
session.last_message_at = datetime.utcnow()
|
||||||
|
if new_response_id:
|
||||||
|
session.llm_response_chain = LlmResponseChain(
|
||||||
|
provider_id=llm.provider_id,
|
||||||
|
model=llm.model,
|
||||||
|
previous_response_id=new_response_id,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
session.llm_response_chain = None
|
||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
|
|
||||||
|
|
||||||
|
def _usable_chain_id(chain: LlmResponseChain | None, llm) -> str | None:
|
||||||
|
if chain is None:
|
||||||
|
return None
|
||||||
|
rid = (chain.previous_response_id or "").strip()
|
||||||
|
if not rid:
|
||||||
|
return None
|
||||||
|
if (chain.model or "") != (llm.model or ""):
|
||||||
|
return None
|
||||||
|
if chain.provider_id is not None and llm.provider_id is not None:
|
||||||
|
if int(chain.provider_id) != int(llm.provider_id):
|
||||||
|
return None
|
||||||
|
return rid
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ class LlmRuntimeService:
|
|||||||
model=self._settings.llm_fallback_model,
|
model=self._settings.llm_fallback_model,
|
||||||
provider_id=None,
|
provider_id=None,
|
||||||
context_window=None,
|
context_window=None,
|
||||||
|
api_style="auto",
|
||||||
)
|
)
|
||||||
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from datetime import datetime
|
|||||||
|
|
||||||
from application.llm_settings_service import LlmRuntimeService
|
from application.llm_settings_service import LlmRuntimeService
|
||||||
from domain.models import Actor, Session, SessionStatus
|
from domain.models import Actor, Session, SessionStatus
|
||||||
from domain.ports import SessionRepository
|
from domain.ports import MessageRepository, SessionRepository
|
||||||
|
|
||||||
|
|
||||||
class SessionService:
|
class SessionService:
|
||||||
@@ -15,9 +15,11 @@ class SessionService:
|
|||||||
self,
|
self,
|
||||||
sessions: SessionRepository,
|
sessions: SessionRepository,
|
||||||
llm_runtime: LlmRuntimeService | None = None,
|
llm_runtime: LlmRuntimeService | None = None,
|
||||||
|
messages: MessageRepository | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._sessions = sessions
|
self._sessions = sessions
|
||||||
self._llm_runtime = llm_runtime
|
self._llm_runtime = llm_runtime
|
||||||
|
self._messages = messages
|
||||||
|
|
||||||
async def create(
|
async def create(
|
||||||
self,
|
self,
|
||||||
@@ -103,11 +105,31 @@ class SessionService:
|
|||||||
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
||||||
raise ValueError("提供商不能为空")
|
raise ValueError("提供商不能为空")
|
||||||
session = await self.require_owned(actor, thread_id)
|
session = await self.require_owned(actor, thread_id)
|
||||||
|
switched = (
|
||||||
|
session.llm_provider_id != int(llm_provider_id)
|
||||||
|
or (session.llm_model or "") != model
|
||||||
|
)
|
||||||
session.llm_provider_id = int(llm_provider_id)
|
session.llm_provider_id = int(llm_provider_id)
|
||||||
session.llm_model = model
|
session.llm_model = model
|
||||||
|
if switched:
|
||||||
|
# 切换选型后厂商侧链不可复用
|
||||||
|
session.llm_response_chain = None
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
||||||
session = await self.require_owned(actor, thread_id)
|
session = await self.require_owned(actor, thread_id)
|
||||||
session.status = SessionStatus.ARCHIVED
|
session.status = SessionStatus.ARCHIVED
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
|
async def delete(self, actor: Actor, thread_id: str) -> Session:
|
||||||
|
"""软删会话,并级联软删该线程消息。"""
|
||||||
|
session = await self.require_owned(actor, thread_id)
|
||||||
|
session.status = SessionStatus.DELETED
|
||||||
|
session.llm_response_chain = None
|
||||||
|
session.summary = None
|
||||||
|
saved = await self._sessions.update(session)
|
||||||
|
if self._messages is not None:
|
||||||
|
await self._messages.soft_delete_by_thread(
|
||||||
|
actor.company_id, actor.user_id, thread_id
|
||||||
|
)
|
||||||
|
return saved
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ _BASE_SYSTEM = (
|
|||||||
"需要经营数据时优先调用可用工具。"
|
"需要经营数据时优先调用可用工具。"
|
||||||
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
"工具可多轮检索,但对用户只报结论;默认不汇报检索过程、未命中关键词、搜了几轮或工具名。"
|
||||||
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
"不要自我纠错或评论上一轮话术(如「不该露编号」)。"
|
||||||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
"【本会话上下文】请求里已包含本会话近期的用户与助手原文,你可以直接看见并引用;"
|
||||||
"需要称呼、偏好或用户事实时:先 memory_search,必要时再 memory_load;"
|
"禁止声称「只收到当前一句」或「前面几轮不会带过来」——那是错误描述。"
|
||||||
"禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
"【长期记忆】跨会话的用户级记忆不会自动注入;需要称呼、偏好或用户事实时:"
|
||||||
|
"先 memory_search,必要时再 memory_load;禁止编造未载入的记忆,也不要声称没有长期记忆能力。"
|
||||||
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
"介绍记忆:自然语言短列表即可;禁止输出 ref、id、字段名、更新时间或表格。"
|
||||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
|
|||||||
# 为模型输出与本轮 tool 预留的 token
|
# 为模型输出与本轮 tool 预留的 token
|
||||||
context_reserve_output_tokens: int = 4096
|
context_reserve_output_tokens: int = 4096
|
||||||
context_reserve_tool_tokens: int = 8192
|
context_reserve_tool_tokens: int = 8192
|
||||||
|
# Responses/store 能力缓存 TTL(秒)
|
||||||
|
llm_capability_ttl_seconds: int = 604800
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cors_origin_list(self) -> list[str]:
|
def cors_origin_list(self) -> list[str]:
|
||||||
|
|||||||
@@ -50,6 +50,15 @@ class Actor:
|
|||||||
return role in {"owner", "admin"}
|
return role in {"owner", "admin"}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LlmResponseChain:
|
||||||
|
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
|
||||||
|
|
||||||
|
provider_id: int | None
|
||||||
|
model: str
|
||||||
|
previous_response_id: str
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Session:
|
class Session:
|
||||||
thread_id: str
|
thread_id: str
|
||||||
@@ -65,6 +74,8 @@ class Session:
|
|||||||
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||||
llm_provider_id: int | None = None
|
llm_provider_id: int | None = None
|
||||||
llm_model: str | None = None
|
llm_model: str | None = None
|
||||||
|
# Responses 续链;切换选型或链失效时清空
|
||||||
|
llm_response_chain: LlmResponseChain | None = None
|
||||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
last_message_at: datetime | None = None
|
last_message_at: datetime | None = None
|
||||||
@@ -118,19 +129,31 @@ class LlmRuntimeConfig:
|
|||||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||||
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
||||||
context_window: int | None = None
|
context_window: int | None = None
|
||||||
|
# API 协议:auto | completions | responses
|
||||||
|
api_style: str = "auto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class LlmProtocolCapability:
|
||||||
|
"""按提供商缓存的协议能力;None 表示尚未验证。"""
|
||||||
|
|
||||||
|
responses: bool | None = None
|
||||||
|
store: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class StreamEvent:
|
class StreamEvent:
|
||||||
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
"""流式片段:正文 token、服务端工具状态、或需前端执行的 client tool。"""
|
||||||
|
|
||||||
kind: str # token | tool | client_tool | pending_client_tools
|
kind: str # token | tool | client_tool | pending_client_tools | response_chain
|
||||||
text: str | None = None
|
text: str | None = None
|
||||||
phase: str | None = None # start | end
|
phase: str | None = None # start | end
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
label: str | None = None
|
label: str | None = None
|
||||||
tool_call_id: str | None = None
|
tool_call_id: str | None = None
|
||||||
args: dict | None = None
|
args: dict | None = None
|
||||||
|
# Responses 本轮最终 response id(仅 kind=response_chain)
|
||||||
|
response_id: str | None = None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def token(text: str) -> StreamEvent:
|
def token(text: str) -> StreamEvent:
|
||||||
@@ -159,3 +182,8 @@ class StreamEvent:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def pending_client_tools() -> StreamEvent:
|
def pending_client_tools() -> StreamEvent:
|
||||||
return StreamEvent(kind="pending_client_tools")
|
return StreamEvent(kind="pending_client_tools")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def response_chain(response_id: str) -> StreamEvent:
|
||||||
|
"""内部事件:落会话续链;不推给前端 SSE。"""
|
||||||
|
return StreamEvent(kind="response_chain", response_id=response_id)
|
||||||
|
|||||||
@@ -5,7 +5,14 @@ from __future__ import annotations
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Any, AsyncIterator
|
from typing import Any, AsyncIterator
|
||||||
|
|
||||||
from domain.models import ChatMessage, LlmRuntimeConfig, Session, StreamEvent, UserMemory
|
from domain.models import (
|
||||||
|
ChatMessage,
|
||||||
|
LlmProtocolCapability,
|
||||||
|
LlmRuntimeConfig,
|
||||||
|
Session,
|
||||||
|
StreamEvent,
|
||||||
|
UserMemory,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class SessionRepository(ABC):
|
class SessionRepository(ABC):
|
||||||
@@ -51,6 +58,13 @@ class MessageRepository(ABC):
|
|||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def soft_delete_by_thread(
|
||||||
|
self, company_id: int, user_id: str, thread_id: str
|
||||||
|
) -> int:
|
||||||
|
"""软删某会话下全部消息,返回影响条数。"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
class MemoryRepository(ABC):
|
class MemoryRepository(ABC):
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
@@ -111,6 +125,25 @@ class LlmRuntimeGateway(ABC):
|
|||||||
) -> LlmRuntimeConfig | None: ...
|
) -> LlmRuntimeConfig | None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class LlmProtocolCapabilityCache(ABC):
|
||||||
|
"""缓存某提供商(或 base_url)是否支持 Responses / store。"""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def get(
|
||||||
|
self, *, provider_id: int | None, base_url: str
|
||||||
|
) -> LlmProtocolCapability | None: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
async def set(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
provider_id: int | None,
|
||||||
|
base_url: str,
|
||||||
|
capability: LlmProtocolCapability,
|
||||||
|
ttl_seconds: int,
|
||||||
|
) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
class ChatStreamer(ABC):
|
class ChatStreamer(ABC):
|
||||||
"""流式生成助手回复。"""
|
"""流式生成助手回复。"""
|
||||||
|
|
||||||
@@ -124,4 +157,5 @@ class ChatStreamer(ABC):
|
|||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
tools: list[Any] | None = None,
|
tools: list[Any] | None = None,
|
||||||
max_tool_result_chars: int = 4000,
|
max_tool_result_chars: int = 4000,
|
||||||
|
previous_response_id: str | None = None,
|
||||||
) -> AsyncIterator[StreamEvent]: ...
|
) -> AsyncIterator[StreamEvent]: ...
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""协议偏好与错误分类:先验缓存 + 运行时探测回退(不写死主机)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from domain.models import LlmProtocolCapability
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_api_style(raw: str | None) -> str:
|
||||||
|
s = (raw or "auto").strip().lower()
|
||||||
|
if s in ("auto", "completions", "responses"):
|
||||||
|
return s
|
||||||
|
return "auto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ProtocolAttempt:
|
||||||
|
"""单次调用策略。"""
|
||||||
|
|
||||||
|
use_responses: bool
|
||||||
|
use_store: bool
|
||||||
|
use_chain: bool # 是否只发增量 + previous_response_id(须 store 已证实)
|
||||||
|
|
||||||
|
|
||||||
|
def plan_protocol_attempts(
|
||||||
|
api_style: str | None,
|
||||||
|
cap: LlmProtocolCapability | None,
|
||||||
|
*,
|
||||||
|
has_chain_id: bool,
|
||||||
|
) -> list[ProtocolAttempt]:
|
||||||
|
"""
|
||||||
|
同轮探测顺序(未产出 token 前可依次尝试):
|
||||||
|
|
||||||
|
- store 已证实:Responses+store,有链则增量续聊
|
||||||
|
- store 未知:Responses+store + **Mongo 全量**,成功后再语义探测
|
||||||
|
- store 证伪:先 **无状态 Responses + Mongo 全量**,失败再 **Completions**
|
||||||
|
- Responses 不可用:Completions
|
||||||
|
"""
|
||||||
|
style = normalize_api_style(api_style)
|
||||||
|
cap = cap or LlmProtocolCapability()
|
||||||
|
|
||||||
|
if style == "completions":
|
||||||
|
return [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
attempts: list[ProtocolAttempt] = []
|
||||||
|
|
||||||
|
if cap.store is False:
|
||||||
|
# 无真实 store:无状态 Responses(全量历史)→ Completions
|
||||||
|
if cap.responses is not False:
|
||||||
|
attempts.append(ProtocolAttempt(True, False, False))
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
return _dedupe(attempts)
|
||||||
|
|
||||||
|
if cap.responses is not False:
|
||||||
|
if cap.store is True:
|
||||||
|
attempts.append(
|
||||||
|
ProtocolAttempt(True, True, use_chain=bool(has_chain_id))
|
||||||
|
)
|
||||||
|
# 有链失败时可降到同协议全量
|
||||||
|
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||||
|
else:
|
||||||
|
# store 未知:Responses+store,必须全量历史,禁止 use_chain
|
||||||
|
attempts.append(ProtocolAttempt(True, True, use_chain=False))
|
||||||
|
attempts.append(ProtocolAttempt(True, False, False))
|
||||||
|
|
||||||
|
# Completions 兜底
|
||||||
|
if style == "auto" or cap.responses is False:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
elif style == "responses" and cap.responses is False:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
|
||||||
|
return _dedupe(attempts) or [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe(attempts: list[ProtocolAttempt]) -> list[ProtocolAttempt]:
|
||||||
|
seen: set[tuple[bool, bool, bool]] = set()
|
||||||
|
out: list[ProtocolAttempt] = []
|
||||||
|
for a in attempts:
|
||||||
|
key = (a.use_responses, a.use_store, a.use_chain)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
out.append(a)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def classify_protocol_error(exc: BaseException) -> str:
|
||||||
|
"""返回: store | responses | chain | other。"""
|
||||||
|
text = str(exc).lower()
|
||||||
|
status = getattr(exc, "status_code", None) or getattr(
|
||||||
|
getattr(exc, "response", None), "status_code", None
|
||||||
|
)
|
||||||
|
|
||||||
|
if "previous_response_id" in text or "previous response" in text:
|
||||||
|
return "chain"
|
||||||
|
if status == 400 and "response" in text and "not found" in text:
|
||||||
|
return "chain"
|
||||||
|
|
||||||
|
if "store" in text and any(
|
||||||
|
n in text
|
||||||
|
for n in (
|
||||||
|
"unsupported",
|
||||||
|
"unknown",
|
||||||
|
"unrecognized",
|
||||||
|
"invalid",
|
||||||
|
"not support",
|
||||||
|
"not supported",
|
||||||
|
)
|
||||||
|
):
|
||||||
|
return "store"
|
||||||
|
|
||||||
|
if status in (404, 405):
|
||||||
|
return "responses"
|
||||||
|
responses_needles = (
|
||||||
|
"/responses",
|
||||||
|
"responses api",
|
||||||
|
"unknown endpoint",
|
||||||
|
"not implemented",
|
||||||
|
"invalid pathname",
|
||||||
|
"no route",
|
||||||
|
)
|
||||||
|
if any(n in text for n in responses_needles):
|
||||||
|
return "responses"
|
||||||
|
if status == 400 and ("responses" in text or "response.create" in text):
|
||||||
|
return "responses"
|
||||||
|
|
||||||
|
return "other"
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。"""
|
"""按租户构建 OpenAI Compatible Chat 模型并流式输出(可带 MCP tools)。
|
||||||
|
|
||||||
|
优先 Responses+store → Responses store=false → Completions;
|
||||||
|
能力结果写入 Redis,不按主机写死。未产出 token 前可同轮回退。
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from typing import Any, AsyncIterator
|
from typing import Any, AsyncIterator
|
||||||
|
|
||||||
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
||||||
@@ -10,11 +15,36 @@ from langchain_openai import ChatOpenAI
|
|||||||
|
|
||||||
from agent.tools.labels import tool_status_label
|
from agent.tools.labels import tool_status_label
|
||||||
from agent.tools.publish_ui import is_client_tool_name
|
from agent.tools.publish_ui import is_client_tool_name
|
||||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
from domain.models import (
|
||||||
from domain.ports import ChatStreamer
|
ChatMessage,
|
||||||
|
LlmProtocolCapability,
|
||||||
|
LlmRuntimeConfig,
|
||||||
|
MessageRole,
|
||||||
|
StreamEvent,
|
||||||
|
)
|
||||||
|
from domain.ports import ChatStreamer, LlmProtocolCapabilityCache
|
||||||
|
from infrastructure.llm.api_style import (
|
||||||
|
ProtocolAttempt,
|
||||||
|
classify_protocol_error,
|
||||||
|
normalize_api_style,
|
||||||
|
plan_protocol_attempts,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_UNSET = object()
|
||||||
|
|
||||||
|
|
||||||
class OpenAICompatibleStreamer(ChatStreamer):
|
class OpenAICompatibleStreamer(ChatStreamer):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
capability_cache: LlmProtocolCapabilityCache | None = None,
|
||||||
|
*,
|
||||||
|
capability_ttl_seconds: int = 604800,
|
||||||
|
) -> None:
|
||||||
|
self._cap_cache = capability_cache
|
||||||
|
self._cap_ttl = capability_ttl_seconds
|
||||||
|
|
||||||
async def stream_reply(
|
async def stream_reply(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
@@ -24,40 +54,331 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
tools: list[Any] | None = None,
|
tools: list[Any] | None = None,
|
||||||
max_tool_result_chars: int = 8000,
|
max_tool_result_chars: int = 8000,
|
||||||
|
previous_response_id: str | None = None,
|
||||||
) -> AsyncIterator[StreamEvent]:
|
) -> AsyncIterator[StreamEvent]:
|
||||||
|
chain_id = (previous_response_id or "").strip() or None
|
||||||
|
style = normalize_api_style(llm.api_style)
|
||||||
|
# 未知 store 时先做语义探测(能否靠 previous_response_id 记住上下文)
|
||||||
|
cap = await self._ensure_protocol_capability(llm, style)
|
||||||
|
attempts = plan_protocol_attempts(
|
||||||
|
llm.api_style, cap, has_chain_id=bool(chain_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
i = 0
|
||||||
|
while i < len(attempts):
|
||||||
|
attempt = attempts[i]
|
||||||
|
# 仅缓存已证实 store=true 时才丢历史、纯续链
|
||||||
|
use_chain_id = (
|
||||||
|
chain_id if (attempt.use_chain and cap and cap.store is True) else None
|
||||||
|
)
|
||||||
|
logger.warning(
|
||||||
|
"LLM attempt model=%s responses=%s store=%s chain=%s hist=%s api_style=%s",
|
||||||
|
llm.model,
|
||||||
|
attempt.use_responses,
|
||||||
|
attempt.use_store,
|
||||||
|
bool(use_chain_id),
|
||||||
|
len(history),
|
||||||
|
style,
|
||||||
|
)
|
||||||
|
yielded_any = False
|
||||||
|
got_chain_id: str | None = None
|
||||||
|
try:
|
||||||
|
async for event in self._stream_once(
|
||||||
|
llm=llm,
|
||||||
|
history=history,
|
||||||
|
user_text=user_text,
|
||||||
|
system_prompt=system_prompt,
|
||||||
|
tools=tools,
|
||||||
|
max_tool_result_chars=max_tool_result_chars,
|
||||||
|
use_responses=attempt.use_responses,
|
||||||
|
use_store=attempt.use_store,
|
||||||
|
previous_response_id=use_chain_id,
|
||||||
|
):
|
||||||
|
if event.kind == "token" and event.text:
|
||||||
|
yielded_any = True
|
||||||
|
if event.kind == "response_chain" and event.response_id:
|
||||||
|
got_chain_id = event.response_id
|
||||||
|
continue
|
||||||
|
yield event
|
||||||
|
|
||||||
|
if attempt.use_responses:
|
||||||
|
if use_chain_id:
|
||||||
|
# 已证实 store 且本轮续链成功
|
||||||
|
await self._update_cap(llm, responses=True, store=True)
|
||||||
|
if got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
elif attempt.use_store:
|
||||||
|
# store 未证实或待刷新:本轮是全量历史;语义探测真伪
|
||||||
|
need_probe = cap is None or cap.store is not True
|
||||||
|
if need_probe:
|
||||||
|
store_ok = await self._probe_store_semantic(llm)
|
||||||
|
await self._update_cap(
|
||||||
|
llm, responses=True, store=store_ok
|
||||||
|
)
|
||||||
|
cap = LlmProtocolCapability(
|
||||||
|
responses=True, store=store_ok
|
||||||
|
)
|
||||||
|
if store_ok and got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
else:
|
||||||
|
await self._update_cap(llm, responses=True, store=True)
|
||||||
|
if got_chain_id:
|
||||||
|
yield StreamEvent.response_chain(got_chain_id)
|
||||||
|
else:
|
||||||
|
# Responses 无 store:能通端点但不持久
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
else:
|
||||||
|
# Completions:若已知有 Responses 只是无 store,不要把 responses 打成 false
|
||||||
|
if cap is not None and cap.responses is True and cap.store is False:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
elif cap is not None and cap.store is False:
|
||||||
|
await self._update_cap(llm, responses=cap.responses, store=False)
|
||||||
|
else:
|
||||||
|
await self._update_cap(llm, responses=False, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
return
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
if yielded_any:
|
||||||
|
raise
|
||||||
|
kind = classify_protocol_error(e)
|
||||||
|
logger.warning(
|
||||||
|
"LLM attempt failed kind=%s model=%s err=%s",
|
||||||
|
kind,
|
||||||
|
llm.model,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
if kind == "chain" and use_chain_id:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
nxt = ProtocolAttempt(True, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if kind == "store" and attempt.use_responses and attempt.use_store:
|
||||||
|
await self._update_cap(llm, responses=True, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
nxt = ProtocolAttempt(True, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if kind == "responses" and attempt.use_responses:
|
||||||
|
await self._update_cap(llm, responses=False, store=False)
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
nxt = ProtocolAttempt(False, False, False)
|
||||||
|
if nxt not in attempts[i + 1 :]:
|
||||||
|
attempts.insert(i + 1, nxt)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if i + 1 < len(attempts):
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if style == "responses" and attempt.use_responses:
|
||||||
|
attempts.append(ProtocolAttempt(False, False, False))
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
raise
|
||||||
|
i += 1 # pragma: no cover
|
||||||
|
|
||||||
|
async def _ensure_protocol_capability(
|
||||||
|
self, llm: LlmRuntimeConfig, style: str
|
||||||
|
) -> LlmProtocolCapability | None:
|
||||||
|
"""读取能力缓存;completions 强制走 Completions,不探测。"""
|
||||||
|
if style == "completions":
|
||||||
|
return LlmProtocolCapability(responses=False, store=False)
|
||||||
|
return await self._load_cap(llm)
|
||||||
|
|
||||||
|
async def _load_cap(self, llm: LlmRuntimeConfig) -> LlmProtocolCapability | None:
|
||||||
|
if self._cap_cache is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return await self._cap_cache.get(
|
||||||
|
provider_id=llm.provider_id, base_url=llm.base_url
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("读取协议能力缓存失败")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _update_cap(
|
||||||
|
self,
|
||||||
|
llm: LlmRuntimeConfig,
|
||||||
|
*,
|
||||||
|
responses: bool | None | object = _UNSET,
|
||||||
|
store: bool | None | object = _UNSET,
|
||||||
|
) -> None:
|
||||||
|
"""更新能力缓存;参数为 _UNSET 表示不改该字段,显式 None 表示未知。"""
|
||||||
|
if self._cap_cache is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
prev = await self._cap_cache.get(
|
||||||
|
provider_id=llm.provider_id, base_url=llm.base_url
|
||||||
|
) or LlmProtocolCapability()
|
||||||
|
new_responses = (
|
||||||
|
prev.responses if responses is _UNSET else responses # type: ignore[arg-type]
|
||||||
|
)
|
||||||
|
new_store = prev.store if store is _UNSET else store # type: ignore[arg-type]
|
||||||
|
await self._cap_cache.set(
|
||||||
|
provider_id=llm.provider_id,
|
||||||
|
base_url=llm.base_url,
|
||||||
|
capability=LlmProtocolCapability(
|
||||||
|
responses=new_responses, # type: ignore[arg-type]
|
||||||
|
store=new_store, # type: ignore[arg-type]
|
||||||
|
),
|
||||||
|
ttl_seconds=self._cap_ttl,
|
||||||
|
)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("写入协议能力缓存失败")
|
||||||
|
|
||||||
|
async def _probe_store_semantic(self, llm: LlmRuntimeConfig) -> bool:
|
||||||
|
"""
|
||||||
|
语义探测:先写入密钥,再用 previous_response_id 且不带历史追问。
|
||||||
|
能答对密钥 → 真支持 store 续链;否则(报错或静默丢上下文)→ false。
|
||||||
|
"""
|
||||||
|
secret = "ALPHA7X"
|
||||||
|
try:
|
||||||
model = ChatOpenAI(
|
model = ChatOpenAI(
|
||||||
api_key=llm.api_key,
|
api_key=llm.api_key,
|
||||||
base_url=llm.base_url,
|
base_url=llm.base_url,
|
||||||
model=llm.model,
|
model=llm.model,
|
||||||
temperature=0.3,
|
temperature=0,
|
||||||
streaming=True,
|
streaming=False,
|
||||||
default_headers=llm.extra_headers or None,
|
default_headers=llm.extra_headers or None,
|
||||||
|
use_responses_api=True,
|
||||||
|
output_version="responses/v1",
|
||||||
|
store=True,
|
||||||
|
use_previous_response_id=True,
|
||||||
)
|
)
|
||||||
messages: list[Any] = [SystemMessage(content=system_prompt)]
|
first = await model.ainvoke(
|
||||||
|
[
|
||||||
|
HumanMessage(
|
||||||
|
content=(
|
||||||
|
f"这是接口能力测试。请记住密钥:{secret}。"
|
||||||
|
"只回复一个词:OK"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
rid = _response_id_of(first)
|
||||||
|
if not rid:
|
||||||
|
logger.info("store 语义探测失败:首轮无 response.id model=%s", llm.model)
|
||||||
|
return False
|
||||||
|
second = await model.ainvoke(
|
||||||
|
[
|
||||||
|
HumanMessage(
|
||||||
|
content="接口能力测试续问:刚才的密钥是什么?只回复密钥本身。"
|
||||||
|
)
|
||||||
|
],
|
||||||
|
previous_response_id=rid,
|
||||||
|
)
|
||||||
|
text = _chunk_text(getattr(second, "content", None)).upper()
|
||||||
|
ok = secret in text.replace(" ", "").replace("-", "")
|
||||||
|
if not ok:
|
||||||
|
logger.info(
|
||||||
|
"store 语义探测未通过(静默丢上下文)model=%s reply=%s",
|
||||||
|
llm.model,
|
||||||
|
text[:80],
|
||||||
|
)
|
||||||
|
return ok
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
logger.info(
|
||||||
|
"store 语义探测异常 model=%s kind=%s err=%s",
|
||||||
|
llm.model,
|
||||||
|
classify_protocol_error(e),
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _stream_once(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
llm: LlmRuntimeConfig,
|
||||||
|
history: list[ChatMessage],
|
||||||
|
user_text: str,
|
||||||
|
system_prompt: str,
|
||||||
|
tools: list[Any] | None,
|
||||||
|
max_tool_result_chars: int,
|
||||||
|
use_responses: bool,
|
||||||
|
use_store: bool,
|
||||||
|
previous_response_id: str | None,
|
||||||
|
) -> AsyncIterator[StreamEvent]:
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
"api_key": llm.api_key,
|
||||||
|
"base_url": llm.base_url,
|
||||||
|
"model": llm.model,
|
||||||
|
"temperature": 0.3,
|
||||||
|
"streaming": True,
|
||||||
|
"default_headers": llm.extra_headers or None,
|
||||||
|
"use_responses_api": use_responses,
|
||||||
|
}
|
||||||
|
if use_responses:
|
||||||
|
kwargs["output_version"] = "responses/v1"
|
||||||
|
kwargs["store"] = use_store
|
||||||
|
# 仅真正续链时打开;否则 LangChain 可能按 AIMessage.id 截断历史
|
||||||
|
kwargs["use_previous_response_id"] = bool(
|
||||||
|
previous_response_id and use_store
|
||||||
|
)
|
||||||
|
|
||||||
|
model = ChatOpenAI(**kwargs)
|
||||||
|
if previous_response_id and use_store:
|
||||||
|
# 已证实 store:只发本轮,靠 previous_response_id 续上下文
|
||||||
|
messages: list[Any] = [
|
||||||
|
SystemMessage(content=system_prompt),
|
||||||
|
HumanMessage(content=user_text),
|
||||||
|
]
|
||||||
|
first_extra: dict[str, Any] = {
|
||||||
|
"previous_response_id": previous_response_id
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 无 store / Completions / 未证实:Mongo 全量历史 + 本轮
|
||||||
|
messages = [SystemMessage(content=system_prompt)]
|
||||||
for m in history:
|
for m in history:
|
||||||
if m.role == MessageRole.USER:
|
if m.role == MessageRole.USER:
|
||||||
messages.append(HumanMessage(content=m.content))
|
messages.append(HumanMessage(content=m.content))
|
||||||
elif m.role == MessageRole.ASSISTANT:
|
elif m.role == MessageRole.ASSISTANT:
|
||||||
messages.append(AIMessage(content=m.content))
|
messages.append(AIMessage(content=m.content))
|
||||||
messages.append(HumanMessage(content=user_text))
|
messages.append(HumanMessage(content=user_text))
|
||||||
|
first_extra = {}
|
||||||
|
logger.warning(
|
||||||
|
"LLM pack full history lc_messages=%s hist_rows=%s preview=%s",
|
||||||
|
len(messages),
|
||||||
|
len(history),
|
||||||
|
[
|
||||||
|
(
|
||||||
|
m.role.value if hasattr(m, "role") else type(m).__name__,
|
||||||
|
(getattr(m, "content", None) or "")[:40],
|
||||||
|
)
|
||||||
|
for m in (
|
||||||
|
history[-4:] if len(history) > 4 else history
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
last_response_id: str | None = None
|
||||||
|
|
||||||
if not tools:
|
if not tools:
|
||||||
async for chunk in model.astream(messages):
|
async for chunk in model.astream(messages, **first_extra):
|
||||||
|
last_response_id = _response_id_of(chunk) or last_response_id
|
||||||
text = _chunk_text(chunk.content)
|
text = _chunk_text(chunk.content)
|
||||||
if text:
|
if text:
|
||||||
yield StreamEvent.token(text)
|
yield StreamEvent.token(text)
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
|
|
||||||
bound = model.bind_tools(tools)
|
bound = model.bind_tools(tools)
|
||||||
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
||||||
tool_cap = max(500, max_tool_result_chars)
|
tool_cap = max(500, max_tool_result_chars)
|
||||||
for _ in range(5):
|
for round_idx in range(5):
|
||||||
gathered = None
|
gathered = None
|
||||||
saw_tool = False
|
saw_tool = False
|
||||||
async for chunk in bound.astream(messages):
|
call_extra = first_extra if round_idx == 0 else {}
|
||||||
|
async for chunk in bound.astream(messages, **call_extra):
|
||||||
gathered = chunk if gathered is None else gathered + chunk
|
gathered = chunk if gathered is None else gathered + chunk
|
||||||
if getattr(chunk, "tool_call_chunks", None) or getattr(chunk, "tool_calls", None):
|
if getattr(chunk, "tool_call_chunks", None) or getattr(
|
||||||
|
chunk, "tool_calls", None
|
||||||
|
):
|
||||||
saw_tool = True
|
saw_tool = True
|
||||||
continue
|
continue
|
||||||
if saw_tool:
|
if saw_tool:
|
||||||
@@ -65,12 +386,19 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
text = _chunk_text(getattr(chunk, "content", None))
|
text = _chunk_text(getattr(chunk, "content", None))
|
||||||
if text:
|
if text:
|
||||||
yield StreamEvent.token(text)
|
yield StreamEvent.token(text)
|
||||||
|
|
||||||
if gathered is None:
|
if gathered is None:
|
||||||
yield StreamEvent.token("(模型未返回内容)")
|
yield StreamEvent.token("(模型未返回内容)")
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
last_response_id = _response_id_of(gathered) or last_response_id
|
||||||
messages.append(gathered)
|
messages.append(gathered)
|
||||||
tool_calls = getattr(gathered, "tool_calls", None) or []
|
tool_calls = getattr(gathered, "tool_calls", None) or []
|
||||||
if not tool_calls:
|
if not tool_calls:
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
seen: set[str] = set()
|
seen: set[str] = set()
|
||||||
@@ -121,19 +449,44 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
|||||||
)
|
)
|
||||||
|
|
||||||
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
yield StreamEvent.token("工具调用轮次过多,请缩小问题范围后重试。")
|
||||||
|
if use_store and last_response_id:
|
||||||
|
yield StreamEvent.response_chain(last_response_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _response_id_of(msg: Any) -> str | None:
|
||||||
|
meta = getattr(msg, "response_metadata", None) or {}
|
||||||
|
if isinstance(meta, dict):
|
||||||
|
rid = meta.get("id")
|
||||||
|
if isinstance(rid, str) and rid.strip():
|
||||||
|
return rid.strip()
|
||||||
|
mid = getattr(msg, "id", None)
|
||||||
|
if isinstance(mid, str) and mid.startswith("resp_"):
|
||||||
|
return mid
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _chunk_text(content: Any) -> str:
|
def _chunk_text(content: Any) -> str:
|
||||||
|
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
|
||||||
|
if content is None:
|
||||||
|
return ""
|
||||||
if isinstance(content, str):
|
if isinstance(content, str):
|
||||||
return content
|
return content
|
||||||
if isinstance(content, list):
|
if isinstance(content, list):
|
||||||
parts: list[str] = []
|
parts: list[str] = []
|
||||||
for part in content:
|
for part in content:
|
||||||
if isinstance(part, dict) and part.get("type") == "text":
|
if isinstance(part, str):
|
||||||
|
parts.append(part)
|
||||||
|
continue
|
||||||
|
if not isinstance(part, dict):
|
||||||
|
text = getattr(part, "text", None)
|
||||||
|
ptype = getattr(part, "type", None)
|
||||||
|
if text and ptype in (None, "text", "output_text"):
|
||||||
|
parts.append(str(text))
|
||||||
|
continue
|
||||||
|
ptype = part.get("type")
|
||||||
|
if ptype in (None, "text", "output_text"):
|
||||||
t = part.get("text")
|
t = part.get("text")
|
||||||
if t:
|
if t:
|
||||||
parts.append(str(t))
|
parts.append(str(t))
|
||||||
elif isinstance(part, str):
|
|
||||||
parts.append(part)
|
|
||||||
return "".join(parts)
|
return "".join(parts)
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import httpx
|
|||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import LlmRuntimeConfig
|
from domain.models import LlmRuntimeConfig
|
||||||
from domain.ports import LlmRuntimeGateway
|
from domain.ports import LlmRuntimeGateway
|
||||||
|
from infrastructure.llm.api_style import normalize_api_style
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
|||||||
for k, v in (data.get("extraHeaders") or {}).items()
|
for k, v in (data.get("extraHeaders") or {}).items()
|
||||||
},
|
},
|
||||||
context_window=_optional_positive_int(data.get("contextWindow")),
|
context_window=_optional_positive_int(data.get("contextWindow")),
|
||||||
|
api_style=normalize_api_style(
|
||||||
|
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
|
||||||
|
),
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from motor.motor_asyncio import AsyncIOMotorDatabase
|
|||||||
|
|
||||||
from domain.models import (
|
from domain.models import (
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
|
LlmResponseChain,
|
||||||
MemoryKind,
|
MemoryKind,
|
||||||
MemoryStatus,
|
MemoryStatus,
|
||||||
MessageRole,
|
MessageRole,
|
||||||
@@ -36,6 +37,30 @@ def _optional_int(v: Any) -> int | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _chain_to_doc(chain: LlmResponseChain | None) -> dict[str, Any] | None:
|
||||||
|
if chain is None or not (chain.previous_response_id or "").strip():
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"provider_id": chain.provider_id,
|
||||||
|
"model": chain.model,
|
||||||
|
"previous_response_id": chain.previous_response_id.strip(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _chain_from_doc(raw: Any) -> LlmResponseChain | None:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
return None
|
||||||
|
rid = str(raw.get("previous_response_id") or "").strip()
|
||||||
|
model = str(raw.get("model") or "").strip()
|
||||||
|
if not rid or not model:
|
||||||
|
return None
|
||||||
|
return LlmResponseChain(
|
||||||
|
provider_id=_optional_int(raw.get("provider_id")),
|
||||||
|
model=model,
|
||||||
|
previous_response_id=rid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class MongoSessionRepository(SessionRepository):
|
class MongoSessionRepository(SessionRepository):
|
||||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||||
self._col = db.agent_sessions
|
self._col = db.agent_sessions
|
||||||
@@ -52,6 +77,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"scene_ref": session.scene_ref,
|
"scene_ref": session.scene_ref,
|
||||||
"llm_provider_id": session.llm_provider_id,
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
|
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||||
"created_at": session.created_at,
|
"created_at": session.created_at,
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
"last_message_at": session.last_message_at,
|
"last_message_at": session.last_message_at,
|
||||||
@@ -135,6 +161,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"scene_ref": session.scene_ref,
|
"scene_ref": session.scene_ref,
|
||||||
"llm_provider_id": session.llm_provider_id,
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
|
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
"last_message_at": session.last_message_at,
|
"last_message_at": session.last_message_at,
|
||||||
}
|
}
|
||||||
@@ -155,6 +182,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
scene_ref=doc.get("scene_ref"),
|
scene_ref=doc.get("scene_ref"),
|
||||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||||
llm_model=doc.get("llm_model"),
|
llm_model=doc.get("llm_model"),
|
||||||
|
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
|
||||||
created_at=_dt(doc.get("created_at")),
|
created_at=_dt(doc.get("created_at")),
|
||||||
updated_at=_dt(doc.get("updated_at")),
|
updated_at=_dt(doc.get("updated_at")),
|
||||||
last_message_at=doc.get("last_message_at"),
|
last_message_at=doc.get("last_message_at"),
|
||||||
@@ -194,7 +222,17 @@ class MongoMessageRepository(MessageRepository):
|
|||||||
) -> list[ChatMessage]:
|
) -> list[ChatMessage]:
|
||||||
cursor = (
|
cursor = (
|
||||||
self._col.find(
|
self._col.find(
|
||||||
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
{
|
||||||
|
"company_id": company_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"thread_id": thread_id,
|
||||||
|
# 兼容旧文档无 status;软删后 status=deleted
|
||||||
|
"$or": [
|
||||||
|
{"status": {"$exists": False}},
|
||||||
|
{"status": None},
|
||||||
|
{"status": {"$ne": "deleted"}},
|
||||||
|
],
|
||||||
|
}
|
||||||
)
|
)
|
||||||
.sort("seq", -1)
|
.sort("seq", -1)
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
@@ -203,6 +241,24 @@ class MongoMessageRepository(MessageRepository):
|
|||||||
rows.reverse()
|
rows.reverse()
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
async def soft_delete_by_thread(
|
||||||
|
self, company_id: int, user_id: str, thread_id: str
|
||||||
|
) -> int:
|
||||||
|
result = await self._col.update_many(
|
||||||
|
{
|
||||||
|
"company_id": company_id,
|
||||||
|
"user_id": user_id,
|
||||||
|
"thread_id": thread_id,
|
||||||
|
"$or": [
|
||||||
|
{"status": {"$exists": False}},
|
||||||
|
{"status": None},
|
||||||
|
{"status": {"$ne": "deleted"}},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
|
||||||
|
)
|
||||||
|
return int(result.modified_count or 0)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
||||||
return ChatMessage(
|
return ChatMessage(
|
||||||
|
|||||||
@@ -7,8 +7,9 @@ import json
|
|||||||
import redis.asyncio as redis
|
import redis.asyncio as redis
|
||||||
|
|
||||||
from config.settings import Settings
|
from config.settings import Settings
|
||||||
from domain.models import LlmRuntimeConfig
|
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
|
||||||
from domain.ports import LlmRuntimeCache
|
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
|
||||||
|
from infrastructure.llm.api_style import normalize_api_style
|
||||||
|
|
||||||
|
|
||||||
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||||
@@ -43,6 +44,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
||||||
extra_headers=data.get("extra_headers") or {},
|
extra_headers=data.get("extra_headers") or {},
|
||||||
context_window=_optional_int(data.get("context_window")),
|
context_window=_optional_int(data.get("context_window")),
|
||||||
|
api_style=normalize_api_style(data.get("api_style")),
|
||||||
)
|
)
|
||||||
if model and cfg.model and cfg.model != model:
|
if model and cfg.model and cfg.model != model:
|
||||||
return None
|
return None
|
||||||
@@ -63,6 +65,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
"model": config.model,
|
"model": config.model,
|
||||||
"extra_headers": config.extra_headers,
|
"extra_headers": config.extra_headers,
|
||||||
"context_window": config.context_window,
|
"context_window": config.context_window,
|
||||||
|
"api_style": normalize_api_style(config.api_style),
|
||||||
}
|
}
|
||||||
await self._r.set(
|
await self._r.set(
|
||||||
self._key(company_id, config.provider_id, config.model),
|
self._key(company_id, config.provider_id, config.model),
|
||||||
@@ -96,6 +99,53 @@ def get_redis(settings: Settings) -> redis.Redis:
|
|||||||
return _redis
|
return _redis
|
||||||
|
|
||||||
|
|
||||||
|
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
|
||||||
|
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
|
||||||
|
|
||||||
|
def __init__(self, client: redis.Redis) -> None:
|
||||||
|
self._r = client
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _key(*, provider_id: int | None, base_url: str) -> str:
|
||||||
|
if provider_id is not None and int(provider_id) > 0:
|
||||||
|
return f"agent:llm:cap:p:{int(provider_id)}"
|
||||||
|
url = (base_url or "").rstrip("/").lower()
|
||||||
|
return f"agent:llm:cap:u:{url}"
|
||||||
|
|
||||||
|
async def get(
|
||||||
|
self, *, provider_id: int | None, base_url: str
|
||||||
|
) -> LlmProtocolCapability | None:
|
||||||
|
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return LlmProtocolCapability(
|
||||||
|
responses=data.get("responses"),
|
||||||
|
store=data.get("store"),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def set(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
provider_id: int | None,
|
||||||
|
base_url: str,
|
||||||
|
capability: LlmProtocolCapability,
|
||||||
|
ttl_seconds: int,
|
||||||
|
) -> None:
|
||||||
|
payload = {
|
||||||
|
"responses": capability.responses,
|
||||||
|
"store": capability.store,
|
||||||
|
}
|
||||||
|
await self._r.set(
|
||||||
|
self._key(provider_id=provider_id, base_url=base_url),
|
||||||
|
json.dumps(payload),
|
||||||
|
ex=max(60, ttl_seconds),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def close_redis() -> None:
|
async def close_redis() -> None:
|
||||||
global _redis
|
global _redis
|
||||||
if _redis is not None:
|
if _redis is not None:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ motor>=3.6.0
|
|||||||
redis>=5.2.0
|
redis>=5.2.0
|
||||||
httpx>=0.27.0
|
httpx>=0.27.0
|
||||||
langchain-core>=0.3.0
|
langchain-core>=0.3.0
|
||||||
langchain-openai>=0.2.0
|
langchain-openai>=0.3.26
|
||||||
langchain-mcp-adapters>=0.1.0
|
langchain-mcp-adapters>=0.1.0
|
||||||
langgraph>=0.2.0
|
langgraph>=0.2.0
|
||||||
sse-starlette>=2.1.0
|
sse-starlette>=2.1.0
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""协议探测规划与错误分类。"""
|
||||||
|
|
||||||
|
from domain.models import LlmProtocolCapability
|
||||||
|
from infrastructure.llm.api_style import (
|
||||||
|
ProtocolAttempt,
|
||||||
|
classify_protocol_error,
|
||||||
|
normalize_api_style,
|
||||||
|
plan_protocol_attempts,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_api_style():
|
||||||
|
assert normalize_api_style(None) == "auto"
|
||||||
|
assert normalize_api_style("Responses") == "responses"
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_unknown_auto_tries_store_full_history_then_fallbacks():
|
||||||
|
attempts = plan_protocol_attempts("auto", None, has_chain_id=True)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, True, False)
|
||||||
|
assert ProtocolAttempt(True, False, False) in attempts
|
||||||
|
assert ProtocolAttempt(False, False, False) in attempts
|
||||||
|
assert not any(a.use_chain for a in attempts)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_true_allows_chain():
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=True)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, True, True)
|
||||||
|
assert ProtocolAttempt(True, True, False) in attempts
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_false_prefers_stateless_responses_then_completions():
|
||||||
|
"""store 证伪:无状态 Responses(全量历史)→ Completions。"""
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=True)
|
||||||
|
assert attempts == [
|
||||||
|
ProtocolAttempt(True, False, False),
|
||||||
|
ProtocolAttempt(False, False, False),
|
||||||
|
]
|
||||||
|
assert not any(a.use_chain or a.use_store for a in attempts)
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_store_false_forced_responses_same_ladder():
|
||||||
|
cap = LlmProtocolCapability(responses=True, store=False)
|
||||||
|
attempts = plan_protocol_attempts("responses", cap, has_chain_id=False)
|
||||||
|
assert attempts[0] == ProtocolAttempt(True, False, False)
|
||||||
|
assert ProtocolAttempt(False, False, False) in attempts
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_completions_only():
|
||||||
|
assert plan_protocol_attempts("completions", None, has_chain_id=True) == [
|
||||||
|
ProtocolAttempt(False, False, False)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_responses_known_unsupported_falls_to_completions():
|
||||||
|
cap = LlmProtocolCapability(responses=False, store=False)
|
||||||
|
attempts = plan_protocol_attempts("auto", cap, has_chain_id=False)
|
||||||
|
assert attempts == [ProtocolAttempt(False, False, False)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_protocol_error():
|
||||||
|
assert classify_protocol_error(Exception("Invalid previous_response_id")) == "chain"
|
||||||
|
assert (
|
||||||
|
classify_protocol_error(Exception("Unsupported parameter: store")) == "store"
|
||||||
|
)
|
||||||
|
assert classify_protocol_error(Exception("404 /v1/responses not found")) == "responses"
|
||||||
|
assert classify_protocol_error(Exception("rate limit")) == "other"
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""会话链选型匹配。"""
|
||||||
|
|
||||||
|
from domain.models import LlmResponseChain, LlmRuntimeConfig
|
||||||
|
from application.chat_service import _usable_chain_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_usable_chain_id_matches():
|
||||||
|
llm = LlmRuntimeConfig(
|
||||||
|
base_url="https://api.openai.com/v1",
|
||||||
|
api_key="k",
|
||||||
|
model="gpt-4o-mini",
|
||||||
|
provider_id=3,
|
||||||
|
api_style="auto",
|
||||||
|
)
|
||||||
|
chain = LlmResponseChain(
|
||||||
|
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||||
|
)
|
||||||
|
assert _usable_chain_id(chain, llm) == "resp_abc"
|
||||||
|
|
||||||
|
|
||||||
|
def test_usable_chain_id_clears_on_model_switch():
|
||||||
|
llm = LlmRuntimeConfig(
|
||||||
|
base_url="https://api.openai.com/v1",
|
||||||
|
api_key="k",
|
||||||
|
model="gpt-4o",
|
||||||
|
provider_id=3,
|
||||||
|
api_style="auto",
|
||||||
|
)
|
||||||
|
chain = LlmResponseChain(
|
||||||
|
provider_id=3, model="gpt-4o-mini", previous_response_id="resp_abc"
|
||||||
|
)
|
||||||
|
assert _usable_chain_id(chain, llm) is None
|
||||||
@@ -16,6 +16,7 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
|||||||
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
||||||
|
`api_style` varchar(32) NOT NULL DEFAULT 'auto' COMMENT 'API协议:auto|completions|responses',
|
||||||
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
-- ========================================
|
||||||
|
-- 电商-内部店铺运营团队
|
||||||
|
-- ec_op_team / ec_op_team_member
|
||||||
|
--
|
||||||
|
-- 边界
|
||||||
|
-- · 团队是公司级资源,是后续数据范围的收口单位(成员 → 团队 → 店铺)
|
||||||
|
-- · 成员表关联 org_company_member,公司成员退出/硬删时可级联摘除
|
||||||
|
-- · 成员表只表达「谁在哪个团队、什么角色」,不挂店铺
|
||||||
|
-- · 店铺分配另做:计划在 ec_shop 加 op_team_id(一店一团队、一团队多店)
|
||||||
|
--
|
||||||
|
-- 角色(ec_op_team_member.role)
|
||||||
|
-- · 1=负责人 2=成员
|
||||||
|
-- · 同一公司成员可加入多个团队;同一团队同一公司成员一行
|
||||||
|
-- · 一团队建议仅一名负责人(应用层保证,便于日后收权限/审批)
|
||||||
|
-- ========================================
|
||||||
|
|
||||||
|
-- ----------------------------
|
||||||
|
-- 运营团队表
|
||||||
|
-- ----------------------------
|
||||||
|
DROP TABLE IF EXISTS `ec_op_team_member`;
|
||||||
|
DROP TABLE IF EXISTS `ec_op_team`;
|
||||||
|
CREATE TABLE `ec_op_team` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '团队ID',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
|
||||||
|
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '团队名称',
|
||||||
|
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
|
||||||
|
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1启用',
|
||||||
|
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||||
|
PRIMARY KEY (`id`) USING BTREE,
|
||||||
|
UNIQUE INDEX `uk_ec_op_team_company_name`(`company_id` ASC, `name` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_company`(`company_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_status`(`status` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_creator`(`create_by` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_updater`(`update_by` ASC) USING BTREE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||||
|
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-内部店铺运营团队' ;
|
||||||
|
|
||||||
|
-- ----------------------------
|
||||||
|
-- 运营团队成员表(挂公司成员,便于级联)
|
||||||
|
-- ----------------------------
|
||||||
|
CREATE TABLE `ec_op_team_member` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '成员记录ID',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余,便于按租户查)',
|
||||||
|
`team_id` bigint UNSIGNED NOT NULL COMMENT '团队ID',
|
||||||
|
`company_member_id` bigint NOT NULL COMMENT '公司成员ID(org_company_member.id)',
|
||||||
|
`role` tinyint NOT NULL DEFAULT 2 COMMENT '角色:1负责人 2成员',
|
||||||
|
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1正常',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||||
|
PRIMARY KEY (`id`) USING BTREE,
|
||||||
|
UNIQUE INDEX `uk_ec_op_team_member_team_cm`(`team_id` ASC, `company_member_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_company`(`company_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_cm`(`company_member_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_role`(`team_id` ASC, `role` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_member_creator`(`create_by` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_member_updater`(`update_by` ASC) USING BTREE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_team` FOREIGN KEY (`team_id`) REFERENCES `ec_op_team` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_cm` FOREIGN KEY (`company_member_id`) REFERENCES `org_company_member` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||||
|
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-运营团队成员' ;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
-- ========================================
|
-- ========================================
|
||||||
-- 电商-店铺域设计
|
-- 电商-店铺域设计
|
||||||
-- ec_shop / ec_shop_monthly_target / ec_shop_product_relation
|
-- ec_shop / ec_shop_monthly_target / ec_shop_product_relation
|
||||||
|
-- 运营团队(后续店铺分配 / 数据范围):见 ec_op_team_design.sql
|
||||||
-- ========================================
|
-- ========================================
|
||||||
|
|
||||||
-- ----------------------------
|
-- ----------------------------
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- 提供商增加 API 协议风格:auto | completions | responses
|
||||||
|
ALTER TABLE `agent_company_llm_provider`
|
||||||
|
ADD COLUMN `api_style` varchar(32) NOT NULL DEFAULT 'auto'
|
||||||
|
COMMENT 'API协议:auto=按base_url推断;completions;responses'
|
||||||
|
AFTER `display_name`;
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
-- 内部店铺运营团队 + 成员;菜单挂「经营店铺」
|
||||||
|
-- 已有经营店铺菜单的公司/岗位同步放开,便于公司 owner 直接使用
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `ec_op_team` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '团队ID',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
|
||||||
|
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '团队名称',
|
||||||
|
`remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '备注',
|
||||||
|
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1启用',
|
||||||
|
`sort_order` int NOT NULL DEFAULT 0 COMMENT '排序',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||||
|
PRIMARY KEY (`id`) USING BTREE,
|
||||||
|
UNIQUE INDEX `uk_ec_op_team_company_name`(`company_id` ASC, `name` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_company`(`company_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_status`(`status` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_creator`(`create_by` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_updater`(`update_by` ASC) USING BTREE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||||
|
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-内部店铺运营团队';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `ec_op_team_member` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '成员记录ID',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID(冗余,便于按租户查)',
|
||||||
|
`team_id` bigint UNSIGNED NOT NULL COMMENT '团队ID',
|
||||||
|
`user_id` bigint UNSIGNED NOT NULL COMMENT '用户ID',
|
||||||
|
`role` tinyint NOT NULL DEFAULT 2 COMMENT '角色:1负责人 2成员',
|
||||||
|
`status` tinyint NOT NULL DEFAULT 1 COMMENT '状态:0停用 1正常',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`create_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL DEFAULT NULL COMMENT '更新人ID',
|
||||||
|
PRIMARY KEY (`id`) USING BTREE,
|
||||||
|
UNIQUE INDEX `uk_ec_op_team_member_team_user`(`team_id` ASC, `user_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_company`(`company_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_user`(`user_id` ASC) USING BTREE,
|
||||||
|
INDEX `idx_ec_op_team_member_role`(`team_id` ASC, `role` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_member_creator`(`create_by` ASC) USING BTREE,
|
||||||
|
INDEX `fk_ec_op_team_member_updater`(`update_by` ASC) USING BTREE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_team` FOREIGN KEY (`team_id`) REFERENCES `ec_op_team` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_user` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
|
||||||
|
CONSTRAINT `fk_ec_op_team_member_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
|
||||||
|
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '电商-运营团队成员';
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3380, (SELECT id FROM `sys_permission` WHERE `code` = 'ec' LIMIT 1), 'ec:op-team', '运营团队', 'module', 1, '', 45
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3380 OR `code` = 'ec:op-team');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3381, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:read', '查看', 'api', 1, '', 1
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3381 OR `code` = 'ec:op-team:read');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3382, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:create', '创建', 'api', 1, '', 2
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3382 OR `code` = 'ec:op-team:create');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3383, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:update', '更新', 'api', 1, '', 3
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3383 OR `code` = 'ec:op-team:update');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3384, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:delete', '删除', 'api', 1, '', 4
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3384 OR `code` = 'ec:op-team:delete');
|
||||||
|
|
||||||
|
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||||
|
SELECT 14011, (SELECT id FROM `sys_menu` WHERE `id` = 7 OR `title` = '经营店铺' OR `route_name` = 'ShopCatalog' LIMIT 1), 0, 'OpTeamManagement', '运营团队', '/ec/shop/op-team', '/ec/shop/op-team/index', '', 'lucide:users', 'menu', 1, 1, 1, 5
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14011 OR `route_name` = 'OpTeamManagement');
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id
|
||||||
|
FROM `sys_menu` m
|
||||||
|
JOIN `sys_permission` p ON p.code LIKE 'ec:op-team:%'
|
||||||
|
WHERE m.route_name = 'OpTeamManagement' OR m.id = 14011;
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `org_company_menu` (`company_id`, `menu_id`, `status`)
|
||||||
|
SELECT DISTINCT cm.`company_id`, 14011, 1
|
||||||
|
FROM `org_company_menu` cm
|
||||||
|
WHERE cm.`menu_id` IN (7, 14010);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `org_company_permission` (`company_id`, `permission_id`)
|
||||||
|
SELECT DISTINCT cm.`company_id`, p.`id`
|
||||||
|
FROM `org_company_menu` cm
|
||||||
|
JOIN `sys_permission` p ON p.`code` LIKE 'ec:op-team:%'
|
||||||
|
WHERE cm.`menu_id` IN (7, 14010, 14011);
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `org_position_menu` (`position_id`, `menu_id`)
|
||||||
|
SELECT pm.`position_id`, 14011
|
||||||
|
FROM `org_position_menu` pm
|
||||||
|
WHERE pm.`menu_id` = 14010;
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `org_position_permission` (`position_id`, `permission_id`)
|
||||||
|
SELECT DISTINCT pp.`position_id`, p.`id`
|
||||||
|
FROM `org_position_permission` pp
|
||||||
|
JOIN `sys_permission` shop ON shop.`id` = pp.`permission_id` AND shop.`code` LIKE 'ec:shop:%'
|
||||||
|
JOIN `sys_permission` p ON p.`code` LIKE 'ec:op-team:%';
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- 运营团队成员:user_id → company_member_id(挂 org_company_member,支持级联)
|
||||||
|
|
||||||
|
-- 1) 可空列,便于回填
|
||||||
|
ALTER TABLE `ec_op_team_member`
|
||||||
|
ADD COLUMN `company_member_id` bigint NULL COMMENT '公司成员ID(org_company_member.id)' AFTER `team_id`;
|
||||||
|
|
||||||
|
-- 2) 按公司+用户回填
|
||||||
|
UPDATE `ec_op_team_member` m
|
||||||
|
INNER JOIN `org_company_member` cm
|
||||||
|
ON cm.`company_id` = m.`company_id`
|
||||||
|
AND cm.`user_id` = m.`user_id`
|
||||||
|
SET m.`company_member_id` = cm.`id`;
|
||||||
|
|
||||||
|
-- 3) 无法回填的脏行删除
|
||||||
|
DELETE FROM `ec_op_team_member` WHERE `company_member_id` IS NULL;
|
||||||
|
|
||||||
|
-- 4) 换约束与列
|
||||||
|
ALTER TABLE `ec_op_team_member`
|
||||||
|
DROP FOREIGN KEY `fk_ec_op_team_member_user`,
|
||||||
|
DROP INDEX `uk_ec_op_team_member_team_user`,
|
||||||
|
DROP INDEX `idx_ec_op_team_member_user`,
|
||||||
|
DROP COLUMN `user_id`,
|
||||||
|
MODIFY COLUMN `company_member_id` bigint NOT NULL COMMENT '公司成员ID(org_company_member.id)',
|
||||||
|
ADD UNIQUE INDEX `uk_ec_op_team_member_team_cm`(`team_id` ASC, `company_member_id` ASC) USING BTREE,
|
||||||
|
ADD INDEX `idx_ec_op_team_member_cm`(`company_member_id` ASC) USING BTREE,
|
||||||
|
ADD CONSTRAINT `fk_ec_op_team_member_cm`
|
||||||
|
FOREIGN KEY (`company_member_id`) REFERENCES `org_company_member` (`id`)
|
||||||
|
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
+5
@@ -16,4 +16,9 @@ public class CreateAgentLlmProviderDTO {
|
|||||||
private String apiKey;
|
private String apiKey;
|
||||||
|
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses;空则 auto
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -16,4 +16,9 @@ public class UpdateAgentLlmProviderDTO {
|
|||||||
|
|
||||||
/** 传 null 表示不改;传空串可清空备注 */
|
/** 传 null 表示不改;传空串可清空备注 */
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses;null 不改
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -33,6 +33,12 @@ public class AgentCompanyLlmProviderPO {
|
|||||||
@TableField("display_name")
|
@TableField("display_name")
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
@TableField("api_style")
|
||||||
|
private String apiStyle;
|
||||||
|
|
||||||
@TableField("extra_headers_json")
|
@TableField("extra_headers_json")
|
||||||
private String extraHeadersJson;
|
private String extraHeadersJson;
|
||||||
|
|
||||||
|
|||||||
+4
@@ -16,5 +16,9 @@ public class AgentLlmProviderVO {
|
|||||||
private String displayName;
|
private String displayName;
|
||||||
private String apiKeyMasked;
|
private String apiKeyMasked;
|
||||||
private String updateTime;
|
private String updateTime;
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -15,5 +15,9 @@ public class AgentLlmRuntimeVO {
|
|||||||
private String model;
|
private String model;
|
||||||
/** 上下文窗口 token;可能为 null */
|
/** 上下文窗口 token;可能为 null */
|
||||||
private Integer contextWindow;
|
private Integer contextWindow;
|
||||||
|
/**
|
||||||
|
* API 协议:auto | completions | responses
|
||||||
|
*/
|
||||||
|
private String apiStyle;
|
||||||
private Map<String, String> extraHeaders;
|
private Map<String, String> extraHeaders;
|
||||||
}
|
}
|
||||||
|
|||||||
+20
@@ -98,6 +98,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||||
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
|
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||||
po.setCreateBy(userId);
|
po.setCreateBy(userId);
|
||||||
po.setUpdateBy(userId);
|
po.setUpdateBy(userId);
|
||||||
providerMapper.insert(po);
|
providerMapper.insert(po);
|
||||||
@@ -123,6 +124,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
if (dto.getDisplayName() != null) {
|
if (dto.getDisplayName() != null) {
|
||||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
}
|
}
|
||||||
|
if (dto.getApiStyle() != null) {
|
||||||
|
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||||
|
}
|
||||||
existing.setUpdateBy(userId);
|
existing.setUpdateBy(userId);
|
||||||
providerMapper.updateById(existing);
|
providerMapper.updateById(existing);
|
||||||
evictRuntimeCache(companyId);
|
evictRuntimeCache(companyId);
|
||||||
@@ -432,6 +436,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||||
vo.setModel(model.getModel());
|
vo.setModel(model.getModel());
|
||||||
vo.setContextWindow(model.getContextWindow());
|
vo.setContextWindow(model.getContextWindow());
|
||||||
|
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
@@ -450,6 +455,17 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String normalizeApiStyle(String raw) {
|
||||||
|
if (!StringUtils.hasText(raw)) {
|
||||||
|
return "auto";
|
||||||
|
}
|
||||||
|
String s = raw.trim().toLowerCase();
|
||||||
|
if ("auto".equals(s) || "completions".equals(s) || "responses".equals(s)) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
throw new BusinessException("apiStyle 必须是 auto / completions / responses");
|
||||||
|
}
|
||||||
|
|
||||||
private static Integer normalizeContextWindow(Integer raw) {
|
private static Integer normalizeContextWindow(Integer raw) {
|
||||||
if (raw == null || raw <= 0) {
|
if (raw == null || raw <= 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -546,6 +562,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
vo.setConfigured(true);
|
vo.setConfigured(true);
|
||||||
vo.setBaseUrl(provider.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setDisplayName(provider.getDisplayName());
|
vo.setDisplayName(provider.getDisplayName());
|
||||||
|
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||||
if (provider.getUpdateTime() != null) {
|
if (provider.getUpdateTime() != null) {
|
||||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||||
@@ -570,6 +587,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
payload.put("api_key", runtime.getApiKey());
|
payload.put("api_key", runtime.getApiKey());
|
||||||
payload.put("model", runtime.getModel());
|
payload.put("model", runtime.getModel());
|
||||||
payload.put("context_window", runtime.getContextWindow());
|
payload.put("context_window", runtime.getContextWindow());
|
||||||
|
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
|
||||||
payload.put("extra_headers",
|
payload.put("extra_headers",
|
||||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||||
stringRedisTemplate.opsForValue().set(
|
stringRedisTemplate.opsForValue().set(
|
||||||
@@ -612,6 +630,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
} else {
|
} else {
|
||||||
vo.setContextWindow(null);
|
vo.setContextWindow(null);
|
||||||
}
|
}
|
||||||
|
Object style = map.get("api_style");
|
||||||
|
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
|
||||||
Object headers = map.get("extra_headers");
|
Object headers = map.get("extra_headers");
|
||||||
if (headers instanceof Map<?, ?> m) {
|
if (headers instanceof Map<?, ?> m) {
|
||||||
Map<String, String> h = new HashMap<>();
|
Map<String, String> h = new HashMap<>();
|
||||||
|
|||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.controller;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.CreateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.OpTeamFilterDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.UpdateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.vo.OpTeamVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.service.OpTeamService;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 运营团队接口。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ec/op-team")
|
||||||
|
public class OpTeamController {
|
||||||
|
|
||||||
|
private final OpTeamService opTeamService;
|
||||||
|
|
||||||
|
public OpTeamController(OpTeamService opTeamService) {
|
||||||
|
this.opTeamService = opTeamService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/create")
|
||||||
|
@RequirePermission(value = "ec:op-team:create", description = "创建运营团队", allowSuper = true)
|
||||||
|
public ApiResponse<OpTeamVO> create(@Valid @RequestBody CreateOpTeamDTO dto) {
|
||||||
|
return ApiResponse.success("运营团队创建成功", opTeamService.createTeam(dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/update/{id}")
|
||||||
|
@RequirePermission(value = "ec:op-team:update", description = "更新运营团队", allowSuper = true)
|
||||||
|
public ApiResponse<OpTeamVO> update(@Valid @RequestBody UpdateOpTeamDTO dto, @PathVariable Long id) {
|
||||||
|
return ApiResponse.success("运营团队更新成功", opTeamService.updateTeam(dto, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/delete/{id}")
|
||||||
|
@RequirePermission(value = "ec:op-team:delete", description = "删除运营团队", allowSuper = true)
|
||||||
|
public ApiResponse<Void> delete(@PathVariable Long id) {
|
||||||
|
opTeamService.deleteTeam(id);
|
||||||
|
return ApiResponse.success("运营团队删除成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/list")
|
||||||
|
@RequirePermission(value = "ec:op-team:read", description = "查询运营团队列表", allowSuper = true)
|
||||||
|
public ApiResponse<PageResultVO<OpTeamVO>> list(@Valid @RequestBody PageQueryDTO<OpTeamFilterDTO> pageQuery) {
|
||||||
|
return ApiResponse.success("获取运营团队列表成功", opTeamService.getTeamPage(pageQuery));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/all")
|
||||||
|
@RequirePermission(value = "ec:op-team:read", description = "查询全部运营团队", allowSuper = true)
|
||||||
|
public ApiResponse<List<OpTeamVO>> all() {
|
||||||
|
return ApiResponse.success("获取全部运营团队成功", opTeamService.getAllTeams());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/detail/{id}")
|
||||||
|
@RequirePermission(value = "ec:op-team:read", description = "查询运营团队详情", allowSuper = true)
|
||||||
|
public ApiResponse<OpTeamVO> detail(@PathVariable Long id) {
|
||||||
|
return ApiResponse.success("获取成功", opTeamService.getTeamDetail(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.po.OpTeamPO;
|
||||||
|
|
||||||
|
/** 运营团队 Mapper。 */
|
||||||
|
@Mapper
|
||||||
|
public interface OpTeamMapper extends BaseMapper<OpTeamPO> {
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member;
|
||||||
|
|
||||||
|
/** 运营团队成员角色:1负责人 2成员。 */
|
||||||
|
public final class OpTeamMemberRoles {
|
||||||
|
|
||||||
|
public static final int LEADER = 1;
|
||||||
|
public static final int MEMBER = 2;
|
||||||
|
|
||||||
|
private OpTeamMemberRoles() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String displayName(Integer role) {
|
||||||
|
if (role != null && role == LEADER) {
|
||||||
|
return "负责人";
|
||||||
|
}
|
||||||
|
return "成员";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isValid(Integer role) {
|
||||||
|
return role != null && (role == LEADER || role == MEMBER);
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.controller;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.AddOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.RemoveOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.UpdateOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamCandidateVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamMemberVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.service.OpTeamMemberService;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 运营团队成员接口。 */
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ec/op-team-member")
|
||||||
|
public class OpTeamMemberController {
|
||||||
|
|
||||||
|
private final OpTeamMemberService opTeamMemberService;
|
||||||
|
|
||||||
|
public OpTeamMemberController(OpTeamMemberService opTeamMemberService) {
|
||||||
|
this.opTeamMemberService = opTeamMemberService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/add")
|
||||||
|
@RequirePermission(value = "ec:op-team:update", description = "添加运营团队成员", allowSuper = true)
|
||||||
|
public ApiResponse<OpTeamMemberVO> add(@Valid @RequestBody AddOpTeamMemberDTO dto) {
|
||||||
|
return ApiResponse.success("成员添加成功", opTeamMemberService.addMember(dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/update/{id}")
|
||||||
|
@RequirePermission(value = "ec:op-team:update", description = "更新运营团队成员角色", allowSuper = true)
|
||||||
|
public ApiResponse<OpTeamMemberVO> updateRole(@PathVariable Long id,
|
||||||
|
@Valid @RequestBody UpdateOpTeamMemberDTO dto) {
|
||||||
|
return ApiResponse.success("成员角色更新成功", opTeamMemberService.updateMemberRole(id, dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/remove")
|
||||||
|
@RequirePermission(value = "ec:op-team:update", description = "移除运营团队成员", allowSuper = true)
|
||||||
|
public ApiResponse<Void> remove(@Valid @RequestBody RemoveOpTeamMemberDTO dto) {
|
||||||
|
opTeamMemberService.removeMember(dto.getTeamId(), dto.getCompanyMemberId());
|
||||||
|
return ApiResponse.success("成员移除成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/team/{teamId}")
|
||||||
|
@RequirePermission(value = "ec:op-team:read", description = "查询运营团队成员", allowSuper = true)
|
||||||
|
public ApiResponse<List<OpTeamMemberVO>> listByTeam(@PathVariable Long teamId) {
|
||||||
|
return ApiResponse.success("获取成员列表成功", opTeamMemberService.listByTeamId(teamId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/candidates")
|
||||||
|
@RequirePermission(value = "ec:op-team:update", description = "查询可加入运营团队的本公司成员", allowSuper = true)
|
||||||
|
public ApiResponse<List<OpTeamCandidateVO>> candidates() {
|
||||||
|
return ApiResponse.success("获取候选人成功", opTeamMemberService.listCandidates());
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.po.OpTeamMemberPO;
|
||||||
|
|
||||||
|
/** 运营团队成员 Mapper。 */
|
||||||
|
@Mapper
|
||||||
|
public interface OpTeamMemberMapper extends BaseMapper<OpTeamMemberPO> {
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 添加运营团队成员。 */
|
||||||
|
@Data
|
||||||
|
public class AddOpTeamMemberDTO {
|
||||||
|
|
||||||
|
@NotNull(message = "团队ID不能为空")
|
||||||
|
private Long teamId;
|
||||||
|
|
||||||
|
@NotNull(message = "公司成员ID不能为空")
|
||||||
|
private Long companyMemberId;
|
||||||
|
|
||||||
|
/** 1负责人 2成员,默认成员 */
|
||||||
|
private Integer role;
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 移除运营团队成员。 */
|
||||||
|
@Data
|
||||||
|
public class RemoveOpTeamMemberDTO {
|
||||||
|
|
||||||
|
@NotNull(message = "团队ID不能为空")
|
||||||
|
private Long teamId;
|
||||||
|
|
||||||
|
@NotNull(message = "公司成员ID不能为空")
|
||||||
|
private Long companyMemberId;
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 更新团队成员角色。 */
|
||||||
|
@Data
|
||||||
|
public class UpdateOpTeamMemberDTO {
|
||||||
|
|
||||||
|
@NotNull(message = "角色不能为空")
|
||||||
|
private Integer role;
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.po;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 运营团队成员(关联公司成员)。 */
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("ec_op_team_member")
|
||||||
|
public class OpTeamMemberPO {
|
||||||
|
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@TableField("company_id")
|
||||||
|
private Long companyId;
|
||||||
|
|
||||||
|
@TableField("team_id")
|
||||||
|
private Long teamId;
|
||||||
|
|
||||||
|
/** org_company_member.id */
|
||||||
|
@TableField("company_member_id")
|
||||||
|
private Long companyMemberId;
|
||||||
|
|
||||||
|
/** 1负责人 2成员 */
|
||||||
|
@TableField("role")
|
||||||
|
private Integer role;
|
||||||
|
|
||||||
|
/** 0停用 1正常 */
|
||||||
|
@TableField("status")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableField("create_by")
|
||||||
|
private Long createBy;
|
||||||
|
|
||||||
|
@TableField("update_by")
|
||||||
|
private Long updateBy;
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 可加入运营团队的本公司成员。 */
|
||||||
|
@Data
|
||||||
|
public class OpTeamCandidateVO {
|
||||||
|
|
||||||
|
/** 公司成员ID(加入团队的关联键) */
|
||||||
|
private Long companyMemberId;
|
||||||
|
private Long userId;
|
||||||
|
private String realName;
|
||||||
|
private String phone;
|
||||||
|
private String username;
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 运营团队成员展示。 */
|
||||||
|
@Data
|
||||||
|
public class OpTeamMemberVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private Long companyId;
|
||||||
|
private Long teamId;
|
||||||
|
private String teamName;
|
||||||
|
/** 公司成员ID */
|
||||||
|
private Long companyMemberId;
|
||||||
|
/** 展示用用户ID(经公司成员解析) */
|
||||||
|
private Long userId;
|
||||||
|
private Integer role;
|
||||||
|
private String roleName;
|
||||||
|
private Integer status;
|
||||||
|
private String realName;
|
||||||
|
private String phone;
|
||||||
|
private String username;
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.AddOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.UpdateOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.po.OpTeamMemberPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamCandidateVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamMemberVO;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 运营团队成员用例。 */
|
||||||
|
public interface OpTeamMemberService extends IService<OpTeamMemberPO> {
|
||||||
|
|
||||||
|
OpTeamMemberVO addMember(AddOpTeamMemberDTO dto);
|
||||||
|
|
||||||
|
OpTeamMemberVO updateMemberRole(Long id, UpdateOpTeamMemberDTO dto);
|
||||||
|
|
||||||
|
void removeMember(Long teamId, Long companyMemberId);
|
||||||
|
|
||||||
|
/** 公司成员退出时,软删其全部运营团队成员记录。 */
|
||||||
|
void deactivateByCompanyMemberId(Long companyMemberId);
|
||||||
|
|
||||||
|
List<OpTeamMemberVO> listByTeamId(Long teamId);
|
||||||
|
|
||||||
|
List<OpTeamCandidateVO> listCandidates();
|
||||||
|
}
|
||||||
+238
@@ -0,0 +1,238 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.member.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.mapper.OpTeamMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.OpTeamMemberRoles;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.mapper.OpTeamMemberMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.AddOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.dto.UpdateOpTeamMemberDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.po.OpTeamMemberPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamCandidateVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.vo.OpTeamMemberVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.service.OpTeamMemberService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.po.OpTeamPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.po.CompanyMemberPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.vo.CompanyMemberVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.mapper.UserMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/** 团队成员编排:关联公司成员;新负责人会把原负责人降为成员。 */
|
||||||
|
@Service
|
||||||
|
public class OpTeamMemberServiceImpl extends ServiceImpl<OpTeamMemberMapper, OpTeamMemberPO>
|
||||||
|
implements OpTeamMemberService {
|
||||||
|
|
||||||
|
private final CurrentUserContext currentUserContext;
|
||||||
|
private final OpTeamMapper opTeamMapper;
|
||||||
|
private final UserMapper userMapper;
|
||||||
|
private final CompanyMemberService companyMemberService;
|
||||||
|
|
||||||
|
public OpTeamMemberServiceImpl(CurrentUserContext currentUserContext,
|
||||||
|
OpTeamMapper opTeamMapper,
|
||||||
|
UserMapper userMapper,
|
||||||
|
CompanyMemberService companyMemberService) {
|
||||||
|
this.currentUserContext = currentUserContext;
|
||||||
|
this.opTeamMapper = opTeamMapper;
|
||||||
|
this.userMapper = userMapper;
|
||||||
|
this.companyMemberService = companyMemberService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public OpTeamMemberVO addMember(AddOpTeamMemberDTO dto) {
|
||||||
|
OpTeamPO team = requireTeam(dto.getTeamId());
|
||||||
|
CompanyMemberPO companyMember = requireActiveCompanyMember(
|
||||||
|
dto.getCompanyMemberId(), team.getCompanyId());
|
||||||
|
int role = dto.getRole() == null ? OpTeamMemberRoles.MEMBER : dto.getRole();
|
||||||
|
if (!OpTeamMemberRoles.isValid(role)) {
|
||||||
|
throw new BusinessException("无效的成员角色");
|
||||||
|
}
|
||||||
|
|
||||||
|
LambdaQueryWrapper<OpTeamMemberPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamMemberPO::getTeamId, dto.getTeamId())
|
||||||
|
.eq(OpTeamMemberPO::getCompanyMemberId, dto.getCompanyMemberId());
|
||||||
|
OpTeamMemberPO existing = this.getOne(wrapper);
|
||||||
|
if (existing != null && existing.getStatus() != null && existing.getStatus() == 1) {
|
||||||
|
throw new BusinessException("该成员已在团队中");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (role == OpTeamMemberRoles.LEADER) {
|
||||||
|
demoteCurrentLeader(dto.getTeamId(), existing == null ? null : existing.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing != null) {
|
||||||
|
existing.setStatus(1);
|
||||||
|
existing.setRole(role);
|
||||||
|
existing.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.updateById(existing);
|
||||||
|
return convertToVO(existing, team, companyMember);
|
||||||
|
}
|
||||||
|
|
||||||
|
OpTeamMemberPO member = new OpTeamMemberPO();
|
||||||
|
member.setCompanyId(team.getCompanyId());
|
||||||
|
member.setTeamId(dto.getTeamId());
|
||||||
|
member.setCompanyMemberId(dto.getCompanyMemberId());
|
||||||
|
member.setRole(role);
|
||||||
|
member.setStatus(1);
|
||||||
|
member.setCreateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.save(member);
|
||||||
|
return convertToVO(member, team, companyMember);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public OpTeamMemberVO updateMemberRole(Long id, UpdateOpTeamMemberDTO dto) {
|
||||||
|
if (!OpTeamMemberRoles.isValid(dto.getRole())) {
|
||||||
|
throw new BusinessException("无效的成员角色");
|
||||||
|
}
|
||||||
|
OpTeamMemberPO member = this.getById(id);
|
||||||
|
if (member == null || member.getStatus() == null || member.getStatus() != 1) {
|
||||||
|
throw new BusinessException("成员不存在");
|
||||||
|
}
|
||||||
|
OpTeamPO team = requireTeam(member.getTeamId());
|
||||||
|
if (dto.getRole() == OpTeamMemberRoles.LEADER) {
|
||||||
|
demoteCurrentLeader(member.getTeamId(), member.getId());
|
||||||
|
}
|
||||||
|
member.setRole(dto.getRole());
|
||||||
|
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.updateById(member);
|
||||||
|
return convertToVO(member, team, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void removeMember(Long teamId, Long companyMemberId) {
|
||||||
|
requireTeam(teamId);
|
||||||
|
LambdaQueryWrapper<OpTeamMemberPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamMemberPO::getTeamId, teamId)
|
||||||
|
.eq(OpTeamMemberPO::getCompanyMemberId, companyMemberId)
|
||||||
|
.eq(OpTeamMemberPO::getStatus, 1);
|
||||||
|
OpTeamMemberPO member = this.getOne(wrapper);
|
||||||
|
if (member == null) {
|
||||||
|
throw new BusinessException("成员不存在");
|
||||||
|
}
|
||||||
|
member.setStatus(0);
|
||||||
|
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.updateById(member);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void deactivateByCompanyMemberId(Long companyMemberId) {
|
||||||
|
if (companyMemberId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LambdaUpdateWrapper<OpTeamMemberPO> wrapper = new LambdaUpdateWrapper<>();
|
||||||
|
wrapper.eq(OpTeamMemberPO::getCompanyMemberId, companyMemberId)
|
||||||
|
.eq(OpTeamMemberPO::getStatus, 1)
|
||||||
|
.set(OpTeamMemberPO::getStatus, 0)
|
||||||
|
.set(OpTeamMemberPO::getUpdateBy, currentUserContext.getCurrentUserId());
|
||||||
|
this.update(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OpTeamMemberVO> listByTeamId(Long teamId) {
|
||||||
|
OpTeamPO team = requireTeam(teamId);
|
||||||
|
LambdaQueryWrapper<OpTeamMemberPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamMemberPO::getTeamId, teamId)
|
||||||
|
.eq(OpTeamMemberPO::getStatus, 1);
|
||||||
|
return this.list(wrapper).stream()
|
||||||
|
.map(m -> convertToVO(m, team, null))
|
||||||
|
.sorted(Comparator
|
||||||
|
.comparing((OpTeamMemberVO vo) -> !Objects.equals(vo.getRole(), OpTeamMemberRoles.LEADER))
|
||||||
|
.thenComparing(OpTeamMemberVO::getId))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OpTeamCandidateVO> listCandidates() {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
return companyMemberService.getByCompanyId(companyId).stream()
|
||||||
|
.map(this::toCandidate)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamPO requireTeam(Long teamId) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
OpTeamPO team = opTeamMapper.selectById(teamId);
|
||||||
|
if (team == null) {
|
||||||
|
throw new BusinessException("运营团队不存在");
|
||||||
|
}
|
||||||
|
if (!companyId.equals(team.getCompanyId())) {
|
||||||
|
throw new BusinessException("无权操作此运营团队");
|
||||||
|
}
|
||||||
|
return team;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 校验公司成员属于当前团队公司且在职。 */
|
||||||
|
private CompanyMemberPO requireActiveCompanyMember(Long companyMemberId, Long companyId) {
|
||||||
|
CompanyMemberPO member = companyMemberService.getById(companyMemberId);
|
||||||
|
if (member == null
|
||||||
|
|| member.getStatus() == null
|
||||||
|
|| member.getStatus() != 1
|
||||||
|
|| !companyId.equals(member.getCompanyId())) {
|
||||||
|
throw new BusinessException("该公司成员不可用或不属于本公司");
|
||||||
|
}
|
||||||
|
return member;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一团队仅一名负责人:新负责人上任时把原负责人降为成员。 */
|
||||||
|
private void demoteCurrentLeader(Long teamId, Long keepMemberId) {
|
||||||
|
LambdaUpdateWrapper<OpTeamMemberPO> wrapper = new LambdaUpdateWrapper<>();
|
||||||
|
wrapper.eq(OpTeamMemberPO::getTeamId, teamId)
|
||||||
|
.eq(OpTeamMemberPO::getRole, OpTeamMemberRoles.LEADER)
|
||||||
|
.eq(OpTeamMemberPO::getStatus, 1);
|
||||||
|
if (keepMemberId != null) {
|
||||||
|
wrapper.ne(OpTeamMemberPO::getId, keepMemberId);
|
||||||
|
}
|
||||||
|
wrapper.set(OpTeamMemberPO::getRole, OpTeamMemberRoles.MEMBER)
|
||||||
|
.set(OpTeamMemberPO::getUpdateBy, currentUserContext.getCurrentUserId());
|
||||||
|
this.update(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamMemberVO convertToVO(OpTeamMemberPO member, OpTeamPO team, CompanyMemberPO companyMember) {
|
||||||
|
OpTeamMemberVO vo = new OpTeamMemberVO();
|
||||||
|
BeanCopyUtils.copyProperties(member, vo);
|
||||||
|
vo.setRoleName(OpTeamMemberRoles.displayName(member.getRole()));
|
||||||
|
if (team != null) {
|
||||||
|
vo.setTeamName(team.getName());
|
||||||
|
}
|
||||||
|
CompanyMemberPO cm = companyMember;
|
||||||
|
if (cm == null && member.getCompanyMemberId() != null) {
|
||||||
|
cm = companyMemberService.getById(member.getCompanyMemberId());
|
||||||
|
}
|
||||||
|
if (cm != null) {
|
||||||
|
vo.setUserId(cm.getUserId());
|
||||||
|
if (cm.getUserId() != null) {
|
||||||
|
UserPO user = userMapper.selectById(cm.getUserId());
|
||||||
|
if (user != null) {
|
||||||
|
vo.setRealName(user.getRealName());
|
||||||
|
vo.setPhone(user.getPhone());
|
||||||
|
vo.setUsername(user.getUsername());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamCandidateVO toCandidate(CompanyMemberVO member) {
|
||||||
|
OpTeamCandidateVO vo = new OpTeamCandidateVO();
|
||||||
|
vo.setCompanyMemberId(member.getId());
|
||||||
|
vo.setUserId(member.getUserId());
|
||||||
|
vo.setRealName(member.getRealName());
|
||||||
|
vo.setPhone(member.getPhone());
|
||||||
|
vo.setUsername(member.getUsername());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 创建运营团队。 */
|
||||||
|
@Data
|
||||||
|
public class CreateOpTeamDTO {
|
||||||
|
|
||||||
|
@NotBlank(message = "团队名称不能为空")
|
||||||
|
@Size(max = 100, message = "团队名称不能超过100字")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Size(max = 500, message = "备注不能超过500字")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
/** 0停用 1启用 */
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
private Integer sortOrder;
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 运营团队分页过滤。 */
|
||||||
|
@Data
|
||||||
|
public class OpTeamFilterDTO {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
/** 0停用 1启用 */
|
||||||
|
private Integer status;
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/** 更新运营团队。 */
|
||||||
|
@Data
|
||||||
|
public class UpdateOpTeamDTO {
|
||||||
|
|
||||||
|
@NotBlank(message = "团队名称不能为空")
|
||||||
|
@Size(max = 100, message = "团队名称不能超过100字")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@Size(max = 500, message = "备注不能超过500字")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
/** 0停用 1启用 */
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
private Integer sortOrder;
|
||||||
|
}
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.model.po;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 内部店铺运营团队。 */
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("ec_op_team")
|
||||||
|
public class OpTeamPO {
|
||||||
|
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@TableField("company_id")
|
||||||
|
private Long companyId;
|
||||||
|
|
||||||
|
@TableField("name")
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
@TableField("remark")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
/** 0停用 1启用 */
|
||||||
|
@TableField("status")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@TableField("sort_order")
|
||||||
|
private Integer sortOrder;
|
||||||
|
|
||||||
|
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableField("create_by")
|
||||||
|
private Long createBy;
|
||||||
|
|
||||||
|
@TableField("update_by")
|
||||||
|
private Long updateBy;
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/** 运营团队展示。 */
|
||||||
|
@Data
|
||||||
|
public class OpTeamVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private Long companyId;
|
||||||
|
private String name;
|
||||||
|
private String remark;
|
||||||
|
private Integer status;
|
||||||
|
private Integer sortOrder;
|
||||||
|
private Integer memberCount;
|
||||||
|
private Long leaderUserId;
|
||||||
|
private String leaderRealName;
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.CreateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.OpTeamFilterDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.UpdateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.po.OpTeamPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.vo.OpTeamVO;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** 运营团队用例。 */
|
||||||
|
public interface OpTeamService extends IService<OpTeamPO> {
|
||||||
|
|
||||||
|
OpTeamVO createTeam(CreateOpTeamDTO dto);
|
||||||
|
|
||||||
|
OpTeamVO updateTeam(UpdateOpTeamDTO dto, Long id);
|
||||||
|
|
||||||
|
void deleteTeam(Long id);
|
||||||
|
|
||||||
|
PageResultVO<OpTeamVO> getTeamPage(PageQueryDTO<OpTeamFilterDTO> pageQuery);
|
||||||
|
|
||||||
|
List<OpTeamVO> getAllTeams();
|
||||||
|
|
||||||
|
OpTeamVO getTeamDetail(Long id);
|
||||||
|
}
|
||||||
+251
@@ -0,0 +1,251 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.ec.opteam.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.mapper.OpTeamMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.OpTeamMemberRoles;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.mapper.OpTeamMemberMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.model.po.OpTeamMemberPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.CreateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.OpTeamFilterDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.dto.UpdateOpTeamDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.po.OpTeamPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.model.vo.OpTeamVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.service.OpTeamService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.po.CompanyMemberPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.mapper.UserMapper;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.sys.user.model.po.UserPO;
|
||||||
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/** 运营团队编排:租户隔离、同名校验、列表附带负责人摘要。 */
|
||||||
|
@Service
|
||||||
|
public class OpTeamServiceImpl extends ServiceImpl<OpTeamMapper, OpTeamPO> implements OpTeamService {
|
||||||
|
|
||||||
|
private final CurrentUserContext currentUserContext;
|
||||||
|
private final OpTeamMemberMapper opTeamMemberMapper;
|
||||||
|
private final UserMapper userMapper;
|
||||||
|
private final CompanyMemberService companyMemberService;
|
||||||
|
|
||||||
|
public OpTeamServiceImpl(CurrentUserContext currentUserContext,
|
||||||
|
OpTeamMemberMapper opTeamMemberMapper,
|
||||||
|
UserMapper userMapper,
|
||||||
|
CompanyMemberService companyMemberService) {
|
||||||
|
this.currentUserContext = currentUserContext;
|
||||||
|
this.opTeamMemberMapper = opTeamMemberMapper;
|
||||||
|
this.userMapper = userMapper;
|
||||||
|
this.companyMemberService = companyMemberService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public OpTeamVO createTeam(CreateOpTeamDTO dto) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
assertNameUnique(companyId, dto.getName(), null);
|
||||||
|
|
||||||
|
OpTeamPO team = new OpTeamPO();
|
||||||
|
BeanCopyUtils.copyProperties(dto, team);
|
||||||
|
team.setCompanyId(companyId);
|
||||||
|
if (team.getStatus() == null) {
|
||||||
|
team.setStatus(1);
|
||||||
|
}
|
||||||
|
if (team.getSortOrder() == null) {
|
||||||
|
team.setSortOrder(0);
|
||||||
|
}
|
||||||
|
team.setCreateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.save(team);
|
||||||
|
return convertToVO(team, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public OpTeamVO updateTeam(UpdateOpTeamDTO dto, Long id) {
|
||||||
|
OpTeamPO existing = requireTeam(id);
|
||||||
|
assertNameUnique(existing.getCompanyId(), dto.getName(), id);
|
||||||
|
|
||||||
|
existing.setName(dto.getName());
|
||||||
|
existing.setRemark(dto.getRemark());
|
||||||
|
if (dto.getStatus() != null) {
|
||||||
|
existing.setStatus(dto.getStatus());
|
||||||
|
}
|
||||||
|
if (dto.getSortOrder() != null) {
|
||||||
|
existing.setSortOrder(dto.getSortOrder());
|
||||||
|
}
|
||||||
|
existing.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
|
this.updateById(existing);
|
||||||
|
return getTeamDetail(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void deleteTeam(Long id) {
|
||||||
|
requireTeam(id);
|
||||||
|
this.removeById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResultVO<OpTeamVO> getTeamPage(PageQueryDTO<OpTeamFilterDTO> pageQuery) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
LambdaQueryWrapper<OpTeamPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamPO::getCompanyId, companyId);
|
||||||
|
OpTeamFilterDTO filters = pageQuery.getFilters();
|
||||||
|
if (filters != null) {
|
||||||
|
if (StringUtils.hasText(filters.getName())) {
|
||||||
|
wrapper.like(OpTeamPO::getName, filters.getName());
|
||||||
|
}
|
||||||
|
if (filters.getStatus() != null) {
|
||||||
|
wrapper.eq(OpTeamPO::getStatus, filters.getStatus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wrapper.orderByAsc(OpTeamPO::getSortOrder).orderByAsc(OpTeamPO::getId);
|
||||||
|
|
||||||
|
Page<OpTeamPO> page = new Page<>(pageQuery.getPage(), pageQuery.getPageSize());
|
||||||
|
IPage<OpTeamPO> pageResult = this.page(page, wrapper);
|
||||||
|
List<OpTeamVO> records = toVoList(pageResult.getRecords());
|
||||||
|
return PageResultVO.create(records, pageResult.getTotal(), pageQuery.getPage(), pageQuery.getPageSize());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OpTeamVO> getAllTeams() {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
LambdaQueryWrapper<OpTeamPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamPO::getCompanyId, companyId)
|
||||||
|
.orderByAsc(OpTeamPO::getSortOrder)
|
||||||
|
.orderByAsc(OpTeamPO::getId);
|
||||||
|
return toVoList(this.list(wrapper));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OpTeamVO getTeamDetail(Long id) {
|
||||||
|
OpTeamPO team = requireTeam(id);
|
||||||
|
List<OpTeamMemberPO> members = listActiveMembers(List.of(id));
|
||||||
|
return convertToVO(team, members);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamPO requireTeam(Long id) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
OpTeamPO team = this.getById(id);
|
||||||
|
if (team == null) {
|
||||||
|
throw new BusinessException("运营团队不存在");
|
||||||
|
}
|
||||||
|
if (!companyId.equals(team.getCompanyId())) {
|
||||||
|
throw new BusinessException("无权操作此运营团队");
|
||||||
|
}
|
||||||
|
return team;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertNameUnique(Long companyId, String name, Long excludeId) {
|
||||||
|
LambdaQueryWrapper<OpTeamPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.eq(OpTeamPO::getCompanyId, companyId).eq(OpTeamPO::getName, name);
|
||||||
|
if (excludeId != null) {
|
||||||
|
wrapper.ne(OpTeamPO::getId, excludeId);
|
||||||
|
}
|
||||||
|
if (this.count(wrapper) > 0) {
|
||||||
|
throw new BusinessException("团队名称已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<OpTeamVO> toVoList(List<OpTeamPO> teams) {
|
||||||
|
if (teams == null || teams.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
List<Long> teamIds = teams.stream().map(OpTeamPO::getId).toList();
|
||||||
|
List<OpTeamMemberPO> members = listActiveMembers(teamIds);
|
||||||
|
Map<Long, List<OpTeamMemberPO>> byTeam = members.stream()
|
||||||
|
.collect(Collectors.groupingBy(OpTeamMemberPO::getTeamId));
|
||||||
|
Map<Long, Long> userIdByCompanyMember = loadUserIdByCompanyMember(members);
|
||||||
|
Map<Long, String> nameByUser = loadUserNamesByUserIds(userIdByCompanyMember.values());
|
||||||
|
return teams.stream()
|
||||||
|
.map(team -> convertToVO(
|
||||||
|
team,
|
||||||
|
byTeam.getOrDefault(team.getId(), List.of()),
|
||||||
|
nameByUser,
|
||||||
|
userIdByCompanyMember))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<OpTeamMemberPO> listActiveMembers(List<Long> teamIds) {
|
||||||
|
if (teamIds == null || teamIds.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
LambdaQueryWrapper<OpTeamMemberPO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
wrapper.in(OpTeamMemberPO::getTeamId, teamIds)
|
||||||
|
.eq(OpTeamMemberPO::getStatus, 1);
|
||||||
|
return opTeamMemberMapper.selectList(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** companyMemberId → userId */
|
||||||
|
private Map<Long, Long> loadUserIdByCompanyMember(List<OpTeamMemberPO> members) {
|
||||||
|
Set<Long> companyMemberIds = members.stream()
|
||||||
|
.map(OpTeamMemberPO::getCompanyMemberId)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
if (companyMemberIds.isEmpty()) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
Map<Long, Long> map = new HashMap<>();
|
||||||
|
for (CompanyMemberPO cm : companyMemberService.listByIds(companyMemberIds)) {
|
||||||
|
map.put(cm.getId(), cm.getUserId());
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<Long, String> loadUserNamesByUserIds(Iterable<Long> userIdsIter) {
|
||||||
|
Set<Long> userIds = new java.util.HashSet<>();
|
||||||
|
for (Long id : userIdsIter) {
|
||||||
|
if (id != null) {
|
||||||
|
userIds.add(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (userIds.isEmpty()) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
Map<Long, String> names = new HashMap<>();
|
||||||
|
for (UserPO user : userMapper.selectBatchIds(userIds)) {
|
||||||
|
names.put(user.getId(), user.getRealName());
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamVO convertToVO(OpTeamPO team, List<OpTeamMemberPO> members) {
|
||||||
|
Map<Long, Long> userIdByCm = loadUserIdByCompanyMember(members);
|
||||||
|
return convertToVO(team, members, loadUserNamesByUserIds(userIdByCm.values()), userIdByCm);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OpTeamVO convertToVO(OpTeamPO team,
|
||||||
|
List<OpTeamMemberPO> members,
|
||||||
|
Map<Long, String> nameByUser,
|
||||||
|
Map<Long, Long> userIdByCompanyMember) {
|
||||||
|
OpTeamVO vo = new OpTeamVO();
|
||||||
|
BeanCopyUtils.copyProperties(team, vo);
|
||||||
|
List<OpTeamMemberPO> active = members == null ? List.of() : members;
|
||||||
|
vo.setMemberCount(active.size());
|
||||||
|
OpTeamMemberPO leader = active.stream()
|
||||||
|
.filter(m -> Objects.equals(m.getRole(), OpTeamMemberRoles.LEADER))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
if (leader != null) {
|
||||||
|
Long userId = userIdByCompanyMember.get(leader.getCompanyMemberId());
|
||||||
|
vo.setLeaderUserId(userId);
|
||||||
|
vo.setLeaderRealName(userId == null ? null : nameByUser.get(userId));
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-1
@@ -9,6 +9,7 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
import top.xyquan.ecomdmbbackend.modules.notify.access.AccessChangedEvent;
|
import top.xyquan.ecomdmbbackend.modules.notify.access.AccessChangedEvent;
|
||||||
import top.xyquan.ecomdmbbackend.modules.notify.access.AccessChangedReason;
|
import top.xyquan.ecomdmbbackend.modules.notify.access.AccessChangedReason;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.ec.opteam.member.service.OpTeamMemberService;
|
||||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberRole;
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberRole;
|
||||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.mapper.CompanyMemberMapper;
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.mapper.CompanyMemberMapper;
|
||||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.dto.CreateCompanyMemberDTO;
|
import top.xyquan.ecomdmbbackend.modules.org.company.member.model.dto.CreateCompanyMemberDTO;
|
||||||
@@ -40,17 +41,20 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
|||||||
private final PositionService positionService;
|
private final PositionService positionService;
|
||||||
private final UserMapper userMapper;
|
private final UserMapper userMapper;
|
||||||
private final ApplicationEventPublisher eventPublisher;
|
private final ApplicationEventPublisher eventPublisher;
|
||||||
|
private final OpTeamMemberService opTeamMemberService;
|
||||||
|
|
||||||
public CompanyMemberServiceImpl(@Lazy CurrentUserContext currentUserContext,
|
public CompanyMemberServiceImpl(@Lazy CurrentUserContext currentUserContext,
|
||||||
@Lazy CompanyService companyService,
|
@Lazy CompanyService companyService,
|
||||||
PositionService positionService,
|
PositionService positionService,
|
||||||
UserMapper userMapper,
|
UserMapper userMapper,
|
||||||
ApplicationEventPublisher eventPublisher) {
|
ApplicationEventPublisher eventPublisher,
|
||||||
|
@Lazy OpTeamMemberService opTeamMemberService) {
|
||||||
this.currentUserContext = currentUserContext;
|
this.currentUserContext = currentUserContext;
|
||||||
this.companyService = companyService;
|
this.companyService = companyService;
|
||||||
this.positionService = positionService;
|
this.positionService = positionService;
|
||||||
this.userMapper = userMapper;
|
this.userMapper = userMapper;
|
||||||
this.eventPublisher = eventPublisher;
|
this.eventPublisher = eventPublisher;
|
||||||
|
this.opTeamMemberService = opTeamMemberService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -158,6 +162,8 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
|||||||
member.setStatus(0);
|
member.setStatus(0);
|
||||||
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
this.updateById(member);
|
this.updateById(member);
|
||||||
|
// 软删不会触发 FK CASCADE,应用层同步摘除运营团队成员
|
||||||
|
opTeamMemberService.deactivateByCompanyMemberId(memberId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -228,6 +234,7 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
|||||||
member.setStatus(0);
|
member.setStatus(0);
|
||||||
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||||
this.updateById(member);
|
this.updateById(member);
|
||||||
|
opTeamMemberService.deactivateByCompanyMemberId(member.getId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -404,6 +404,26 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
|
|||||||
SELECT 3304, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:shop' LIMIT 1), 'ec:shop:delete', '删除', 'api', 1, '', 4
|
SELECT 3304, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:shop' LIMIT 1), 'ec:shop:delete', '删除', 'api', 1, '', 4
|
||||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3304 OR `code` = 'ec:shop:delete');
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3304 OR `code` = 'ec:shop:delete');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3380, (SELECT id FROM `sys_permission` WHERE `code` = 'ec' LIMIT 1), 'ec:op-team', '运营团队', 'module', 1, '', 45
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3380 OR `code` = 'ec:op-team');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3381, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:read', '查看', 'api', 1, '', 1
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3381 OR `code` = 'ec:op-team:read');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3382, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:create', '创建', 'api', 1, '', 2
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3382 OR `code` = 'ec:op-team:create');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3383, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:update', '更新', 'api', 1, '', 3
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3383 OR `code` = 'ec:op-team:update');
|
||||||
|
|
||||||
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
|
SELECT 3384, (SELECT id FROM `sys_permission` WHERE `code` = 'ec:op-team' LIMIT 1), 'ec:op-team:delete', '删除', 'api', 1, '', 4
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3384 OR `code` = 'ec:op-team:delete');
|
||||||
|
|
||||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||||
SELECT 3610, (SELECT id FROM `sys_permission` WHERE `code` = 'channel' LIMIT 1), 'channel:pdd', '拼多多', 'module', 1, '', 10
|
SELECT 3610, (SELECT id FROM `sys_permission` WHERE `code` = 'channel' LIMIT 1), 'channel:pdd', '拼多多', 'module', 1, '', 10
|
||||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3610 OR `code` = 'channel:pdd');
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 3610 OR `code` = 'channel:pdd');
|
||||||
@@ -848,6 +868,10 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path
|
|||||||
SELECT 14010, (SELECT id FROM `sys_menu` WHERE `id` = 7 OR `title` = '经营店铺' LIMIT 1), 0, 'ShopManagement', '店铺列表', '/ec/shop/list', '/ec/shop/list/index', '', 'solar:shop-outline', 'menu', 1, 1, 1, 1
|
SELECT 14010, (SELECT id FROM `sys_menu` WHERE `id` = 7 OR `title` = '经营店铺' LIMIT 1), 0, 'ShopManagement', '店铺列表', '/ec/shop/list', '/ec/shop/list/index', '', 'solar:shop-outline', 'menu', 1, 1, 1, 1
|
||||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14010 OR `route_name` = 'ShopManagement');
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14010 OR `route_name` = 'ShopManagement');
|
||||||
|
|
||||||
|
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||||
|
SELECT 14011, (SELECT id FROM `sys_menu` WHERE `id` = 7 OR `title` = '经营店铺' LIMIT 1), 0, 'OpTeamManagement', '运营团队', '/ec/shop/op-team', '/ec/shop/op-team/index', '', 'lucide:users', 'menu', 1, 1, 1, 5
|
||||||
|
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14011 OR `route_name` = 'OpTeamManagement');
|
||||||
|
|
||||||
-- ------------------------------------------------
|
-- ------------------------------------------------
|
||||||
-- 3. 菜单-权限关联
|
-- 3. 菜单-权限关联
|
||||||
-- ------------------------------------------------
|
-- ------------------------------------------------
|
||||||
@@ -908,6 +932,9 @@ SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:p
|
|||||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:shop:%' WHERE m.name = '店铺列表';
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:shop:%' WHERE m.name = '店铺列表';
|
||||||
|
|
||||||
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:op-team:%' WHERE m.route_name = 'OpTeamManagement';
|
||||||
|
|
||||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:shop:ad-fee:%' WHERE m.name = '推广费';
|
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:shop:ad-fee:%' WHERE m.name = '推广费';
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -53,6 +53,8 @@ export namespace AgentVO {
|
|||||||
configured: boolean;
|
configured: boolean;
|
||||||
baseUrl?: string | null;
|
baseUrl?: string | null;
|
||||||
displayName?: string | null;
|
displayName?: string | null;
|
||||||
|
/** auto | completions | responses */
|
||||||
|
apiStyle?: string | null;
|
||||||
apiKeyMasked?: string | null;
|
apiKeyMasked?: string | null;
|
||||||
models?: LlmModelItem[];
|
models?: LlmModelItem[];
|
||||||
updateTime?: string;
|
updateTime?: string;
|
||||||
@@ -110,6 +112,11 @@ export async function patchAgentSessionApi(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 软删会话(级联软删消息) */
|
||||||
|
export async function deleteAgentSessionApi(threadId: string) {
|
||||||
|
return requestClient.delete<AgentVO.Session>(`/agent/sessions/${threadId}`);
|
||||||
|
}
|
||||||
|
|
||||||
export async function listAgentMessagesApi(threadId: string) {
|
export async function listAgentMessagesApi(threadId: string) {
|
||||||
return requestClient.get<{ items: AgentVO.Message[] }>(
|
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||||
`/agent/sessions/${threadId}/messages`,
|
`/agent/sessions/${threadId}/messages`,
|
||||||
@@ -140,6 +147,7 @@ export async function createAgentLlmProviderApi(body: {
|
|||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
apiKey: string;
|
apiKey: string;
|
||||||
displayName?: string;
|
displayName?: string;
|
||||||
|
apiStyle?: string;
|
||||||
}) {
|
}) {
|
||||||
return requestClient.post<AgentVO.LlmProvider>(
|
return requestClient.post<AgentVO.LlmProvider>(
|
||||||
'/company/agent-llm-providers',
|
'/company/agent-llm-providers',
|
||||||
@@ -149,7 +157,12 @@ export async function createAgentLlmProviderApi(body: {
|
|||||||
|
|
||||||
export async function updateAgentLlmProviderApi(
|
export async function updateAgentLlmProviderApi(
|
||||||
providerId: number,
|
providerId: number,
|
||||||
body: { baseUrl?: string; apiKey?: string; displayName?: string },
|
body: {
|
||||||
|
baseUrl?: string;
|
||||||
|
apiKey?: string;
|
||||||
|
displayName?: string;
|
||||||
|
apiStyle?: string;
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
return requestClient.put<AgentVO.LlmProvider>(
|
return requestClient.put<AgentVO.LlmProvider>(
|
||||||
`/company/agent-llm-providers/${providerId}`,
|
`/company/agent-llm-providers/${providerId}`,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ export {
|
|||||||
createAgentSessionApi,
|
createAgentSessionApi,
|
||||||
deleteAgentLlmProviderApi,
|
deleteAgentLlmProviderApi,
|
||||||
deleteAgentMemoryApi,
|
deleteAgentMemoryApi,
|
||||||
|
deleteAgentSessionApi,
|
||||||
getAgentLlmProviderApi,
|
getAgentLlmProviderApi,
|
||||||
listAgentEnabledLlmModelsApi,
|
listAgentEnabledLlmModelsApi,
|
||||||
listAgentLlmProvidersApi,
|
listAgentLlmProvidersApi,
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import type { OpTeamDTO, OpTeamVO } from './types';
|
||||||
|
|
||||||
|
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||||
|
|
||||||
|
import { requestClient } from '#/api/request';
|
||||||
|
|
||||||
|
/** 分页查询运营团队 */
|
||||||
|
export async function getOpTeamPageApi(
|
||||||
|
params: PageQueryDTO<OpTeamDTO.Filters>,
|
||||||
|
) {
|
||||||
|
return requestClient.post<PageResultVO<OpTeamVO.Info>>(
|
||||||
|
'/ec/op-team/list',
|
||||||
|
params,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 全部运营团队(后续店铺分配用) */
|
||||||
|
export async function getAllOpTeamsApi() {
|
||||||
|
return requestClient.get<OpTeamVO.Info[]>('/ec/op-team/all');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createOpTeamApi(data: OpTeamDTO.Create) {
|
||||||
|
return requestClient.post<OpTeamVO.Info>('/ec/op-team/create', data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateOpTeamApi(id: number, data: OpTeamDTO.Update) {
|
||||||
|
return requestClient.put<OpTeamVO.Info>(`/ec/op-team/update/${id}`, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteOpTeamApi(id: number) {
|
||||||
|
return requestClient.delete(`/ec/op-team/delete/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getOpTeamMembersApi(teamId: number) {
|
||||||
|
return requestClient.get<OpTeamVO.Member[]>(
|
||||||
|
`/ec/op-team-member/team/${teamId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addOpTeamMemberApi(data: OpTeamDTO.AddMember) {
|
||||||
|
return requestClient.post<OpTeamVO.Member>('/ec/op-team-member/add', data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateOpTeamMemberRoleApi(
|
||||||
|
id: number,
|
||||||
|
data: OpTeamDTO.UpdateMember,
|
||||||
|
) {
|
||||||
|
return requestClient.put<OpTeamVO.Member>(
|
||||||
|
`/ec/op-team-member/update/${id}`,
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeOpTeamMemberApi(data: OpTeamDTO.RemoveMember) {
|
||||||
|
return requestClient.post('/ec/op-team-member/remove', data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getOpTeamCandidatesApi() {
|
||||||
|
return requestClient.get<OpTeamVO.Candidate[]>(
|
||||||
|
'/ec/op-team-member/candidates',
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './apis';
|
||||||
|
export * from './types';
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export * from './types.dto';
|
||||||
|
export * from './types.vo';
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/**
|
||||||
|
* 运营团队 DTO
|
||||||
|
*/
|
||||||
|
|
||||||
|
export namespace OpTeamDTO {
|
||||||
|
export interface Create {
|
||||||
|
name: string;
|
||||||
|
remark?: string;
|
||||||
|
status?: number;
|
||||||
|
sortOrder?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Update {
|
||||||
|
name: string;
|
||||||
|
remark?: string;
|
||||||
|
status?: number;
|
||||||
|
sortOrder?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Filters {
|
||||||
|
name?: string;
|
||||||
|
status?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AddMember {
|
||||||
|
teamId: number;
|
||||||
|
companyMemberId: number;
|
||||||
|
role?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateMember {
|
||||||
|
role: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RemoveMember {
|
||||||
|
teamId: number;
|
||||||
|
companyMemberId: number;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* 运营团队 VO
|
||||||
|
*/
|
||||||
|
|
||||||
|
export namespace OpTeamVO {
|
||||||
|
export interface Info {
|
||||||
|
id: number;
|
||||||
|
companyId: number;
|
||||||
|
name: string;
|
||||||
|
remark?: string;
|
||||||
|
status: number;
|
||||||
|
sortOrder: number;
|
||||||
|
memberCount: number;
|
||||||
|
leaderUserId?: number;
|
||||||
|
leaderRealName?: string;
|
||||||
|
createTime: string;
|
||||||
|
updateTime: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Member {
|
||||||
|
id: number;
|
||||||
|
companyId: number;
|
||||||
|
teamId: number;
|
||||||
|
teamName?: string;
|
||||||
|
companyMemberId: number;
|
||||||
|
userId?: number;
|
||||||
|
role: number;
|
||||||
|
roleName?: string;
|
||||||
|
status: number;
|
||||||
|
realName?: string;
|
||||||
|
phone?: string;
|
||||||
|
username?: string;
|
||||||
|
createTime: string;
|
||||||
|
updateTime: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Candidate {
|
||||||
|
companyMemberId: number;
|
||||||
|
userId?: number;
|
||||||
|
realName?: string;
|
||||||
|
phone?: string;
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -113,10 +113,8 @@ const UserIcon = createIconifyIcon('lucide:user');
|
|||||||
const MemoryIcon = createIconifyIcon('lucide:brain');
|
const MemoryIcon = createIconifyIcon('lucide:brain');
|
||||||
// 意见反馈图标
|
// 意见反馈图标
|
||||||
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
|
const FeedbackIcon = createIconifyIcon('lucide:message-square-plus');
|
||||||
// 锁图标
|
|
||||||
const LockIcon = createIconifyIcon('lucide:lock');
|
|
||||||
|
|
||||||
/** 是否具备智能助手聊天权限(用于「我的记忆」入口;含超管) */
|
/** 是否具备智能助手聊天权限(用于「助手记忆」入口;含超管) */
|
||||||
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
|
const canUseAgentChat = computed(() => hasPermission('agent:chat'));
|
||||||
|
|
||||||
/** 当前用户可切换的可用公司数 */
|
/** 当前用户可切换的可用公司数 */
|
||||||
@@ -128,22 +126,22 @@ const companyCount = computed(() => {
|
|||||||
const menus = computed(() => {
|
const menus = computed(() => {
|
||||||
const menuItems = [];
|
const menuItems = [];
|
||||||
|
|
||||||
// 个人信息
|
// 个人中心
|
||||||
menuItems.push({
|
menuItems.push({
|
||||||
handler: () => {
|
handler: () => {
|
||||||
router.push('/system/profile');
|
router.push('/system/profile');
|
||||||
},
|
},
|
||||||
icon: UserIcon,
|
icon: UserIcon,
|
||||||
text: '个人信息',
|
text: '个人中心',
|
||||||
});
|
});
|
||||||
// 我的记忆(有助手聊天权才显示)
|
// 助手记忆(有助手聊天权才显示)
|
||||||
if (canUseAgentChat.value) {
|
if (canUseAgentChat.value) {
|
||||||
menuItems.push({
|
menuItems.push({
|
||||||
handler: () => {
|
handler: () => {
|
||||||
router.push('/agent/memories');
|
router.push('/agent/memories');
|
||||||
},
|
},
|
||||||
icon: MemoryIcon,
|
icon: MemoryIcon,
|
||||||
text: '我的记忆',
|
text: '助手记忆',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// 意见反馈
|
// 意见反馈
|
||||||
@@ -154,14 +152,6 @@ const menus = computed(() => {
|
|||||||
icon: FeedbackIcon,
|
icon: FeedbackIcon,
|
||||||
text: '意见反馈',
|
text: '意见反馈',
|
||||||
});
|
});
|
||||||
// 修改密码
|
|
||||||
menuItems.push({
|
|
||||||
handler: () => {
|
|
||||||
router.push('/system/change-password');
|
|
||||||
},
|
|
||||||
icon: LockIcon,
|
|
||||||
text: '修改密码',
|
|
||||||
});
|
|
||||||
|
|
||||||
// 可切换公司数大于 1 时显示切换公司
|
// 可切换公司数大于 1 时显示切换公司
|
||||||
if (companyCount.value > 1) {
|
if (companyCount.value > 1) {
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
import type { RouteRecordRaw } from 'vue-router';
|
import type { RouteRecordRaw } from 'vue-router';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 修改密码静态路由
|
* 修改密码:并入个人中心,保留旧路径兼容跳转
|
||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
name: 'ChangePassword',
|
name: 'ChangePassword',
|
||||||
path: '/system/change-password',
|
path: '/system/change-password',
|
||||||
component: () =>
|
redirect: '/system/profile?tab=password',
|
||||||
import(
|
|
||||||
'#/views/sys/profile/modules/ChangePasswordModal.vue'
|
|
||||||
),
|
|
||||||
meta: {
|
meta: {
|
||||||
title: '修改密码',
|
title: '修改密码',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { RouteRecordRaw } from 'vue-router';
|
import type { RouteRecordRaw } from 'vue-router';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户记忆管理(头像下拉入口;不进侧栏菜单)
|
* 助手长期记忆管理(头像下拉「助手记忆」入口;不进侧栏菜单)
|
||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
@@ -10,7 +10,7 @@ const staticRoutes: RouteRecordRaw[] = [
|
|||||||
component: () => import('#/views/agent/memories/index.vue'),
|
component: () => import('#/views/agent/memories/index.vue'),
|
||||||
meta: {
|
meta: {
|
||||||
icon: 'lucide:brain',
|
icon: 'lucide:brain',
|
||||||
title: '我的记忆',
|
title: '助手记忆',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
ignoreAccess: true,
|
ignoreAccess: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5,14 +5,16 @@ import type { RouteRecordRaw } from 'vue-router';
|
|||||||
*/
|
*/
|
||||||
const staticRoutes: RouteRecordRaw[] = [
|
const staticRoutes: RouteRecordRaw[] = [
|
||||||
{
|
{
|
||||||
name: 'PersonalProfile',
|
name: 'PersonalCenter',
|
||||||
path: '/system/profile',
|
path: '/system/profile',
|
||||||
component: () => import('#/views/sys/profile/index.vue'),
|
component: () => import('#/views/sys/profile/index.vue'),
|
||||||
meta: {
|
meta: {
|
||||||
icon: 'lucide:user',
|
icon: 'lucide:user',
|
||||||
title: '个人信息',
|
title: '个人中心',
|
||||||
hideInMenu: true,
|
hideInMenu: true,
|
||||||
ignoreAccess: true,
|
ignoreAccess: true,
|
||||||
|
// 页内 ?tab= 不另开系统标签
|
||||||
|
fullPathKey: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import { computed } from 'vue';
|
||||||
|
|
||||||
|
import {
|
||||||
|
catalogCiteLabel,
|
||||||
|
parseMessageCiteSegments,
|
||||||
|
} from './catalog-cite';
|
||||||
|
|
||||||
|
/** 把消息正文里的实体引用渲染成标签(兼容 token / 展开 line)。 */
|
||||||
|
const props = defineProps<{
|
||||||
|
text: string;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const segments = computed(() => parseMessageCiteSegments(props.text || ''));
|
||||||
|
const hasCite = computed(() => segments.value.some((s) => s.type === 'cite'));
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span class="cite-rich-text" :class="{ 'cite-rich-text--plain': !hasCite }">
|
||||||
|
<template v-for="(seg, index) in segments" :key="index">
|
||||||
|
<span v-if="seg.type === 'text'" class="cite-rich-text__text">{{
|
||||||
|
seg.value
|
||||||
|
}}</span>
|
||||||
|
<span
|
||||||
|
v-else
|
||||||
|
class="cite-msg-chip"
|
||||||
|
:title="seg.id != null ? `id=${seg.id}` : undefined"
|
||||||
|
>
|
||||||
|
<span class="cite-msg-chip__kind">{{ catalogCiteLabel(seg.kind) }}</span>
|
||||||
|
<span class="cite-msg-chip__title">{{ seg.title }}</span>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.cite-rich-text {
|
||||||
|
display: inline;
|
||||||
|
word-break: break-word;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cite-msg-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
max-width: 14rem;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
margin: 0 2px;
|
||||||
|
padding: 0 6px;
|
||||||
|
overflow: hidden;
|
||||||
|
vertical-align: middle;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 20px;
|
||||||
|
color: hsl(var(--primary));
|
||||||
|
white-space: nowrap;
|
||||||
|
background: hsl(var(--primary) / 0.12);
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cite-msg-chip__kind {
|
||||||
|
flex-shrink: 0;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cite-msg-chip__title {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -10,25 +10,100 @@ export interface CatalogCite {
|
|||||||
line: string;
|
line: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 光标处未完成的 @ 查询区间 */
|
||||||
|
export interface MentionHit {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
query: string;
|
||||||
|
}
|
||||||
|
|
||||||
const KIND_LABEL: Record<CatalogCiteKind, string> = {
|
const KIND_LABEL: Record<CatalogCiteKind, string> = {
|
||||||
shop: '店铺',
|
shop: '店铺',
|
||||||
product: '商品',
|
product: '商品',
|
||||||
sku: 'SKU',
|
sku: 'SKU',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const LABEL_KIND: Record<string, CatalogCiteKind> = {
|
||||||
|
店铺: 'shop',
|
||||||
|
商品: 'product',
|
||||||
|
SKU: 'sku',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 行内引用:@[店铺#123·名称](每次新建,避免 /g lastIndex 串扰) */
|
||||||
|
function inlineCitePattern() {
|
||||||
|
return /@\[(店铺|商品|SKU)#(\d+)·([^\]]*)\]/g;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 草稿分段:纯文本 / 已选引用(供 contenteditable 渲染标签) */
|
||||||
|
export type DraftSegment =
|
||||||
|
| { type: 'text'; value: string }
|
||||||
|
| { type: 'cite'; key: string };
|
||||||
|
|
||||||
|
export function parseDraftSegments(text: string): DraftSegment[] {
|
||||||
|
const segments: DraftSegment[] = [];
|
||||||
|
let last = 0;
|
||||||
|
for (const m of text.matchAll(inlineCitePattern())) {
|
||||||
|
if (m.index == null) continue;
|
||||||
|
if (m.index > last) {
|
||||||
|
segments.push({ type: 'text', value: text.slice(last, m.index) });
|
||||||
|
}
|
||||||
|
const label = m[1];
|
||||||
|
const id = Number(m[2]);
|
||||||
|
const kind = label ? LABEL_KIND[label] : undefined;
|
||||||
|
if (kind && Number.isFinite(id)) {
|
||||||
|
segments.push({ type: 'cite', key: `${kind}:${id}` });
|
||||||
|
} else {
|
||||||
|
segments.push({ type: 'text', value: m[0] });
|
||||||
|
}
|
||||||
|
last = m.index + m[0].length;
|
||||||
|
}
|
||||||
|
if (last < text.length) {
|
||||||
|
segments.push({ type: 'text', value: text.slice(last) });
|
||||||
|
}
|
||||||
|
if (segments.length === 0) {
|
||||||
|
segments.push({ type: 'text', value: '' });
|
||||||
|
}
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
export function catalogCiteLabel(kind: CatalogCiteKind) {
|
export function catalogCiteLabel(kind: CatalogCiteKind) {
|
||||||
return KIND_LABEL[kind];
|
return KIND_LABEL[kind];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 输入框末尾的 @ 查询;没有则 null。空字符串表示刚输入 @。 */
|
/** 在光标前查找未完成的 @查询(支持正文任意位置)。 */
|
||||||
export function trailingMentionQuery(text: string): null | string {
|
export function mentionQueryAt(
|
||||||
const matched = text.match(/(^|\s)@([^\s@]*)$/);
|
text: string,
|
||||||
return matched ? matched[2] ?? '' : null;
|
cursor: number,
|
||||||
|
): MentionHit | null {
|
||||||
|
const pos = Math.max(0, Math.min(cursor, text.length));
|
||||||
|
const before = text.slice(0, pos);
|
||||||
|
const matched = before.match(/(^|[\s\n])@([^\s@\[]*)$/);
|
||||||
|
if (!matched) return null;
|
||||||
|
const index = matched.index;
|
||||||
|
if (index == null) return null;
|
||||||
|
const prefix = matched[1] ?? '';
|
||||||
|
return {
|
||||||
|
start: index + prefix.length,
|
||||||
|
end: pos,
|
||||||
|
query: matched[2] ?? '',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 发送前去掉还没选中的 @查询。 */
|
/** @deprecated 兼容旧调用:等价于光标在末尾 */
|
||||||
|
export function trailingMentionQuery(text: string): null | string {
|
||||||
|
return mentionQueryAt(text, text.length)?.query ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 发送前去掉仍未选中的残缺 @查询(末尾)。 */
|
||||||
export function stripTrailingMention(text: string) {
|
export function stripTrailingMention(text: string) {
|
||||||
return text.replace(/(^|\s)@[^\s@]*$/, '$1').replace(/\s+$/, '');
|
return text.replace(/(^|[\s\n])@[^\s@\[]*$/u, '$1').replace(/\s+$/u, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 输入框内展示用标记(嵌 id,发送时按位置展开)。 */
|
||||||
|
export function formatInlineCite(cite: CatalogCite): string {
|
||||||
|
const raw = cite.title.trim() || String(cite.id);
|
||||||
|
const title = raw.length > 24 ? `${raw.slice(0, 23)}…` : raw;
|
||||||
|
return `@[${KIND_LABEL[cite.kind]}#${cite.id}·${title}]`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toShopCite(shop: {
|
export function toShopCite(shop: {
|
||||||
@@ -85,12 +160,125 @@ export function toSkuCite(sku: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 正文后面附上引用 id。标签只在输入框里显示,不占一行正文。 */
|
/**
|
||||||
|
* 按正文中的行内标记位置展开引用;标记不在文中的 cite 仍附在末尾 [引用] 块(兼容旧数据)。
|
||||||
|
*/
|
||||||
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
|
export function composeMessageWithCites(text: string, cites: CatalogCite[]) {
|
||||||
const body = text.trim();
|
const body = stripTrailingMention(text);
|
||||||
if (cites.length === 0) return body;
|
if (!body && cites.length === 0) return '';
|
||||||
const block = ['[引用]', ...cites.map((item) => item.line)].join('\n');
|
|
||||||
return body ? `${body}\n${block}` : block;
|
const used = new Set<string>();
|
||||||
|
const expanded = body.replace(
|
||||||
|
inlineCitePattern(),
|
||||||
|
(_raw, label: string, idStr: string) => {
|
||||||
|
const kind = LABEL_KIND[label];
|
||||||
|
const id = Number(idStr);
|
||||||
|
if (!kind || !Number.isFinite(id)) return _raw;
|
||||||
|
const hit =
|
||||||
|
cites.find((c) => c.kind === kind && c.id === id) ||
|
||||||
|
cites.find((c) => c.key === `${kind}:${id}`);
|
||||||
|
if (!hit) return _raw;
|
||||||
|
used.add(hit.key);
|
||||||
|
return hit.line;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const orphans = cites.filter((c) => !used.has(c.key));
|
||||||
|
if (orphans.length === 0) return expanded.trim();
|
||||||
|
const block = ['[引用]', ...orphans.map((item) => item.line)].join('\n');
|
||||||
|
const trimmed = expanded.trim();
|
||||||
|
return trimmed ? `${trimmed}\n${block}` : block;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 消息气泡展示用分段(token / 展开后的 line 都能识别) */
|
||||||
|
export type MessageCiteSegment =
|
||||||
|
| { type: 'text'; value: string }
|
||||||
|
| { type: 'cite'; kind: CatalogCiteKind; id?: number; title: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把消息正文拆成文本 + 引用标签。
|
||||||
|
* 支持 `@[店铺#1·名]` 与 `店铺「名」 id=1 平台=…` 两种形态。
|
||||||
|
*/
|
||||||
|
export function parseMessageCiteSegments(text: string): MessageCiteSegment[] {
|
||||||
|
const source = text.replace(/^\s*\[引用\]\s*/m, '');
|
||||||
|
if (!source) return [{ type: 'text', value: '' }];
|
||||||
|
|
||||||
|
// token 或已展开 line;attrs 吃掉 key=value,直到下一个引用
|
||||||
|
const re =
|
||||||
|
/@\[(店铺|商品|SKU)#(\d+)·([^\]]*)\]|(店铺|商品|SKU)「([^」]*)」\s+id=(\d+)((?:\s+[^\s「=]+=\S+)*)/g;
|
||||||
|
|
||||||
|
const segments: MessageCiteSegment[] = [];
|
||||||
|
let last = 0;
|
||||||
|
for (const m of source.matchAll(re)) {
|
||||||
|
if (m.index == null) continue;
|
||||||
|
if (m.index > last) {
|
||||||
|
segments.push({ type: 'text', value: source.slice(last, m.index) });
|
||||||
|
}
|
||||||
|
if (m[1]) {
|
||||||
|
const kind = LABEL_KIND[m[1]];
|
||||||
|
if (kind) {
|
||||||
|
segments.push({
|
||||||
|
type: 'cite',
|
||||||
|
kind,
|
||||||
|
id: Number(m[2]),
|
||||||
|
title: (m[3] || '').trim() || String(m[2]),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
segments.push({ type: 'text', value: m[0] });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const kind = LABEL_KIND[m[4] || ''];
|
||||||
|
if (kind) {
|
||||||
|
segments.push({
|
||||||
|
type: 'cite',
|
||||||
|
kind,
|
||||||
|
id: Number(m[6]),
|
||||||
|
title: (m[5] || '').trim() || String(m[6]),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
segments.push({ type: 'text', value: m[0] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
last = m.index + m[0].length;
|
||||||
|
}
|
||||||
|
if (last < source.length) {
|
||||||
|
segments.push({ type: 'text', value: source.slice(last) });
|
||||||
|
}
|
||||||
|
return segments.length > 0 ? segments : [{ type: 'text', value: source }];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 正文里仍存在的引用 key(用于删字后同步 cites)。 */
|
||||||
|
export function inlineCiteKeysInText(text: string): Set<string> {
|
||||||
|
const keys = new Set<string>();
|
||||||
|
for (const m of text.matchAll(inlineCitePattern())) {
|
||||||
|
const label = m[1];
|
||||||
|
const id = Number(m[2]);
|
||||||
|
const kind = label ? LABEL_KIND[label] : undefined;
|
||||||
|
if (kind && Number.isFinite(id)) keys.add(`${kind}:${id}`);
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 光标落在某个行内引用上(含紧挨标记末尾)时返回其区间,便于 ⌫ 整段删除。
|
||||||
|
*/
|
||||||
|
export function inlineCiteRangeAt(
|
||||||
|
text: string,
|
||||||
|
cursor: number,
|
||||||
|
): { start: number; end: number; key: string } | null {
|
||||||
|
for (const m of text.matchAll(inlineCitePattern())) {
|
||||||
|
if (m.index == null) continue;
|
||||||
|
const start = m.index;
|
||||||
|
const end = start + m[0].length;
|
||||||
|
if (cursor > start && cursor <= end) {
|
||||||
|
const label = m[1];
|
||||||
|
const id = Number(m[2]);
|
||||||
|
const kind = label ? LABEL_KIND[label] : undefined;
|
||||||
|
if (!kind || !Number.isFinite(id)) continue;
|
||||||
|
return { start, end, key: `${kind}:${id}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function joinLine(kind: string, title: string, id: number, extra: string) {
|
function joinLine(kind: string, title: string, id: number, extra: string) {
|
||||||
|
|||||||
@@ -1,16 +1,37 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, h, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { EllipsisText, Page } from '@vben/common-ui';
|
||||||
import { PlusOutlined } from '@ant-design/icons-vue';
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
import {
|
||||||
|
BarChartOutlined,
|
||||||
|
CalendarOutlined,
|
||||||
|
FundOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
RiseOutlined,
|
||||||
|
} from '@ant-design/icons-vue';
|
||||||
|
import dayjs from 'dayjs';
|
||||||
|
|
||||||
import { Button, Empty, Select, Spin, message } from 'ant-design-vue';
|
import type { MenuProps } from 'ant-design-vue';
|
||||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
|
||||||
|
import {
|
||||||
|
Dropdown,
|
||||||
|
Empty,
|
||||||
|
Menu,
|
||||||
|
Modal,
|
||||||
|
Popover,
|
||||||
|
Select,
|
||||||
|
Spin,
|
||||||
|
Tooltip,
|
||||||
|
message,
|
||||||
|
} from 'ant-design-vue';
|
||||||
|
import { ChatItem, ChatLoading } from '@tdesign-vue-next/chat';
|
||||||
import 'tdesign-vue-next/es/style/index.css';
|
import 'tdesign-vue-next/es/style/index.css';
|
||||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
createAgentSessionApi,
|
createAgentSessionApi,
|
||||||
|
deleteAgentSessionApi,
|
||||||
listAgentEnabledLlmModelsApi,
|
listAgentEnabledLlmModelsApi,
|
||||||
listAgentMessagesApi,
|
listAgentMessagesApi,
|
||||||
listAgentSessionsApi,
|
listAgentSessionsApi,
|
||||||
@@ -20,6 +41,8 @@ import {
|
|||||||
} from '#/api/agent';
|
} from '#/api/agent';
|
||||||
|
|
||||||
import CatalogCiteSender from './catalog-cite-sender.vue';
|
import CatalogCiteSender from './catalog-cite-sender.vue';
|
||||||
|
import CatalogCiteRichText from './catalog-cite-rich-text.vue';
|
||||||
|
import SessionSearchModal from './session-search-modal.vue';
|
||||||
import {
|
import {
|
||||||
composeMessageWithCites,
|
composeMessageWithCites,
|
||||||
stripTrailingMention,
|
stripTrailingMention,
|
||||||
@@ -28,14 +51,43 @@ import {
|
|||||||
|
|
||||||
defineOptions({ name: 'AgentChat' });
|
defineOptions({ name: 'AgentChat' });
|
||||||
|
|
||||||
/** 新对话空态快捷提示:点击只填入输入框,不直接发送 */
|
const AgentBrandIcon = createIconifyIcon('lucide:bot');
|
||||||
|
const SearchIcon = createIconifyIcon('lucide:search');
|
||||||
|
const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
|
||||||
|
const PanelOpenIcon = createIconifyIcon('lucide:panel-left');
|
||||||
|
const NewChatIcon = createIconifyIcon('lucide:square-pen');
|
||||||
|
const RecentChatIcon = createIconifyIcon('lucide:message-square');
|
||||||
|
const MoreIcon = createIconifyIcon('lucide:ellipsis');
|
||||||
|
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||||
|
|
||||||
|
const SIDER_COLLAPSED_KEY = 'agent-chat-sider-collapsed';
|
||||||
|
|
||||||
|
/** 空态快捷 chips:短标签展示,点击填入完整提问 */
|
||||||
const starterPrompts = [
|
const starterPrompts = [
|
||||||
'近7天的销售额、单量、净利和费比分别是多少',
|
{
|
||||||
'昨天的经营情况怎么样',
|
label: '近7天经营概览',
|
||||||
'本周销售额和净利帮我汇总一下',
|
prompt: '近7天的销售额、单量、净利和费比分别是多少',
|
||||||
'近30天单量和费比有什么变化',
|
icon: BarChartOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '昨天经营情况',
|
||||||
|
prompt: '昨天的经营情况怎么样',
|
||||||
|
icon: CalendarOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '本周销售与净利',
|
||||||
|
prompt: '本周销售额和净利帮我汇总一下',
|
||||||
|
icon: RiseOutlined,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '近30天费比变化',
|
||||||
|
prompt: '近30天单量和费比有什么变化',
|
||||||
|
icon: FundOutlined,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
type SessionGroup = { key: string; label: string; items: AgentVO.Session[] };
|
||||||
|
|
||||||
/** 消息气泡视图模型(走 Vue ChatItem,避免 ChatList→WebComponent 丢正文) */
|
/** 消息气泡视图模型(走 Vue ChatItem,避免 ChatList→WebComponent 丢正文) */
|
||||||
type BubbleView = {
|
type BubbleView = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -52,6 +104,14 @@ const sessions = ref<AgentVO.Session[]>([]);
|
|||||||
const activeThreadId = ref<string | null>(null);
|
const activeThreadId = ref<string | null>(null);
|
||||||
/** 点了「新对话」但还没发出第一条消息,此时不请求后端 */
|
/** 点了「新对话」但还没发出第一条消息,此时不请求后端 */
|
||||||
const composingNew = ref(false);
|
const composingNew = ref(false);
|
||||||
|
/** 侧栏收起状态(localStorage 持久化) */
|
||||||
|
const siderCollapsed = ref(
|
||||||
|
typeof localStorage !== 'undefined' &&
|
||||||
|
localStorage.getItem(SIDER_COLLAPSED_KEY) === '1',
|
||||||
|
);
|
||||||
|
/** 收起态:最近会话浮层 */
|
||||||
|
const collapsedRecentOpen = ref(false);
|
||||||
|
const sessionSearchModalRef = ref<{ open: () => void } | null>(null);
|
||||||
const messages = ref<AgentVO.Message[]>([]);
|
const messages = ref<AgentVO.Message[]>([]);
|
||||||
/** 当前流式助手正文(与 messages 末条同步) */
|
/** 当前流式助手正文(与 messages 末条同步) */
|
||||||
const streamingText = ref('');
|
const streamingText = ref('');
|
||||||
@@ -110,7 +170,7 @@ const showMessageLoading = computed(
|
|||||||
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
||||||
);
|
);
|
||||||
|
|
||||||
/** 新对话草稿,或还没有任何会话时,展示能力引导 */
|
/** 新对话草稿,或还没有任何会话时,展示居中空态 */
|
||||||
const showStarter = computed(
|
const showStarter = computed(
|
||||||
() =>
|
() =>
|
||||||
messages.value.length === 0 &&
|
messages.value.length === 0 &&
|
||||||
@@ -119,6 +179,86 @@ const showStarter = computed(
|
|||||||
(!loadingSessions.value && !activeThreadId.value)),
|
(!loadingSessions.value && !activeThreadId.value)),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const greeting = computed(() => {
|
||||||
|
const h = dayjs().hour();
|
||||||
|
if (h < 12) return '早上好,今天想看点什么?';
|
||||||
|
if (h < 18) return '下午好,今天想看点什么?';
|
||||||
|
return '晚上好,今天想看点什么?';
|
||||||
|
});
|
||||||
|
|
||||||
|
function sessionTime(s: AgentVO.Session) {
|
||||||
|
const raw = s.lastMessageAt || s.updatedAt;
|
||||||
|
const d = raw ? dayjs(raw) : null;
|
||||||
|
return d?.isValid() ? d : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSiderCollapsed(next: boolean) {
|
||||||
|
siderCollapsed.value = next;
|
||||||
|
try {
|
||||||
|
localStorage.setItem(SIDER_COLLAPSED_KEY, next ? '1' : '0');
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
if (!next) {
|
||||||
|
collapsedRecentOpen.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 居中弹窗搜索会话(展开/收起侧栏共用入口) */
|
||||||
|
function openSessionSearch() {
|
||||||
|
sessionSearchModalRef.value?.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onCollapsedRecentOpenChange(open: boolean) {
|
||||||
|
collapsedRecentOpen.value = open;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收起态浮层 / 搜索弹窗点选会话 */
|
||||||
|
function pickSessionFromOverlay(threadId: string) {
|
||||||
|
collapsedRecentOpen.value = false;
|
||||||
|
onSessionClick(threadId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收起态「最近」列表(按接口顺序,最多 20 条) */
|
||||||
|
const recentSessions = computed(() => sessions.value.slice(0, 20));
|
||||||
|
|
||||||
|
/** 侧栏按「今天 / 昨天 / 近7天 / 更早」分组,对齐常见助手布局 */
|
||||||
|
const sessionGroups = computed<SessionGroup[]>(() => {
|
||||||
|
const buckets: Record<
|
||||||
|
'today' | 'yesterday' | 'week' | 'earlier',
|
||||||
|
AgentVO.Session[]
|
||||||
|
> = {
|
||||||
|
today: [],
|
||||||
|
yesterday: [],
|
||||||
|
week: [],
|
||||||
|
earlier: [],
|
||||||
|
};
|
||||||
|
const startToday = dayjs().startOf('day');
|
||||||
|
const startYesterday = startToday.subtract(1, 'day');
|
||||||
|
const startWeek = startToday.subtract(6, 'day');
|
||||||
|
for (const s of sessions.value) {
|
||||||
|
const t = sessionTime(s);
|
||||||
|
if (!t || !t.isBefore(startToday)) {
|
||||||
|
buckets.today.push(s);
|
||||||
|
} else if (!t.isBefore(startYesterday)) {
|
||||||
|
buckets.yesterday.push(s);
|
||||||
|
} else if (!t.isBefore(startWeek)) {
|
||||||
|
buckets.week.push(s);
|
||||||
|
} else {
|
||||||
|
buckets.earlier.push(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const labels: Array<[keyof typeof buckets, string]> = [
|
||||||
|
['today', '今天'],
|
||||||
|
['yesterday', '昨天'],
|
||||||
|
['week', '近 7 天'],
|
||||||
|
['earlier', '更早'],
|
||||||
|
];
|
||||||
|
return labels
|
||||||
|
.map(([key, label]) => ({ key, label, items: buckets[key] }))
|
||||||
|
.filter((g) => g.items.length > 0);
|
||||||
|
});
|
||||||
|
|
||||||
const bubbleViews = computed<BubbleView[]>(() =>
|
const bubbleViews = computed<BubbleView[]>(() =>
|
||||||
messages.value.map((m, idx) => {
|
messages.value.map((m, idx) => {
|
||||||
const isStreamingAssistant =
|
const isStreamingAssistant =
|
||||||
@@ -210,6 +350,71 @@ function onSessionClick(threadId: string) {
|
|||||||
activeThreadId.value = threadId;
|
activeThreadId.value = threadId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const deletingThreadId = ref<string | null>(null);
|
||||||
|
/** 打开中的会话操作菜单;用于悬停三点在菜单打开时保持可见 */
|
||||||
|
const sessionMenuOpenThreadId = ref<string | null>(null);
|
||||||
|
|
||||||
|
const sessionMenuItems: MenuProps['items'] = [
|
||||||
|
{
|
||||||
|
key: 'delete',
|
||||||
|
danger: true,
|
||||||
|
label: '删除',
|
||||||
|
icon: () => h(TrashIcon, { class: 'size-3.5' }),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function onSessionMenuOpenChange(threadId: string, open: boolean) {
|
||||||
|
sessionMenuOpenThreadId.value = open ? threadId : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSessionMenuClick(
|
||||||
|
threadId: string,
|
||||||
|
info: Parameters<NonNullable<MenuProps['onClick']>>[0],
|
||||||
|
) {
|
||||||
|
sessionMenuOpenThreadId.value = null;
|
||||||
|
if (info.key === 'delete') {
|
||||||
|
confirmDeleteSession(threadId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 确认后软删会话;若删的是当前会话则回到新对话空态 */
|
||||||
|
function confirmDeleteSession(threadId: string) {
|
||||||
|
Modal.confirm({
|
||||||
|
title: '删除会话',
|
||||||
|
content: '删除后无法在列表中恢复,确定删除该会话?',
|
||||||
|
okText: '删除',
|
||||||
|
okType: 'danger',
|
||||||
|
cancelText: '取消',
|
||||||
|
async onOk() {
|
||||||
|
await onDeleteSession(threadId);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onDeleteSession(threadId: string) {
|
||||||
|
if (sending.value) {
|
||||||
|
message.warning('回复生成中,请稍候再删除');
|
||||||
|
return Promise.reject(new Error('busy'));
|
||||||
|
}
|
||||||
|
if (deletingThreadId.value) {
|
||||||
|
return Promise.reject(new Error('deleting'));
|
||||||
|
}
|
||||||
|
deletingThreadId.value = threadId;
|
||||||
|
try {
|
||||||
|
await deleteAgentSessionApi(threadId);
|
||||||
|
sessions.value = sessions.value.filter((s) => s.threadId !== threadId);
|
||||||
|
if (activeThreadId.value === threadId) {
|
||||||
|
beginNewChat();
|
||||||
|
}
|
||||||
|
message.success('会话已删除');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '删除会话失败');
|
||||||
|
return Promise.reject(e);
|
||||||
|
} finally {
|
||||||
|
deletingThreadId.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSessions() {
|
async function refreshSessions() {
|
||||||
loadingSessions.value = true;
|
loadingSessions.value = true;
|
||||||
try {
|
try {
|
||||||
@@ -469,15 +674,139 @@ void loadEnabledModels().then(() => refreshSessions());
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page auto-content-height content-class="!p-0">
|
<Page auto-content-height content-class="!p-0">
|
||||||
<div class="flex h-full min-h-0 w-full overflow-hidden">
|
<div class="agent-shell flex h-full min-h-0 w-full overflow-hidden">
|
||||||
|
<!-- 左轨:顶栏标题/搜索/收起;收起后为图标轨(展开/新建/搜索/最近) -->
|
||||||
<aside
|
<aside
|
||||||
class="flex w-64 shrink-0 flex-col border-r border-border bg-card"
|
class="agent-sider flex shrink-0 flex-col border-r border-border transition-[width] duration-200"
|
||||||
|
:class="siderCollapsed ? 'w-[56px]' : 'w-[260px]'"
|
||||||
>
|
>
|
||||||
<div class="border-b border-border p-3">
|
<div
|
||||||
<Button type="primary" block @click="beginNewChat">
|
v-if="!siderCollapsed"
|
||||||
<template #icon><PlusOutlined /></template>
|
class="flex h-12 shrink-0 items-center gap-1 px-3"
|
||||||
|
>
|
||||||
|
<div class="min-w-0 flex-1 truncate text-sm font-semibold">
|
||||||
|
智能助手
|
||||||
|
</div>
|
||||||
|
<Tooltip title="搜索会话">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="搜索会话"
|
||||||
|
@click="openSessionSearch"
|
||||||
|
>
|
||||||
|
<SearchIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="收起侧栏">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="收起侧栏"
|
||||||
|
@click="setSiderCollapsed(true)"
|
||||||
|
>
|
||||||
|
<PanelCloseIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="flex min-h-0 flex-1 flex-col items-center gap-1 px-1.5 pt-0 pb-3"
|
||||||
|
>
|
||||||
|
<Tooltip title="展开侧栏" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="agent-sider-brand-btn hover:bg-muted group flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="展开侧栏"
|
||||||
|
@click="setSiderCollapsed(false)"
|
||||||
|
>
|
||||||
|
<AgentBrandIcon class="size-5 group-hover:hidden" />
|
||||||
|
<PanelOpenIcon class="hidden size-5 group-hover:block" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="新对话" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="新对话"
|
||||||
|
@click="beginNewChat"
|
||||||
|
>
|
||||||
|
<NewChatIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Tooltip title="搜索会话" placement="right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="搜索会话"
|
||||||
|
@click="openSessionSearch"
|
||||||
|
>
|
||||||
|
<SearchIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
<Popover
|
||||||
|
:open="collapsedRecentOpen"
|
||||||
|
trigger="click"
|
||||||
|
placement="rightTop"
|
||||||
|
:overlay-style="{ padding: 0 }"
|
||||||
|
@update:open="onCollapsedRecentOpenChange"
|
||||||
|
>
|
||||||
|
<template #content>
|
||||||
|
<div class="agent-sider-pop flex w-64 flex-col p-2">
|
||||||
|
<div class="text-muted-foreground px-1 pb-2 text-xs font-medium">
|
||||||
|
最近聊天
|
||||||
|
</div>
|
||||||
|
<div class="max-h-72 overflow-y-auto">
|
||||||
|
<Empty
|
||||||
|
v-if="recentSessions.length === 0"
|
||||||
|
class="py-6"
|
||||||
|
description="暂无会话"
|
||||||
|
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
v-for="s in recentSessions"
|
||||||
|
:key="s.threadId"
|
||||||
|
type="button"
|
||||||
|
class="agent-session-item mb-0.5 w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'agent-session-item--active'
|
||||||
|
: ''
|
||||||
|
"
|
||||||
|
@click="pickSessionFromOverlay(s.threadId)"
|
||||||
|
>
|
||||||
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
|
{{ s.title || '新对话' }}
|
||||||
|
</EllipsisText>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<Tooltip
|
||||||
|
:title="collapsedRecentOpen ? '' : '最近聊天'"
|
||||||
|
placement="right"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
:class="collapsedRecentOpen ? 'bg-muted text-foreground' : ''"
|
||||||
|
aria-label="最近聊天"
|
||||||
|
>
|
||||||
|
<RecentChatIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="!siderCollapsed">
|
||||||
|
<div class="px-3 pb-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted flex h-9 w-full items-center gap-2 rounded-lg px-3 text-sm font-medium transition-colors"
|
||||||
|
@click="beginNewChat"
|
||||||
|
>
|
||||||
|
<PlusOutlined />
|
||||||
新对话
|
新对话
|
||||||
</Button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="relative min-h-0 flex-1">
|
<div class="relative min-h-0 flex-1">
|
||||||
<div
|
<div
|
||||||
@@ -488,163 +817,359 @@ void loadEnabledModels().then(() => refreshSessions());
|
|||||||
</div>
|
</div>
|
||||||
<Empty
|
<Empty
|
||||||
v-if="!loadingSessions && sessions.length === 0 && !composingNew"
|
v-if="!loadingSessions && sessions.length === 0 && !composingNew"
|
||||||
class="mt-10 px-2"
|
class="mt-12 px-3"
|
||||||
description="暂无会话"
|
description="暂无会话"
|
||||||
/>
|
/>
|
||||||
<div v-else class="h-full space-y-1 overflow-y-auto px-3 py-2">
|
<div v-else class="h-full overflow-y-auto px-2 pb-4">
|
||||||
<button
|
<button
|
||||||
v-if="composingNew"
|
v-if="composingNew"
|
||||||
type="button"
|
type="button"
|
||||||
class="bg-primary/10 text-primary mb-1 w-full rounded-lg px-3 py-2 text-left text-sm"
|
class="bg-muted mb-3 w-full rounded-lg px-3 py-2 text-left text-sm font-medium"
|
||||||
>
|
>
|
||||||
<div class="truncate font-medium">新对话</div>
|
新对话
|
||||||
<div class="text-muted-foreground mt-0.5 truncate text-xs">
|
|
||||||
尚未发送
|
|
||||||
</div>
|
|
||||||
</button>
|
</button>
|
||||||
<button
|
<div
|
||||||
v-for="s in sessions"
|
v-for="group in sessionGroups"
|
||||||
|
:key="group.key"
|
||||||
|
class="mb-3"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="text-muted-foreground px-3 pb-1 pt-2 text-xs font-medium"
|
||||||
|
>
|
||||||
|
{{ group.label }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="s in group.items"
|
||||||
:key="s.threadId"
|
:key="s.threadId"
|
||||||
type="button"
|
class="agent-session-item group mb-0.5 flex w-full cursor-pointer items-center gap-1 rounded-lg px-2 py-1.5 text-left text-sm transition-colors"
|
||||||
class="w-full rounded-lg px-3 py-2 text-left text-sm transition-colors"
|
|
||||||
:class="
|
:class="
|
||||||
s.threadId === activeThreadId
|
s.threadId === activeThreadId
|
||||||
? 'bg-primary/10 text-primary'
|
? 'agent-session-item--active'
|
||||||
: 'hover:bg-muted text-foreground'
|
: ''
|
||||||
"
|
"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="min-w-0 flex-1 truncate px-1 py-0.5 text-left"
|
||||||
@click="onSessionClick(s.threadId)"
|
@click="onSessionClick(s.threadId)"
|
||||||
>
|
>
|
||||||
<div class="truncate font-medium">{{ s.title || '新对话' }}</div>
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
<div
|
{{ s.title || '新对话' }}
|
||||||
v-if="s.updatedAt || s.lastMessageAt"
|
</EllipsisText>
|
||||||
class="text-muted-foreground mt-0.5 truncate text-xs"
|
|
||||||
>
|
|
||||||
{{ s.updatedAt || s.lastMessageAt }}
|
|
||||||
</div>
|
|
||||||
</button>
|
</button>
|
||||||
|
<Dropdown
|
||||||
|
:trigger="['click']"
|
||||||
|
:open="sessionMenuOpenThreadId === s.threadId"
|
||||||
|
@open-change="
|
||||||
|
(open: boolean) =>
|
||||||
|
onSessionMenuOpenChange(s.threadId, open)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="text-muted-foreground hover:bg-accent hover:text-foreground flex size-7 shrink-0 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100"
|
||||||
|
:class="
|
||||||
|
sessionMenuOpenThreadId === s.threadId ||
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'opacity-100'
|
||||||
|
: ''
|
||||||
|
"
|
||||||
|
aria-label="会话操作"
|
||||||
|
@click.stop
|
||||||
|
>
|
||||||
|
<MoreIcon class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
<template #overlay>
|
||||||
|
<Menu
|
||||||
|
:items="sessionMenuItems"
|
||||||
|
@click="
|
||||||
|
(info) => onSessionMenuClick(s.threadId, info)
|
||||||
|
"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</Dropdown>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<section class="agent-chat-main flex min-h-0 min-w-0 flex-1 flex-col">
|
<!-- 主区:空态居中 / 对话时消息 + 底栏输入 -->
|
||||||
<header
|
<section class="agent-main relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||||
class="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4"
|
|
||||||
>
|
|
||||||
<span class="min-w-0 flex-1 truncate font-medium">
|
|
||||||
{{
|
|
||||||
composingNew
|
|
||||||
? '新对话'
|
|
||||||
: activeSession?.title || '智能助手'
|
|
||||||
}}
|
|
||||||
</span>
|
|
||||||
<Select
|
|
||||||
:value="selectedModelKey"
|
|
||||||
:options="modelOptions"
|
|
||||||
:loading="patchingModel"
|
|
||||||
:disabled="sending || enabledModels.length === 0"
|
|
||||||
placeholder="选择模型"
|
|
||||||
class="w-64 shrink-0"
|
|
||||||
:allow-clear="false"
|
|
||||||
@change="(v) => onModelChange(String(v ?? ''))"
|
|
||||||
/>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
|
||||||
<div
|
<div
|
||||||
v-if="showMessageLoading"
|
v-if="showMessageLoading"
|
||||||
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
||||||
>
|
>
|
||||||
加载消息…
|
加载消息…
|
||||||
</div>
|
</div>
|
||||||
<Empty
|
|
||||||
v-if="!showStarter && !showMessageLoading && messages.length === 0"
|
<!-- 空态:问候 + 居中输入 + chips -->
|
||||||
class="absolute inset-0 flex items-center justify-center"
|
|
||||||
description="开始提问吧(需先在「模型管理」配置 API)"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
ref="messagePaneRef"
|
|
||||||
class="agent-td-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-4"
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
v-if="showStarter"
|
v-if="showStarter"
|
||||||
class="mx-auto flex h-full max-w-xl flex-col justify-center px-2 py-6"
|
class="flex min-h-0 flex-1 flex-col items-center justify-center px-4 pb-16 pt-8"
|
||||||
>
|
>
|
||||||
<div class="text-base font-medium">智能助手可以帮你看经营数据</div>
|
<h1 class="mb-10 text-center text-3xl font-semibold tracking-tight">
|
||||||
<p class="text-muted-foreground mt-2 text-sm leading-6">
|
{{ greeting }}
|
||||||
直接问销售额、单量、净利、费比。说「近7天」「昨天」「本周」「本月」即可,不必自己换算日期。查某家店或某个商品时,带上店铺名或商品名。
|
</h1>
|
||||||
</p>
|
<div class="agent-composer w-full max-w-[720px]">
|
||||||
<ul
|
|
||||||
class="text-muted-foreground mt-3 list-disc space-y-1 pl-5 text-sm leading-6"
|
|
||||||
>
|
|
||||||
<li>工作台概览:销售额、单量、净利、费比</li>
|
|
||||||
<li>店铺 / 商品:销量、ROI、目标达成</li>
|
|
||||||
</ul>
|
|
||||||
<div class="mt-4 flex flex-col gap-2">
|
|
||||||
<button
|
|
||||||
v-for="item in starterPrompts"
|
|
||||||
:key="item"
|
|
||||||
type="button"
|
|
||||||
class="hover:border-primary hover:bg-primary/5 rounded-lg border border-border bg-card px-3 py-2 text-left text-sm transition-colors"
|
|
||||||
@click="applyStarterPrompt(item)"
|
|
||||||
>
|
|
||||||
{{ item }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<ChatItem
|
|
||||||
v-for="item in bubbleViews"
|
|
||||||
:key="item.id"
|
|
||||||
class="agent-td-item"
|
|
||||||
:role="item.role"
|
|
||||||
:name="item.name"
|
|
||||||
:content="item.content"
|
|
||||||
:text-loading="item.textLoading"
|
|
||||||
variant="base"
|
|
||||||
animation="gradient"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
v-if="toolStatusActive && toolStatusLabel"
|
|
||||||
class="text-muted-foreground mx-auto flex max-w-3xl items-center gap-2 px-4 py-1 text-xs"
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
|
||||||
/>
|
|
||||||
<span>{{ toolStatusLabel }}…</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="shrink-0 border-t border-border p-3">
|
|
||||||
<CatalogCiteSender
|
<CatalogCiteSender
|
||||||
v-model="draft"
|
v-model="draft"
|
||||||
v-model:cites="citations"
|
v-model:cites="citations"
|
||||||
:loading="sending"
|
:loading="sending"
|
||||||
@send="onSenderSend"
|
@send="onSenderSend"
|
||||||
@stop="onSenderStop"
|
@stop="onSenderStop"
|
||||||
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="agent-model-select min-w-0 max-w-[200px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
/>
|
/>
|
||||||
|
</template>
|
||||||
|
</CatalogCiteSender>
|
||||||
|
<div class="mt-5 flex flex-wrap justify-center gap-2">
|
||||||
|
<Tooltip
|
||||||
|
v-for="item in starterPrompts"
|
||||||
|
:key="item.label"
|
||||||
|
:title="item.prompt"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted border-border text-foreground/80 hover:text-foreground inline-flex cursor-pointer items-center gap-2 rounded-full border bg-card px-3.5 py-1.5 text-sm transition-colors"
|
||||||
|
@click="applyStarterPrompt(item.prompt)"
|
||||||
|
>
|
||||||
|
<component :is="item.icon" class="text-muted-foreground" />
|
||||||
|
{{ item.label }}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 对话态:可滚动消息 + 底部输入 -->
|
||||||
|
<template v-else>
|
||||||
|
<div
|
||||||
|
ref="messagePaneRef"
|
||||||
|
class="agent-td-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-6"
|
||||||
|
>
|
||||||
|
<Empty
|
||||||
|
v-if="!showMessageLoading && messages.length === 0"
|
||||||
|
class="mt-24"
|
||||||
|
description="开始提问吧(需先在「模型管理」配置 API)"
|
||||||
|
/>
|
||||||
|
<div class="mx-auto max-w-[760px]">
|
||||||
|
<ChatItem
|
||||||
|
v-for="item in bubbleViews"
|
||||||
|
:key="item.id"
|
||||||
|
class="agent-td-item"
|
||||||
|
:class="[
|
||||||
|
item.role === 'user'
|
||||||
|
? 'agent-td-item--user'
|
||||||
|
: 'agent-td-item--assistant',
|
||||||
|
{ 'agent-td-item--loading': item.textLoading },
|
||||||
|
]"
|
||||||
|
:role="item.role"
|
||||||
|
:name="item.name"
|
||||||
|
:content="
|
||||||
|
item.textLoading || item.role === 'user'
|
||||||
|
? undefined
|
||||||
|
: item.content
|
||||||
|
"
|
||||||
|
:text-loading="false"
|
||||||
|
variant="base"
|
||||||
|
>
|
||||||
|
<!-- ChatItem.animation 无 dots,等待首包时用 ChatLoading -->
|
||||||
|
<template v-if="item.textLoading" #content>
|
||||||
|
<ChatLoading animation="dots" />
|
||||||
|
</template>
|
||||||
|
<template v-else-if="item.role === 'user'" #content>
|
||||||
|
<CatalogCiteRichText :text="item.content" />
|
||||||
|
</template>
|
||||||
|
</ChatItem>
|
||||||
|
<div
|
||||||
|
v-if="toolStatusActive && toolStatusLabel"
|
||||||
|
class="agent-tool-status text-muted-foreground flex items-center gap-2 px-2 py-1 text-xs"
|
||||||
|
>
|
||||||
|
<ChatLoading animation="dots" :text="`${toolStatusLabel}…`" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="agent-composer-dock shrink-0 px-4 pb-5 pt-2">
|
||||||
|
<div class="agent-composer mx-auto max-w-[720px]">
|
||||||
|
<CatalogCiteSender
|
||||||
|
v-model="draft"
|
||||||
|
v-model:cites="citations"
|
||||||
|
:loading="sending"
|
||||||
|
@send="onSenderSend"
|
||||||
|
@stop="onSenderStop"
|
||||||
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="agent-model-select min-w-0 max-w-[200px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</CatalogCiteSender>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
<SessionSearchModal
|
||||||
|
ref="sessionSearchModalRef"
|
||||||
|
:sessions="sessions"
|
||||||
|
:active-thread-id="activeThreadId"
|
||||||
|
@pick="pickSessionFromOverlay"
|
||||||
|
/>
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.agent-td-chat {
|
/* 浅色:侧栏略深于主区;深色沿用 background-deep */
|
||||||
--td-bg-color-container: transparent;
|
.agent-sider {
|
||||||
padding-inline: 28px;
|
background: hsl(var(--muted) / 0.45);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html.dark .agent-sider,
|
||||||
|
.dark .agent-sider {
|
||||||
|
background: hsl(var(--background-deep, var(--background)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item:hover {
|
||||||
|
background: hsl(var(--accent));
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item,
|
||||||
|
.agent-session-item :deep(*) {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-session-item--active {
|
||||||
|
background: hsl(var(--background));
|
||||||
|
font-weight: 500;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border));
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-session-item--active,
|
||||||
|
.dark .agent-session-item--active {
|
||||||
|
background: hsl(var(--muted));
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-composer :deep(.t-chat-sender) {
|
||||||
|
border-radius: 24px;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border) / 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-composer :deep(.t-chat-sender__textarea__wrapper) {
|
||||||
|
border-radius: 24px;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-model-select :deep(.ant-select-selector) {
|
||||||
|
border-radius: 999px !important;
|
||||||
|
}
|
||||||
|
|
||||||
.agent-td-item {
|
.agent-td-item {
|
||||||
margin-bottom: 12px;
|
/* ChatItem 根节点即 .t-chat__inner,样式打在本类上 */
|
||||||
}
|
display: flex;
|
||||||
/* 气泡按内容收缩,左右再留一截,避免贴边铺满 */
|
|
||||||
.agent-td-item :deep(.t-chat__inner) {
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding-inline: 4px;
|
width: 100%;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding-inline: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.agent-td-item :deep(.t-chat__content) {
|
.agent-td-item :deep(.t-chat__content) {
|
||||||
width: auto;
|
flex: 0 1 auto !important;
|
||||||
max-width: min(720px, calc(100% - 32px));
|
width: fit-content !important;
|
||||||
|
max-width: min(680px, 100%);
|
||||||
|
justify-content: flex-start !important;
|
||||||
}
|
}
|
||||||
.agent-td-item :deep(.t-chat__inner.user) {
|
|
||||||
|
.agent-td-item--assistant {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--assistant :deep(.t-chat__content) {
|
||||||
|
align-self: flex-start;
|
||||||
|
align-items: flex-start !important;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user {
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user :deep(.t-chat__content) {
|
||||||
|
align-self: flex-end;
|
||||||
|
align-items: flex-end !important;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item :deep(.t-chat__detail) {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item :deep(.t-chat__text__name) {
|
||||||
|
opacity: 0.55;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-tool-status {
|
||||||
|
justify-content: flex-start;
|
||||||
|
padding-inline: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 浅色:给气泡补边框与底色,避免与主背景糊在一起 */
|
||||||
|
.agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.agent-td-item :deep(.t-chat__detail) {
|
||||||
|
border: 1px solid hsl(var(--border));
|
||||||
|
border-radius: 12px;
|
||||||
|
background: hsl(var(--muted) / 0.65);
|
||||||
|
padding-block: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
.agent-td-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.1);
|
||||||
|
border-color: hsl(var(--primary) / 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .agent-td-item :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .agent-td-item :deep(.t-chat__detail) {
|
||||||
|
border-color: transparent;
|
||||||
|
background: hsl(var(--muted) / 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
html.dark .agent-td-item.user :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .agent-td-item--user :deep(.t-chat__detail),
|
||||||
|
.dark .agent-td-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.22);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
/**
|
||||||
|
* 会话搜索弹窗:居中打开,按标题过滤;点选后回传 threadId。
|
||||||
|
*/
|
||||||
|
import { computed, nextTick, ref } from 'vue';
|
||||||
|
|
||||||
|
import { EllipsisText, useVbenModal } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import { Empty, Input } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import type { AgentVO } from '#/api/agent';
|
||||||
|
|
||||||
|
defineOptions({ name: 'AgentSessionSearchModal' });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
sessions: AgentVO.Session[];
|
||||||
|
activeThreadId?: string | null;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
pick: [threadId: string];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const query = ref('');
|
||||||
|
const inputRef = ref<{ focus?: () => void } | null>(null);
|
||||||
|
|
||||||
|
const hits = computed(() => {
|
||||||
|
const q = query.value.trim().toLowerCase();
|
||||||
|
const list = props.sessions || [];
|
||||||
|
if (!q) return list.slice(0, 30);
|
||||||
|
return list
|
||||||
|
.filter((s) => (s.title || '新对话').toLowerCase().includes(q))
|
||||||
|
.slice(0, 30);
|
||||||
|
});
|
||||||
|
|
||||||
|
const [Modal, modalApi] = useVbenModal({
|
||||||
|
title: '搜索会话',
|
||||||
|
class: 'w-[520px]',
|
||||||
|
draggable: true,
|
||||||
|
footer: false,
|
||||||
|
showConfirmButton: false,
|
||||||
|
showCancelButton: false,
|
||||||
|
onOpenChange(isOpen: boolean) {
|
||||||
|
if (!isOpen) {
|
||||||
|
query.value = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
query.value = '';
|
||||||
|
void nextTick(() => inputRef.value?.focus?.());
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
modalApi.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
function pick(threadId: string) {
|
||||||
|
emit('pick', threadId);
|
||||||
|
modalApi.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ open });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Modal>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<Input
|
||||||
|
ref="inputRef"
|
||||||
|
v-model:value="query"
|
||||||
|
allow-clear
|
||||||
|
placeholder="按会话标题搜索"
|
||||||
|
size="large"
|
||||||
|
/>
|
||||||
|
<div class="max-h-[360px] min-h-[120px] overflow-y-auto">
|
||||||
|
<Empty
|
||||||
|
v-if="hits.length === 0"
|
||||||
|
class="py-10"
|
||||||
|
:description="query.trim() ? '无匹配会话' : '暂无会话'"
|
||||||
|
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
v-for="s in hits"
|
||||||
|
:key="s.threadId"
|
||||||
|
type="button"
|
||||||
|
class="mb-0.5 w-full rounded-lg px-3 py-2.5 text-left text-sm transition-colors"
|
||||||
|
:class="
|
||||||
|
s.threadId === activeThreadId
|
||||||
|
? 'bg-muted font-medium'
|
||||||
|
: 'hover:bg-muted/70'
|
||||||
|
"
|
||||||
|
@click="pick(s.threadId)"
|
||||||
|
>
|
||||||
|
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||||
|
{{ s.title || '新对话' }}
|
||||||
|
</EllipsisText>
|
||||||
|
<div
|
||||||
|
v-if="s.updatedAt || s.lastMessageAt"
|
||||||
|
class="text-muted-foreground mt-0.5 text-xs"
|
||||||
|
>
|
||||||
|
{{ s.updatedAt || s.lastMessageAt }}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</template>
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
FormItem,
|
FormItem,
|
||||||
Input,
|
Input,
|
||||||
InputPassword,
|
InputPassword,
|
||||||
|
Select,
|
||||||
message,
|
message,
|
||||||
} from 'ant-design-vue';
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
@@ -28,8 +29,18 @@ const form = ref({
|
|||||||
baseUrl: '',
|
baseUrl: '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
displayName: '',
|
displayName: '',
|
||||||
|
apiStyle: 'auto',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const apiStyleOptions = [
|
||||||
|
{
|
||||||
|
value: 'auto',
|
||||||
|
label: '自动(优先 Responses+store,失败再降级)',
|
||||||
|
},
|
||||||
|
{ value: 'completions', label: 'Chat Completions' },
|
||||||
|
{ value: 'responses', label: 'Responses API' },
|
||||||
|
];
|
||||||
|
|
||||||
const isEdit = computed(() => !!editing.value);
|
const isEdit = computed(() => !!editing.value);
|
||||||
const modalTitle = computed(() =>
|
const modalTitle = computed(() =>
|
||||||
isEdit.value ? '编辑提供商' : '添加提供商',
|
isEdit.value ? '编辑提供商' : '添加提供商',
|
||||||
@@ -52,6 +63,7 @@ function open(row?: AgentVO.LlmProvider) {
|
|||||||
baseUrl: row?.baseUrl || '',
|
baseUrl: row?.baseUrl || '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
displayName: row?.displayName || '',
|
displayName: row?.displayName || '',
|
||||||
|
apiStyle: row?.apiStyle || 'auto',
|
||||||
};
|
};
|
||||||
modalApi.setState({ title: modalTitle.value });
|
modalApi.setState({ title: modalTitle.value });
|
||||||
modalApi.open();
|
modalApi.open();
|
||||||
@@ -74,6 +86,7 @@ async function handleSubmit() {
|
|||||||
baseUrl: form.value.baseUrl.trim(),
|
baseUrl: form.value.baseUrl.trim(),
|
||||||
apiKey: form.value.apiKey.trim() || undefined,
|
apiKey: form.value.apiKey.trim() || undefined,
|
||||||
displayName: form.value.displayName.trim(),
|
displayName: form.value.displayName.trim(),
|
||||||
|
apiStyle: form.value.apiStyle,
|
||||||
});
|
});
|
||||||
message.success('已保存');
|
message.success('已保存');
|
||||||
} else {
|
} else {
|
||||||
@@ -81,6 +94,7 @@ async function handleSubmit() {
|
|||||||
baseUrl: form.value.baseUrl.trim(),
|
baseUrl: form.value.baseUrl.trim(),
|
||||||
apiKey: form.value.apiKey.trim(),
|
apiKey: form.value.apiKey.trim(),
|
||||||
displayName: form.value.displayName.trim() || undefined,
|
displayName: form.value.displayName.trim() || undefined,
|
||||||
|
apiStyle: form.value.apiStyle,
|
||||||
});
|
});
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
}
|
}
|
||||||
@@ -116,6 +130,13 @@ defineExpose({ open });
|
|||||||
>
|
>
|
||||||
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
<FormItem label="API 协议">
|
||||||
|
<Select
|
||||||
|
v-model:value="form.apiStyle"
|
||||||
|
:options="apiStyleOptions"
|
||||||
|
class="w-full"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
<FormItem label="备注(可选)">
|
<FormItem label="备注(可选)">
|
||||||
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
|||||||
@@ -65,6 +65,19 @@ const baseColumns: VxeGridProps<ProviderRow>['columns'] = [
|
|||||||
minWidth: 220,
|
minWidth: 220,
|
||||||
showOverflow: 'tooltip',
|
showOverflow: 'tooltip',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
field: 'apiStyle',
|
||||||
|
title: 'API 协议',
|
||||||
|
minWidth: 120,
|
||||||
|
formatter: ({ row }) => {
|
||||||
|
const m: Record<string, string> = {
|
||||||
|
auto: '自动',
|
||||||
|
completions: 'Completions',
|
||||||
|
responses: 'Responses',
|
||||||
|
};
|
||||||
|
return m[row.apiStyle || 'auto'] || row.apiStyle || '自动';
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
field: 'apiKeyMasked',
|
field: 'apiKeyMasked',
|
||||||
title: 'API Key',
|
title: 'API Key',
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { onMounted, ref } from 'vue';
|
/**
|
||||||
|
* 助手长期记忆:Page + VXE 表格(与反馈/API Key 等列表页一致)。
|
||||||
|
*/
|
||||||
|
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { ref } from 'vue';
|
||||||
|
|
||||||
import { Button, Card, Empty, Spin, message } from 'ant-design-vue';
|
import { EllipsisText, Page } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import { Alert, Button, Modal, Popconfirm, Space, Tag, message } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||||
import {
|
import {
|
||||||
deleteAgentMemoryApi,
|
deleteAgentMemoryApi,
|
||||||
listAgentMemoriesApi,
|
listAgentMemoriesApi,
|
||||||
@@ -13,79 +19,193 @@ import {
|
|||||||
|
|
||||||
defineOptions({ name: 'AgentMemories' });
|
defineOptions({ name: 'AgentMemories' });
|
||||||
|
|
||||||
const loading = ref(true);
|
const loading = ref(false);
|
||||||
const memories = ref<AgentVO.Memory[]>([]);
|
|
||||||
|
|
||||||
async function loadMemories() {
|
const KIND_META: Record<string, { color: string; label: string }> = {
|
||||||
|
note: { color: 'blue', label: '笔记' },
|
||||||
|
preference: { color: 'purple', label: '偏好' },
|
||||||
|
fact: { color: 'green', label: '事实' },
|
||||||
|
};
|
||||||
|
|
||||||
|
function kindMeta(kind?: string) {
|
||||||
|
const k = (kind || 'note').trim() || 'note';
|
||||||
|
return KIND_META[k] || { color: 'default', label: k };
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(raw?: string) {
|
||||||
|
if (!raw) return '—';
|
||||||
|
// 后端多为 ISO;展示时去掉过长毫秒/Z
|
||||||
|
return raw.replace('T', ' ').replace(/\.\d+Z?$/, '').replace(/Z$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
const gridOptions: VxeGridProps<AgentVO.Memory> = {
|
||||||
|
columns: [
|
||||||
|
{ type: 'seq', width: 56, title: '序号' },
|
||||||
|
{
|
||||||
|
field: 'kind',
|
||||||
|
title: '类型',
|
||||||
|
width: 96,
|
||||||
|
slots: { default: 'kind' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'summary',
|
||||||
|
title: '摘要',
|
||||||
|
minWidth: 200,
|
||||||
|
slots: { default: 'summary' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'text',
|
||||||
|
title: '原文',
|
||||||
|
minWidth: 240,
|
||||||
|
slots: { default: 'text' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'key',
|
||||||
|
title: '键',
|
||||||
|
width: 120,
|
||||||
|
showOverflow: 'tooltip',
|
||||||
|
formatter: ({ cellValue }) => cellValue || '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'updatedAt',
|
||||||
|
title: '更新时间',
|
||||||
|
width: 176,
|
||||||
|
formatter: ({ cellValue }) => formatTime(cellValue),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 96,
|
||||||
|
fixed: 'right',
|
||||||
|
slots: { default: 'action' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
height: 'auto',
|
||||||
|
border: true,
|
||||||
|
stripe: true,
|
||||||
|
rowConfig: { isHover: true },
|
||||||
|
showOverflow: true,
|
||||||
|
size: 'small',
|
||||||
|
toolbarConfig: {
|
||||||
|
custom: true,
|
||||||
|
refresh: true,
|
||||||
|
zoom: true,
|
||||||
|
},
|
||||||
|
pagerConfig: {
|
||||||
|
enabled: true,
|
||||||
|
pageSizes: [10, 20, 50],
|
||||||
|
layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage'],
|
||||||
|
},
|
||||||
|
proxyConfig: {
|
||||||
|
ajax: {
|
||||||
|
query: async ({ page }) => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await listAgentMemoriesApi();
|
const res = await listAgentMemoriesApi();
|
||||||
memories.value = res.items || [];
|
const all = res.items || [];
|
||||||
|
const pageSize = page.pageSize || 20;
|
||||||
|
const current = page.currentPage || 1;
|
||||||
|
const start = (current - 1) * pageSize;
|
||||||
|
return {
|
||||||
|
items: all.slice(start, start + pageSize),
|
||||||
|
total: all.length,
|
||||||
|
};
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '加载记忆失败');
|
message.error(e?.message || '加载记忆失败');
|
||||||
|
return { items: [], total: 0 };
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
async function removeMemory(id: string) {
|
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||||
|
|
||||||
|
async function removeMemory(row: AgentVO.Memory) {
|
||||||
try {
|
try {
|
||||||
await deleteAgentMemoryApi(id);
|
await deleteAgentMemoryApi(row.id);
|
||||||
memories.value = memories.value.filter((m) => m.id !== id);
|
message.success('已删除');
|
||||||
message.success('已删除记忆');
|
await gridApi.reload();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '删除失败');
|
message.error(e?.message || '删除失败');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
function clearAll() {
|
||||||
void loadMemories();
|
Modal.confirm({
|
||||||
});
|
title: '清空全部助手记忆?',
|
||||||
|
content: '将逐条删除当前列表中的记忆,且不可恢复。',
|
||||||
|
okText: '清空',
|
||||||
|
okType: 'danger',
|
||||||
|
cancelText: '取消',
|
||||||
|
async onOk() {
|
||||||
|
const res = await listAgentMemoriesApi();
|
||||||
|
const items = res.items || [];
|
||||||
|
for (const m of items) {
|
||||||
|
await deleteAgentMemoryApi(m.id);
|
||||||
|
}
|
||||||
|
message.success(items.length ? `已清空 ${items.length} 条` : '暂无记忆');
|
||||||
|
await gridApi.reload();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page auto-content-height>
|
<Page
|
||||||
<div class="relative mx-auto max-w-3xl pb-8">
|
auto-content-height
|
||||||
<div
|
title="助手记忆"
|
||||||
v-if="loading"
|
description="智能助手跨会话保存的称呼、偏好与事实,按需检索,不会默认整包注入对话。"
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
|
||||||
>
|
>
|
||||||
<Spin />
|
<Alert
|
||||||
</div>
|
type="info"
|
||||||
|
show-icon
|
||||||
<Card title="我的记忆" :bordered="false">
|
class="mb-4"
|
||||||
<p class="text-muted-foreground mb-4 text-sm">
|
message="在智能助手里发送「记住:……」即可写入;不需要的条目可随时删除。"
|
||||||
在智能助手对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
|
|
||||||
</p>
|
|
||||||
<Empty
|
|
||||||
v-if="!loading && memories.length === 0"
|
|
||||||
description="暂无记忆"
|
|
||||||
/>
|
/>
|
||||||
<div
|
|
||||||
v-for="m in memories"
|
<Grid :loading="loading">
|
||||||
:key="m.id"
|
<template #toolbar-tools>
|
||||||
class="mb-2 flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm"
|
<Space>
|
||||||
|
<Button danger @click="clearAll">清空全部</Button>
|
||||||
|
</Space>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #kind="{ row }">
|
||||||
|
<Tag :color="kindMeta(row.kind).color">
|
||||||
|
{{ kindMeta(row.kind).label }}
|
||||||
|
</Tag>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #summary="{ row }">
|
||||||
|
<EllipsisText :max-width="360" tooltip-when-ellipsis>
|
||||||
|
{{ row.summary || row.text || '—' }}
|
||||||
|
</EllipsisText>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #text="{ row }">
|
||||||
|
<EllipsisText
|
||||||
|
v-if="row.summary && row.text && row.summary !== row.text"
|
||||||
|
:max-width="420"
|
||||||
|
tooltip-when-ellipsis
|
||||||
>
|
>
|
||||||
<div class="min-w-0 flex-1">
|
{{ row.text }}
|
||||||
<div class="break-words">{{ m.summary || m.text }}</div>
|
</EllipsisText>
|
||||||
<div
|
<span v-else class="text-muted-foreground">—</span>
|
||||||
v-if="m.summary && m.text && m.summary !== m.text"
|
</template>
|
||||||
class="text-muted-foreground mt-1 break-words text-xs"
|
|
||||||
|
<template #action="{ row }">
|
||||||
|
<Popconfirm
|
||||||
|
title="确定删除这条记忆?"
|
||||||
|
ok-text="删除"
|
||||||
|
cancel-text="取消"
|
||||||
|
ok-type="danger"
|
||||||
|
@confirm="removeMemory(row)"
|
||||||
>
|
>
|
||||||
{{ m.text }}
|
<Button type="link" size="small" danger>删除</Button>
|
||||||
</div>
|
</Popconfirm>
|
||||||
<div
|
</template>
|
||||||
v-if="m.updatedAt"
|
</Grid>
|
||||||
class="text-muted-foreground mt-1 text-xs"
|
|
||||||
>
|
|
||||||
{{ m.updatedAt }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
|
||||||
删除
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ import {
|
|||||||
} from '#/utils/overview-date-range';
|
} from '#/utils/overview-date-range';
|
||||||
|
|
||||||
import WorkbenchFinanceTab from './tabs/finance/index.vue';
|
import WorkbenchFinanceTab from './tabs/finance/index.vue';
|
||||||
|
import WorkbenchRegionTab from './tabs/region/index.vue';
|
||||||
import WorkbenchMultiTab from './tabs/multi/index.vue';
|
import WorkbenchMultiTab from './tabs/multi/index.vue';
|
||||||
import WorkbenchPeriodCompareTab from './tabs/compare/index.vue';
|
import WorkbenchPeriodCompareTab from './tabs/compare/index.vue';
|
||||||
import WorkbenchSalesRankTab from './tabs/sales-rank/index.vue';
|
import WorkbenchSalesRankTab from './tabs/sales-rank/index.vue';
|
||||||
@@ -126,9 +127,9 @@ const customDateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>([
|
|||||||
dateRange.value[1],
|
dateRange.value[1],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
/** 触发器:灰底外框 + 白底内面板(与改前一致) */
|
/** 触发器:灰底外框 + 白底内面板(窄屏也保持横向,避免 w-full 整行换行) */
|
||||||
const toolbarShellClass =
|
const toolbarShellClass =
|
||||||
'flex w-full flex-col gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 p-1.5 sm:w-auto sm:flex-row sm:items-center sm:gap-2 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]';
|
'flex w-auto shrink-0 flex-row items-center gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 p-1.5 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]';
|
||||||
|
|
||||||
const toolbarPanelClass =
|
const toolbarPanelClass =
|
||||||
'rounded-xl bg-white dark:bg-[hsl(222.34deg_10.43%_14%)]';
|
'rounded-xl bg-white dark:bg-[hsl(222.34deg_10.43%_14%)]';
|
||||||
@@ -568,6 +569,11 @@ async function softRefreshActiveTab() {
|
|||||||
await periodCompareTabRef.value?.refresh?.({ silent: true });
|
await periodCompareTabRef.value?.refresh?.({ silent: true });
|
||||||
softInvalidateDataTabs();
|
softInvalidateDataTabs();
|
||||||
})()
|
})()
|
||||||
|
: activeTab.value === 'region'
|
||||||
|
? (async () => {
|
||||||
|
await regionTabRef.value?.redraw();
|
||||||
|
softInvalidateDataTabs();
|
||||||
|
})()
|
||||||
: (async () => {
|
: (async () => {
|
||||||
const tab = activeTab.value as DataTabKey;
|
const tab = activeTab.value as DataTabKey;
|
||||||
await loadTabData(tab, { force: true });
|
await loadTabData(tab, { force: true });
|
||||||
@@ -591,6 +597,11 @@ async function refreshActiveDataTab(opts?: { force?: boolean }) {
|
|||||||
await periodCompareTabRef.value?.refresh?.({ silent: !!opts?.force });
|
await periodCompareTabRef.value?.refresh?.({ silent: !!opts?.force });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (activeTab.value === 'region') {
|
||||||
|
// Mock Tab:随筛选种子变化即可,触发重绘
|
||||||
|
await regionTabRef.value?.redraw();
|
||||||
|
return;
|
||||||
|
}
|
||||||
await loadTabData(activeTab.value as DataTabKey, opts);
|
await loadTabData(activeTab.value as DataTabKey, opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -730,6 +741,7 @@ function handleSkuNavigate(skuId: number) {
|
|||||||
const financeTabRef = ref<InstanceType<typeof WorkbenchFinanceTab> | null>(
|
const financeTabRef = ref<InstanceType<typeof WorkbenchFinanceTab> | null>(
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
const regionTabRef = ref<InstanceType<typeof WorkbenchRegionTab> | null>(null);
|
||||||
const multiTabRef = ref<InstanceType<typeof WorkbenchMultiTab> | null>(null);
|
const multiTabRef = ref<InstanceType<typeof WorkbenchMultiTab> | null>(null);
|
||||||
const salesRankTabRef = ref<InstanceType<typeof WorkbenchSalesRankTab> | null>(
|
const salesRankTabRef = ref<InstanceType<typeof WorkbenchSalesRankTab> | null>(
|
||||||
null,
|
null,
|
||||||
@@ -742,6 +754,12 @@ const periodCompareTabRef = ref<
|
|||||||
| null
|
| null
|
||||||
>(null);
|
>(null);
|
||||||
|
|
||||||
|
/** 区域销量 Mock 随筛选日期变化,便于演示分布变化 */
|
||||||
|
const regionRangeKey = computed(
|
||||||
|
() =>
|
||||||
|
`${dateRange.value[0]?.format('YYYY-MM-DD')}_${dateRange.value[1]?.format('YYYY-MM-DD')}_${selectedPlatformSlug.value}_${selectedShopSlug.value}`,
|
||||||
|
);
|
||||||
|
|
||||||
async function redrawActiveTabCharts() {
|
async function redrawActiveTabCharts() {
|
||||||
await nextTick();
|
await nextTick();
|
||||||
switch (activeTab.value) {
|
switch (activeTab.value) {
|
||||||
@@ -749,6 +767,10 @@ async function redrawActiveTabCharts() {
|
|||||||
await financeTabRef.value?.redraw();
|
await financeTabRef.value?.redraw();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case 'region': {
|
||||||
|
await regionTabRef.value?.redraw();
|
||||||
|
break;
|
||||||
|
}
|
||||||
case 'multi': {
|
case 'multi': {
|
||||||
await multiTabRef.value?.redraw();
|
await multiTabRef.value?.redraw();
|
||||||
break;
|
break;
|
||||||
@@ -766,7 +788,7 @@ async function redrawActiveTabCharts() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
watch(activeTab, (tab) => {
|
watch(activeTab, (tab) => {
|
||||||
if (tab !== 'periodCompare') {
|
if (tab !== 'periodCompare' && tab !== 'region') {
|
||||||
void loadTabData(tab as DataTabKey);
|
void loadTabData(tab as DataTabKey);
|
||||||
}
|
}
|
||||||
void refreshBiHealth();
|
void refreshBiHealth();
|
||||||
@@ -840,7 +862,7 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<template #extra>
|
<template #extra>
|
||||||
<div
|
<div
|
||||||
class="workbench-header-extra flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2"
|
class="workbench-header-extra flex w-full max-w-full flex-nowrap items-center gap-2 overflow-x-auto overscroll-x-contain [-ms-overflow-style:none] [scrollbar-width:none] sm:w-auto sm:overflow-visible [&::-webkit-scrollbar]:hidden"
|
||||||
>
|
>
|
||||||
<BiDataHealthToolbarButton
|
<BiDataHealthToolbarButton
|
||||||
ref="biHealthRef"
|
ref="biHealthRef"
|
||||||
@@ -1081,6 +1103,12 @@ onUnmounted(() => {
|
|||||||
/>
|
/>
|
||||||
</Spin>
|
</Spin>
|
||||||
</Tabs.TabPane>
|
</Tabs.TabPane>
|
||||||
|
<Tabs.TabPane key="region" tab="区域销量">
|
||||||
|
<WorkbenchRegionTab
|
||||||
|
ref="regionTabRef"
|
||||||
|
:range-key="regionRangeKey"
|
||||||
|
/>
|
||||||
|
</Tabs.TabPane>
|
||||||
<Tabs.TabPane key="multi" tab="多维分析">
|
<Tabs.TabPane key="multi" tab="多维分析">
|
||||||
<Spin :spinning="multiLoading && !multiAnalysisData">
|
<Spin :spinning="multiLoading && !multiAnalysisData">
|
||||||
<WorkbenchMultiTab
|
<WorkbenchMultiTab
|
||||||
|
|||||||
+307
@@ -0,0 +1,307 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { EchartsUIType } from '@vben/plugins/echarts';
|
||||||
|
import type { RegionMetricKey, RegionSalesRow } from '../types';
|
||||||
|
|
||||||
|
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||||
|
|
||||||
|
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
|
||||||
|
|
||||||
|
import { FINANCE_PANEL_SHELL } from '../../finance/constants/finance-ui';
|
||||||
|
import {
|
||||||
|
WORLD_SALES_MAP_NAME,
|
||||||
|
ensureWorldSalesMapRegistered,
|
||||||
|
} from '../composables/use-world-geo';
|
||||||
|
import { REGION_METRIC_OPTIONS } from '../types';
|
||||||
|
|
||||||
|
defineOptions({ name: 'RegionSalesMapChart' });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
rows: RegionSalesRow[];
|
||||||
|
metric: RegionMetricKey;
|
||||||
|
selectedProvince?: string | null;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
select: [provinceName: string | null];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const chartRef = ref<EchartsUIType>();
|
||||||
|
const { renderEcharts, getChartInstance } = useEcharts(chartRef);
|
||||||
|
const mapReady = ref(false);
|
||||||
|
const mapError = ref('');
|
||||||
|
const loadingMap = ref(true);
|
||||||
|
|
||||||
|
let darkObserver: MutationObserver | null = null;
|
||||||
|
let renderSeq = 0;
|
||||||
|
|
||||||
|
const metricMeta = computed(
|
||||||
|
() =>
|
||||||
|
REGION_METRIC_OPTIONS.find((o) => o.value === props.metric) ||
|
||||||
|
REGION_METRIC_OPTIONS[0]!,
|
||||||
|
);
|
||||||
|
|
||||||
|
const provinceNameSet = computed(
|
||||||
|
() => new Set(props.rows.map((r) => r.provinceName)),
|
||||||
|
);
|
||||||
|
|
||||||
|
function metricValue(row: RegionSalesRow): number {
|
||||||
|
switch (props.metric) {
|
||||||
|
case 'salesQty': {
|
||||||
|
return row.salesQty;
|
||||||
|
}
|
||||||
|
case 'orderCount': {
|
||||||
|
return row.orderCount;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
return row.salesAmount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMetric(value: number): string {
|
||||||
|
if (props.metric === 'salesAmount') {
|
||||||
|
if (value >= 10_000) return `${(value / 10_000).toFixed(1)}万`;
|
||||||
|
return `${Math.round(value)}`;
|
||||||
|
}
|
||||||
|
if (value >= 10_000) return `${(value / 10_000).toFixed(1)}万`;
|
||||||
|
return String(Math.round(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function shortProvinceName(name: string) {
|
||||||
|
return name.replace(
|
||||||
|
/(维吾尔|壮族|回族)?自治区$|特别行政区$|省$|市$/g,
|
||||||
|
'',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isDarkTheme() {
|
||||||
|
return document.documentElement.classList.contains('dark');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindChartClick() {
|
||||||
|
const chart = getChartInstance();
|
||||||
|
if (!chart) return;
|
||||||
|
chart.off('click');
|
||||||
|
chart.on('click', (params: unknown) => {
|
||||||
|
const p = params as { name?: string; componentType?: string };
|
||||||
|
if (p.componentType !== 'series') return;
|
||||||
|
const name = p.name || '';
|
||||||
|
// 仅中国省级可点选;其他国家忽略
|
||||||
|
if (!provinceNameSet.value.has(name)) return;
|
||||||
|
emit('select', name === props.selectedProvince ? null : name);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderMap() {
|
||||||
|
if (!mapReady.value) return;
|
||||||
|
const seq = ++renderSeq;
|
||||||
|
const dark = isDarkTheme();
|
||||||
|
const values = props.rows.map((r) => metricValue(r));
|
||||||
|
const max = Math.max(...values, 1);
|
||||||
|
const ranked = [...props.rows].sort(
|
||||||
|
(a, b) => metricValue(b) - metricValue(a),
|
||||||
|
);
|
||||||
|
const topNames = new Set(ranked.slice(0, 8).map((r) => r.provinceName));
|
||||||
|
|
||||||
|
const data = props.rows.map((r) => {
|
||||||
|
const value = metricValue(r);
|
||||||
|
const selected = props.selectedProvince === r.provinceName;
|
||||||
|
const isTop = topNames.has(r.provinceName);
|
||||||
|
return {
|
||||||
|
name: r.provinceName,
|
||||||
|
value,
|
||||||
|
label: {
|
||||||
|
show: selected || isTop,
|
||||||
|
formatter: () => shortProvinceName(r.provinceName),
|
||||||
|
},
|
||||||
|
itemStyle: selected
|
||||||
|
? {
|
||||||
|
areaColor: dark ? '#fbbf24' : '#f97316',
|
||||||
|
borderColor: '#fff',
|
||||||
|
borderWidth: 1.5,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
await renderEcharts({
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
title: {
|
||||||
|
text: metricMeta.value.label,
|
||||||
|
subtext: '2D 世界地图 · 滚轮缩放 · 拖拽平移 · 点击省份查看明细',
|
||||||
|
left: 16,
|
||||||
|
top: 10,
|
||||||
|
textStyle: {
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 600,
|
||||||
|
color: dark ? '#e2e8f0' : '#0f172a',
|
||||||
|
},
|
||||||
|
subtextStyle: {
|
||||||
|
fontSize: 11,
|
||||||
|
color: dark ? '#64748b' : '#94a3b8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'item',
|
||||||
|
borderWidth: 0,
|
||||||
|
backgroundColor: dark ? 'rgba(15,23,42,0.92)' : 'rgba(255,255,255,0.96)',
|
||||||
|
textStyle: { color: dark ? '#e2e8f0' : '#0f172a' },
|
||||||
|
formatter: (params: unknown) => {
|
||||||
|
const p = params as {
|
||||||
|
name?: string;
|
||||||
|
value?: number | string;
|
||||||
|
data?: { value?: number };
|
||||||
|
};
|
||||||
|
const name = p.name || '';
|
||||||
|
if (!provinceNameSet.value.has(name)) {
|
||||||
|
return name ? `${name}<br/>暂无区域销量数据` : '';
|
||||||
|
}
|
||||||
|
const raw =
|
||||||
|
typeof p.value === 'number'
|
||||||
|
? p.value
|
||||||
|
: Number(p.data?.value ?? Number.NaN);
|
||||||
|
if (!Number.isFinite(raw)) {
|
||||||
|
return `${name}<br/>暂无数据`;
|
||||||
|
}
|
||||||
|
return `${name}<br/>${metricMeta.value.label}:<b>${formatMetric(raw)}</b> ${metricMeta.value.unit}`;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
visualMap: {
|
||||||
|
type: 'continuous',
|
||||||
|
min: 0,
|
||||||
|
max,
|
||||||
|
right: 18,
|
||||||
|
bottom: 24,
|
||||||
|
orient: 'vertical',
|
||||||
|
align: 'left',
|
||||||
|
text: ['高', '低'],
|
||||||
|
calculable: true,
|
||||||
|
realtime: false,
|
||||||
|
itemWidth: 12,
|
||||||
|
itemHeight: 120,
|
||||||
|
inRange: {
|
||||||
|
color: dark
|
||||||
|
? ['#172554', '#1d4ed8', '#38bdf8', '#a5f3fc']
|
||||||
|
: ['#eff6ff', '#93c5fd', '#2563eb', '#1e3a8a'],
|
||||||
|
},
|
||||||
|
textStyle: {
|
||||||
|
color: dark ? '#94a3b8' : '#64748b',
|
||||||
|
fontSize: 11,
|
||||||
|
},
|
||||||
|
backgroundColor: dark ? 'rgba(15,23,42,0.55)' : 'rgba(255,255,255,0.72)',
|
||||||
|
padding: [8, 10],
|
||||||
|
borderRadius: 8,
|
||||||
|
formatter: (v: number) => formatMetric(v),
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: metricMeta.value.label,
|
||||||
|
type: 'map',
|
||||||
|
map: WORLD_SALES_MAP_NAME,
|
||||||
|
// 放大并以中国为视觉中心
|
||||||
|
center: [105, 36],
|
||||||
|
zoom: 4.9,
|
||||||
|
roam: true,
|
||||||
|
scaleLimit: { min: 2.5, max: 24 },
|
||||||
|
selectedMode: false,
|
||||||
|
data,
|
||||||
|
nameProperty: 'name',
|
||||||
|
emphasis: {
|
||||||
|
label: {
|
||||||
|
show: true,
|
||||||
|
color: dark ? '#f8fafc' : '#0f172a',
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
itemStyle: {
|
||||||
|
areaColor: dark ? '#38bdf8' : '#60a5fa',
|
||||||
|
borderWidth: 1.2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
itemStyle: {
|
||||||
|
borderColor: dark ? 'rgba(15,23,42,0.75)' : '#fff',
|
||||||
|
borderWidth: 0.6,
|
||||||
|
areaColor: dark ? '#1e293b' : '#e2e8f0',
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
show: false,
|
||||||
|
color: dark ? '#e2e8f0' : '#1e293b',
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: 500,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
if (seq !== renderSeq) return;
|
||||||
|
await nextTick();
|
||||||
|
bindChartClick();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
loadingMap.value = true;
|
||||||
|
mapError.value = '';
|
||||||
|
try {
|
||||||
|
await ensureWorldSalesMapRegistered();
|
||||||
|
mapReady.value = true;
|
||||||
|
await renderMap();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
mapError.value = e instanceof Error ? e.message : '地图加载失败';
|
||||||
|
} finally {
|
||||||
|
loadingMap.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function redraw() {
|
||||||
|
await renderMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.rows, props.metric, props.selectedProvince] as const,
|
||||||
|
() => {
|
||||||
|
void renderMap();
|
||||||
|
},
|
||||||
|
{ deep: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
void bootstrap();
|
||||||
|
darkObserver = new MutationObserver(() => {
|
||||||
|
void renderMap();
|
||||||
|
});
|
||||||
|
darkObserver.observe(document.documentElement, {
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ['class'],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
darkObserver?.disconnect();
|
||||||
|
darkObserver = null;
|
||||||
|
renderSeq += 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
defineExpose({ redraw });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
:class="[FINANCE_PANEL_SHELL, 'relative min-h-[420px] overflow-hidden p-0']"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="loadingMap"
|
||||||
|
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center text-sm"
|
||||||
|
>
|
||||||
|
正在加载世界地图…
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="mapError"
|
||||||
|
class="absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 px-6 text-center"
|
||||||
|
>
|
||||||
|
<p class="text-sm text-rose-500">{{ mapError }}</p>
|
||||||
|
<p class="text-muted-foreground text-xs">
|
||||||
|
地图数据默认走本地 /geo;若仍失败请检查静态资源是否已部署
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<EchartsUI ref="chartRef" class="h-[420px] w-full" height="420px" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { RegionMetricKey, RegionSalesRow } from '../types';
|
||||||
|
|
||||||
|
import { computed } from 'vue';
|
||||||
|
|
||||||
|
import { FINANCE_PANEL_SHELL } from '../../finance/constants/finance-ui';
|
||||||
|
import { REGION_METRIC_OPTIONS } from '../types';
|
||||||
|
|
||||||
|
defineOptions({ name: 'RegionSalesRankList' });
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
rows: RegionSalesRow[];
|
||||||
|
metric: RegionMetricKey;
|
||||||
|
selectedProvince?: string | null;
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
select: [provinceName: string | null];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
const metricMeta = computed(
|
||||||
|
() =>
|
||||||
|
REGION_METRIC_OPTIONS.find((o) => o.value === props.metric) ||
|
||||||
|
REGION_METRIC_OPTIONS[0]!,
|
||||||
|
);
|
||||||
|
|
||||||
|
function metricValue(row: RegionSalesRow): number {
|
||||||
|
switch (props.metric) {
|
||||||
|
case 'salesQty': {
|
||||||
|
return row.salesQty;
|
||||||
|
}
|
||||||
|
case 'orderCount': {
|
||||||
|
return row.orderCount;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
return row.salesAmount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMetric(value: number): string {
|
||||||
|
if (props.metric === 'salesAmount') {
|
||||||
|
if (value >= 10_000) return `${(value / 10_000).toFixed(2)}万`;
|
||||||
|
return value.toLocaleString('zh-CN', { maximumFractionDigits: 0 });
|
||||||
|
}
|
||||||
|
return value.toLocaleString('zh-CN');
|
||||||
|
}
|
||||||
|
|
||||||
|
const ranked = computed(() => {
|
||||||
|
const total = props.rows.reduce((s, r) => s + metricValue(r), 0) || 1;
|
||||||
|
return [...props.rows]
|
||||||
|
.sort((a, b) => metricValue(b) - metricValue(a))
|
||||||
|
.map((row, index) => ({
|
||||||
|
...row,
|
||||||
|
rank: index + 1,
|
||||||
|
value: metricValue(row),
|
||||||
|
share: (metricValue(row) / total) * 100,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
const maxValue = computed(() => Math.max(...ranked.value.map((r) => r.value), 1));
|
||||||
|
|
||||||
|
function onRowClick(name: string) {
|
||||||
|
emit('select', name === props.selectedProvince ? null : name);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div :class="[FINANCE_PANEL_SHELL, 'flex h-[420px] flex-col overflow-hidden']">
|
||||||
|
<div
|
||||||
|
class="flex shrink-0 items-center justify-between border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
|
||||||
|
>
|
||||||
|
<div class="text-sm font-semibold text-slate-800 dark:text-slate-100">
|
||||||
|
省份排行
|
||||||
|
</div>
|
||||||
|
<div class="text-xs text-slate-500">
|
||||||
|
按{{ metricMeta.label }} · 共 {{ ranked.length }} 省
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-y-auto px-2 py-2">
|
||||||
|
<button
|
||||||
|
v-for="row in ranked"
|
||||||
|
:key="row.provinceCode"
|
||||||
|
type="button"
|
||||||
|
class="flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-2 text-left transition-colors"
|
||||||
|
:class="
|
||||||
|
selectedProvince === row.provinceName
|
||||||
|
? 'bg-indigo-50 dark:bg-indigo-950/40'
|
||||||
|
: 'hover:bg-slate-50 dark:hover:bg-white/5'
|
||||||
|
"
|
||||||
|
@click="onRowClick(row.provinceName)"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="w-6 shrink-0 text-center text-xs font-bold tabular-nums"
|
||||||
|
:class="
|
||||||
|
row.rank <= 3
|
||||||
|
? 'text-amber-500'
|
||||||
|
: 'text-slate-400 dark:text-slate-500'
|
||||||
|
"
|
||||||
|
>
|
||||||
|
{{ row.rank }}
|
||||||
|
</span>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<div class="flex items-baseline justify-between gap-2">
|
||||||
|
<span
|
||||||
|
class="truncate text-sm font-medium text-slate-800 dark:text-slate-100"
|
||||||
|
>
|
||||||
|
{{ row.provinceName.replace(/(省|市|自治区|壮族|回族|维吾尔)/g, '') }}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="shrink-0 text-xs font-semibold tabular-nums text-slate-700 dark:text-slate-200"
|
||||||
|
>
|
||||||
|
{{ formatMetric(row.value) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="mt-1.5 h-1.5 overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="h-full rounded-full bg-gradient-to-r from-blue-400 to-indigo-500"
|
||||||
|
:style="{ width: `${(row.value / maxValue) * 100}%` }"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 text-[11px] tabular-nums text-slate-400">
|
||||||
|
占比 {{ row.share.toFixed(1) }}% · 退款
|
||||||
|
{{
|
||||||
|
row.refundAmount >= 10_000
|
||||||
|
? `${(row.refundAmount / 10_000).toFixed(1)}万`
|
||||||
|
: row.refundAmount.toLocaleString('zh-CN')
|
||||||
|
}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
+83
@@ -0,0 +1,83 @@
|
|||||||
|
import { echarts } from '@vben/plugins/echarts';
|
||||||
|
|
||||||
|
const CHINA_MAP_NAME = 'china-mainland';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 省级边界:优先本地静态资源(已裁南海附图),
|
||||||
|
* DataV 仅作兜底。
|
||||||
|
*/
|
||||||
|
const CHINA_GEO_URLS = [
|
||||||
|
'/geo/china-100000-full.json',
|
||||||
|
'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
|
||||||
|
];
|
||||||
|
|
||||||
|
export type ChinaGeoJson = {
|
||||||
|
type?: string;
|
||||||
|
features?: Array<{
|
||||||
|
type?: string;
|
||||||
|
properties?: { name?: string; adcode?: string | number };
|
||||||
|
geometry?: {
|
||||||
|
type?: string;
|
||||||
|
coordinates?: unknown;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
let loadPromise: Promise<ChinaGeoJson> | null = null;
|
||||||
|
let cachedGeoJson: ChinaGeoJson | null = null;
|
||||||
|
|
||||||
|
/** 去掉南海诸岛附图,避免包围盒过大导致主图四周大片留白 */
|
||||||
|
function trimSouthSeaInset(geoJson: ChinaGeoJson): ChinaGeoJson {
|
||||||
|
const features = (geoJson.features || []).filter((f) => {
|
||||||
|
const name = f.properties?.name || '';
|
||||||
|
const adcode = String(f.properties?.adcode ?? '');
|
||||||
|
if (name.includes('南海')) return false;
|
||||||
|
if (adcode.includes('_JD')) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return { ...geoJson, features };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 拉取省级中国 geoJSON(同名只注册一次),并返回裁剪后的数据供矢量地球使用。 */
|
||||||
|
export function ensureChinaMapRegistered(): Promise<ChinaGeoJson> {
|
||||||
|
if (cachedGeoJson) {
|
||||||
|
if (!echarts.getMap(CHINA_MAP_NAME)) {
|
||||||
|
echarts.registerMap(CHINA_MAP_NAME, cachedGeoJson as never);
|
||||||
|
}
|
||||||
|
return Promise.resolve(cachedGeoJson);
|
||||||
|
}
|
||||||
|
if (loadPromise) return loadPromise;
|
||||||
|
|
||||||
|
loadPromise = (async () => {
|
||||||
|
let lastError: unknown;
|
||||||
|
for (const url of CHINA_GEO_URLS) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
lastError = new Error(`加载地图失败(${res.status})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const geoJson = trimSouthSeaInset(await res.json());
|
||||||
|
cachedGeoJson = geoJson;
|
||||||
|
echarts.registerMap(CHINA_MAP_NAME, geoJson as never);
|
||||||
|
return geoJson;
|
||||||
|
} catch (e) {
|
||||||
|
lastError = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastError instanceof Error
|
||||||
|
? lastError
|
||||||
|
: new Error('加载地图失败');
|
||||||
|
})().catch((err) => {
|
||||||
|
loadPromise = null;
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
|
||||||
|
return loadPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getChinaGeoJson(): ChinaGeoJson | null {
|
||||||
|
return cachedGeoJson;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { CHINA_MAP_NAME };
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
import { echarts } from '@vben/plugins/echarts';
|
||||||
|
|
||||||
|
import type { ChinaGeoJson } from './use-china-map';
|
||||||
|
import { ensureChinaMapRegistered } from './use-china-map';
|
||||||
|
|
||||||
|
/** 世界 + 中国省级合并后的地图名(供 2D map 系列使用) */
|
||||||
|
export const WORLD_SALES_MAP_NAME = 'world-with-china-provinces';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 世界国家边界:优先本地静态资源(public/geo/world.json),
|
||||||
|
* 避免境外 CDN 在国内不可用;远程仅作兜底。
|
||||||
|
*/
|
||||||
|
const WORLD_GEO_URLS = [
|
||||||
|
'/geo/world.json',
|
||||||
|
'https://cdn.jsdelivr.net/npm/echarts@4.9.0/map/json/world.json',
|
||||||
|
];
|
||||||
|
|
||||||
|
const CHINA_COUNTRY_NAMES = new Set([
|
||||||
|
'China',
|
||||||
|
'中国',
|
||||||
|
'中华人民共和国',
|
||||||
|
]);
|
||||||
|
|
||||||
|
let worldLoadPromise: Promise<ChinaGeoJson> | null = null;
|
||||||
|
let cachedWorld: ChinaGeoJson | null = null;
|
||||||
|
let mergePromise: Promise<ChinaGeoJson> | null = null;
|
||||||
|
let cachedMerged: ChinaGeoJson | null = null;
|
||||||
|
|
||||||
|
/** 拉取世界国家 geoJSON(缓存一次)。 */
|
||||||
|
export function ensureWorldGeoJson(): Promise<ChinaGeoJson> {
|
||||||
|
if (cachedWorld) return Promise.resolve(cachedWorld);
|
||||||
|
if (worldLoadPromise) return worldLoadPromise;
|
||||||
|
|
||||||
|
worldLoadPromise = (async () => {
|
||||||
|
let lastError: unknown;
|
||||||
|
for (const url of WORLD_GEO_URLS) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
lastError = new Error(`加载世界地图失败(${res.status})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cachedWorld = (await res.json()) as ChinaGeoJson;
|
||||||
|
return cachedWorld;
|
||||||
|
} catch (e) {
|
||||||
|
lastError = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastError instanceof Error
|
||||||
|
? lastError
|
||||||
|
: new Error('加载世界地图失败');
|
||||||
|
})().catch((err) => {
|
||||||
|
worldLoadPromise = null;
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
|
||||||
|
return worldLoadPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用中国省级边界替换世界图中的 China 国界,得到可色阶到省的世界地图。
|
||||||
|
*/
|
||||||
|
export function mergeWorldWithChinaProvinces(
|
||||||
|
world: ChinaGeoJson,
|
||||||
|
china: ChinaGeoJson,
|
||||||
|
): ChinaGeoJson {
|
||||||
|
const worldFeatures = (world.features || []).filter((f) => {
|
||||||
|
const name = f.properties?.name || '';
|
||||||
|
return !CHINA_COUNTRY_NAMES.has(name);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
type: 'FeatureCollection',
|
||||||
|
features: [...worldFeatures, ...(china.features || [])],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 注册「世界 + 中国省」合并地图,返回合并后的 geoJSON。 */
|
||||||
|
export async function ensureWorldSalesMapRegistered(): Promise<ChinaGeoJson> {
|
||||||
|
if (cachedMerged) {
|
||||||
|
if (!echarts.getMap(WORLD_SALES_MAP_NAME)) {
|
||||||
|
echarts.registerMap(WORLD_SALES_MAP_NAME, cachedMerged as never);
|
||||||
|
}
|
||||||
|
return cachedMerged;
|
||||||
|
}
|
||||||
|
if (mergePromise) return mergePromise;
|
||||||
|
|
||||||
|
mergePromise = (async () => {
|
||||||
|
const [world, china] = await Promise.all([
|
||||||
|
ensureWorldGeoJson(),
|
||||||
|
ensureChinaMapRegistered(),
|
||||||
|
]);
|
||||||
|
const merged = mergeWorldWithChinaProvinces(world, china);
|
||||||
|
cachedMerged = merged;
|
||||||
|
echarts.registerMap(WORLD_SALES_MAP_NAME, merged as never);
|
||||||
|
return merged;
|
||||||
|
})().catch((err) => {
|
||||||
|
mergePromise = null;
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
|
||||||
|
return mergePromise;
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { RegionMetricKey, RegionSalesPanel, RegionSalesRow } from './types';
|
||||||
|
|
||||||
|
import { computed, nextTick, ref, watch } from 'vue';
|
||||||
|
|
||||||
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
import { Segmented } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { FINANCE_KPI_CARD_SHELL } from '../finance/constants/finance-ui';
|
||||||
|
import RegionSalesMapChart from './components/RegionSalesMapChart.vue';
|
||||||
|
import RegionSalesRankList from './components/RegionSalesRankList.vue';
|
||||||
|
import { buildMockRegionSalesPanel } from './mock-data';
|
||||||
|
import { REGION_METRIC_OPTIONS } from './types';
|
||||||
|
|
||||||
|
defineOptions({ name: 'WorkbenchRegionTab' });
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
/** 与工作台筛选同步的区间种子,便于演示时随筛选轻微变化 */
|
||||||
|
rangeKey?: string;
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
rangeKey: 'default',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const MapPinIcon = createIconifyIcon('lucide:map-pinned');
|
||||||
|
const CoinsIcon = createIconifyIcon('lucide:coins');
|
||||||
|
const PackageIcon = createIconifyIcon('lucide:package');
|
||||||
|
const PercentIcon = createIconifyIcon('lucide:percent');
|
||||||
|
|
||||||
|
const metric = ref<RegionMetricKey>('salesAmount');
|
||||||
|
const selectedProvince = ref<string | null>(null);
|
||||||
|
const mapRef = ref<InstanceType<typeof RegionSalesMapChart> | null>(null);
|
||||||
|
|
||||||
|
const panel = computed<RegionSalesPanel>(() =>
|
||||||
|
buildMockRegionSalesPanel(props.rangeKey),
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows = computed(() => panel.value.rows);
|
||||||
|
|
||||||
|
function metricValue(row: RegionSalesRow): number {
|
||||||
|
switch (metric.value) {
|
||||||
|
case 'salesQty': {
|
||||||
|
return row.salesQty;
|
||||||
|
}
|
||||||
|
case 'orderCount': {
|
||||||
|
return row.orderCount;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
return row.salesAmount;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const kpis = computed(() => {
|
||||||
|
const list = rows.value;
|
||||||
|
const totalAmount = list.reduce((s, r) => s + r.salesAmount, 0);
|
||||||
|
const totalQty = list.reduce((s, r) => s + r.salesQty, 0);
|
||||||
|
const covered = list.filter((r) => metricValue(r) > 0).length;
|
||||||
|
const ranked = [...list].sort((a, b) => metricValue(b) - metricValue(a));
|
||||||
|
const top = ranked[0];
|
||||||
|
const topShare =
|
||||||
|
top && list.length
|
||||||
|
? (metricValue(top) /
|
||||||
|
Math.max(
|
||||||
|
1,
|
||||||
|
list.reduce((s, r) => s + metricValue(r), 0),
|
||||||
|
)) *
|
||||||
|
100
|
||||||
|
: 0;
|
||||||
|
return {
|
||||||
|
totalAmount,
|
||||||
|
totalQty,
|
||||||
|
covered,
|
||||||
|
topName: top?.provinceName?.replace(/(省|市|自治区|壮族|回族|维吾尔)/g, '') || '—',
|
||||||
|
topShare,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectedRow = computed(() =>
|
||||||
|
selectedProvince.value
|
||||||
|
? rows.value.find((r) => r.provinceName === selectedProvince.value) || null
|
||||||
|
: null,
|
||||||
|
);
|
||||||
|
|
||||||
|
function formatWan(yuan: number) {
|
||||||
|
if (yuan >= 10_000) return `${(yuan / 10_000).toFixed(2)}万`;
|
||||||
|
return yuan.toLocaleString('zh-CN', { maximumFractionDigits: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSelectProvince(name: string | null) {
|
||||||
|
selectedProvince.value = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMetricChange(v: string | number) {
|
||||||
|
metric.value = String(v) as RegionMetricKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function redraw() {
|
||||||
|
await nextTick();
|
||||||
|
await mapRef.value?.redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.rangeKey,
|
||||||
|
() => {
|
||||||
|
selectedProvince.value = null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
defineExpose({ redraw });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="mt-4 space-y-3">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<Segmented
|
||||||
|
:value="metric"
|
||||||
|
:options="REGION_METRIC_OPTIONS.map((o) => ({ label: o.label, value: o.value }))"
|
||||||
|
@change="onMetricChange"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||||
|
<div :class="[FINANCE_KPI_CARD_SHELL]">
|
||||||
|
<div class="flex items-start justify-between gap-2">
|
||||||
|
<span class="text-xs font-medium text-slate-500">全国净销售额</span>
|
||||||
|
<span
|
||||||
|
class="flex size-8 items-center justify-center rounded-lg bg-blue-50 text-blue-500 dark:bg-blue-950/40 dark:text-blue-300"
|
||||||
|
>
|
||||||
|
<CoinsIcon class="size-4" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="mt-3 text-[22px] font-bold tabular-nums tracking-tight text-slate-800 dark:text-slate-100"
|
||||||
|
>
|
||||||
|
¥{{ formatWan(kpis.totalAmount) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div :class="[FINANCE_KPI_CARD_SHELL]">
|
||||||
|
<div class="flex items-start justify-between gap-2">
|
||||||
|
<span class="text-xs font-medium text-slate-500">全国净销量</span>
|
||||||
|
<span
|
||||||
|
class="flex size-8 items-center justify-center rounded-lg bg-emerald-50 text-emerald-500 dark:bg-emerald-950/40 dark:text-emerald-300"
|
||||||
|
>
|
||||||
|
<PackageIcon class="size-4" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="mt-3 text-[22px] font-bold tabular-nums tracking-tight text-slate-800 dark:text-slate-100"
|
||||||
|
>
|
||||||
|
{{ kpis.totalQty.toLocaleString('zh-CN') }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div :class="[FINANCE_KPI_CARD_SHELL]">
|
||||||
|
<div class="flex items-start justify-between gap-2">
|
||||||
|
<span class="text-xs font-medium text-slate-500">覆盖省份</span>
|
||||||
|
<span
|
||||||
|
class="flex size-8 items-center justify-center rounded-lg bg-violet-50 text-violet-500 dark:bg-violet-950/40 dark:text-violet-300"
|
||||||
|
>
|
||||||
|
<MapPinIcon class="size-4" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="mt-3 text-[22px] font-bold tabular-nums tracking-tight text-slate-800 dark:text-slate-100"
|
||||||
|
>
|
||||||
|
{{ kpis.covered }}
|
||||||
|
<span class="text-sm font-normal text-slate-400">/ {{ rows.length }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div :class="[FINANCE_KPI_CARD_SHELL]">
|
||||||
|
<div class="flex items-start justify-between gap-2">
|
||||||
|
<span class="text-xs font-medium text-slate-500">TOP1 占比</span>
|
||||||
|
<span
|
||||||
|
class="flex size-8 items-center justify-center rounded-lg bg-amber-50 text-amber-500 dark:bg-amber-950/40 dark:text-amber-300"
|
||||||
|
>
|
||||||
|
<PercentIcon class="size-4" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="mt-3 text-[22px] font-bold tabular-nums tracking-tight text-slate-800 dark:text-slate-100"
|
||||||
|
>
|
||||||
|
{{ kpis.topShare.toFixed(1) }}%
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 truncate text-xs text-slate-500">{{ kpis.topName }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="selectedRow"
|
||||||
|
class="flex flex-wrap items-center gap-x-4 gap-y-1 rounded-xl border border-indigo-200/80 bg-indigo-50/60 px-4 py-2.5 text-sm dark:border-indigo-500/30 dark:bg-indigo-950/30"
|
||||||
|
>
|
||||||
|
<span class="font-semibold text-indigo-700 dark:text-indigo-200">
|
||||||
|
{{ selectedRow.provinceName }}
|
||||||
|
</span>
|
||||||
|
<span class="tabular-nums text-slate-700 dark:text-slate-200">
|
||||||
|
净销售额 ¥{{ formatWan(selectedRow.salesAmount) }}
|
||||||
|
</span>
|
||||||
|
<span class="tabular-nums text-slate-600 dark:text-slate-300">
|
||||||
|
净销量 {{ selectedRow.salesQty.toLocaleString('zh-CN') }}
|
||||||
|
</span>
|
||||||
|
<span class="tabular-nums text-slate-600 dark:text-slate-300">
|
||||||
|
单量 {{ selectedRow.orderCount.toLocaleString('zh-CN') }}
|
||||||
|
</span>
|
||||||
|
<span class="tabular-nums text-slate-500">
|
||||||
|
退款 ¥{{ formatWan(selectedRow.refundAmount) }}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="ml-auto text-xs text-indigo-600 hover:underline dark:text-indigo-300"
|
||||||
|
@click="selectedProvince = null"
|
||||||
|
>
|
||||||
|
清除选中
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-1 gap-3 xl:grid-cols-5">
|
||||||
|
<div class="xl:col-span-3">
|
||||||
|
<RegionSalesMapChart
|
||||||
|
ref="mapRef"
|
||||||
|
:rows="rows"
|
||||||
|
:metric="metric"
|
||||||
|
:selected-province="selectedProvince"
|
||||||
|
@select="onSelectProvince"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="xl:col-span-2">
|
||||||
|
<RegionSalesRankList
|
||||||
|
:rows="rows"
|
||||||
|
:metric="metric"
|
||||||
|
:selected-province="selectedProvince"
|
||||||
|
@select="onSelectProvince"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import type { RegionSalesPanel, RegionSalesRow } from './types';
|
||||||
|
|
||||||
|
/** 与 DataV 省级 geoJSON 名称对齐的省份清单(演示用) */
|
||||||
|
const PROVINCES: Array<{ code: string; name: string; weight: number }> = [
|
||||||
|
{ code: '110000', name: '北京市', weight: 1.15 },
|
||||||
|
{ code: '120000', name: '天津市', weight: 0.55 },
|
||||||
|
{ code: '130000', name: '河北省', weight: 0.85 },
|
||||||
|
{ code: '140000', name: '山西省', weight: 0.45 },
|
||||||
|
{ code: '150000', name: '内蒙古自治区', weight: 0.35 },
|
||||||
|
{ code: '210000', name: '辽宁省', weight: 0.7 },
|
||||||
|
{ code: '220000', name: '吉林省', weight: 0.4 },
|
||||||
|
{ code: '230000', name: '黑龙江省', weight: 0.42 },
|
||||||
|
{ code: '310000', name: '上海市', weight: 1.25 },
|
||||||
|
{ code: '320000', name: '江苏省', weight: 1.35 },
|
||||||
|
{ code: '330000', name: '浙江省', weight: 1.4 },
|
||||||
|
{ code: '340000', name: '安徽省', weight: 0.75 },
|
||||||
|
{ code: '350000', name: '福建省', weight: 0.8 },
|
||||||
|
{ code: '360000', name: '江西省', weight: 0.55 },
|
||||||
|
{ code: '370000', name: '山东省', weight: 1.2 },
|
||||||
|
{ code: '410000', name: '河南省', weight: 0.95 },
|
||||||
|
{ code: '420000', name: '湖北省', weight: 0.85 },
|
||||||
|
{ code: '430000', name: '湖南省', weight: 0.8 },
|
||||||
|
{ code: '440000', name: '广东省', weight: 1.55 },
|
||||||
|
{ code: '450000', name: '广西壮族自治区', weight: 0.5 },
|
||||||
|
{ code: '460000', name: '海南省', weight: 0.28 },
|
||||||
|
{ code: '500000', name: '重庆市', weight: 0.7 },
|
||||||
|
{ code: '510000', name: '四川省', weight: 0.95 },
|
||||||
|
{ code: '520000', name: '贵州省', weight: 0.4 },
|
||||||
|
{ code: '530000', name: '云南省', weight: 0.48 },
|
||||||
|
{ code: '540000', name: '西藏自治区', weight: 0.08 },
|
||||||
|
{ code: '610000', name: '陕西省', weight: 0.65 },
|
||||||
|
{ code: '620000', name: '甘肃省', weight: 0.28 },
|
||||||
|
{ code: '630000', name: '青海省', weight: 0.12 },
|
||||||
|
{ code: '640000', name: '宁夏回族自治区', weight: 0.15 },
|
||||||
|
{ code: '650000', name: '新疆维吾尔自治区', weight: 0.32 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function hashSeed(input: string): number {
|
||||||
|
let h = 2166136261;
|
||||||
|
for (let i = 0; i < input.length; i += 1) {
|
||||||
|
h ^= input.charCodeAt(i);
|
||||||
|
h = Math.imul(h, 16777619);
|
||||||
|
}
|
||||||
|
return h >>> 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mulberry32(seed: number) {
|
||||||
|
let t = seed;
|
||||||
|
return () => {
|
||||||
|
t += 0x6d2b79f5;
|
||||||
|
let r = Math.imul(t ^ (t >>> 15), 1 | t);
|
||||||
|
r ^= r + Math.imul(r ^ (r >>> 7), 61 | r);
|
||||||
|
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成演示用省级净销售分布(稳定可复现)。
|
||||||
|
* @param rangeKey 可用日期区间字符串作种子,切换筛选时分布略变
|
||||||
|
*/
|
||||||
|
export function buildMockRegionSalesPanel(rangeKey = 'default'): RegionSalesPanel {
|
||||||
|
const rand = mulberry32(hashSeed(`region-sales:${rangeKey}`));
|
||||||
|
const rows: RegionSalesRow[] = PROVINCES.map((p) => {
|
||||||
|
const jitter = 0.65 + rand() * 0.7;
|
||||||
|
const base = 180_000 * p.weight * jitter;
|
||||||
|
const salesAmount = Math.round(base);
|
||||||
|
const avgPrice = 68 + rand() * 90;
|
||||||
|
const salesQty = Math.max(1, Math.round(salesAmount / avgPrice));
|
||||||
|
const orderCount = Math.max(1, Math.round(salesQty / (1.4 + rand() * 1.2)));
|
||||||
|
const refundAmount = Math.round(salesAmount * (0.04 + rand() * 0.1));
|
||||||
|
return {
|
||||||
|
provinceName: p.name,
|
||||||
|
provinceCode: p.code,
|
||||||
|
salesAmount,
|
||||||
|
salesQty,
|
||||||
|
orderCount,
|
||||||
|
refundAmount,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
rows,
|
||||||
|
mock: true,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/** 区域销量 Tab:省份地理维(口径草案,后端就绪后对齐) */
|
||||||
|
|
||||||
|
/** 地图着色主指标 */
|
||||||
|
export type RegionMetricKey = 'salesAmount' | 'salesQty' | 'orderCount';
|
||||||
|
|
||||||
|
export const REGION_METRIC_OPTIONS: Array<{
|
||||||
|
label: string;
|
||||||
|
value: RegionMetricKey;
|
||||||
|
unit: string;
|
||||||
|
}> = [
|
||||||
|
{ label: '净销售额', value: 'salesAmount', unit: '元' },
|
||||||
|
{ label: '净销量', value: 'salesQty', unit: '件' },
|
||||||
|
{ label: '净销售单量', value: 'orderCount', unit: '单' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单省汇总。
|
||||||
|
* 口径建议:收货地址省份;净销售=成交−退款(与经营概览「净销售额/净销量」同口径)。
|
||||||
|
*/
|
||||||
|
export interface RegionSalesRow {
|
||||||
|
/** 与地图 geoJSON properties.name 对齐,如「广东省」 */
|
||||||
|
provinceName: string;
|
||||||
|
provinceCode: string;
|
||||||
|
/** 净销售额(元) */
|
||||||
|
salesAmount: number;
|
||||||
|
/** 净销量(件) */
|
||||||
|
salesQty: number;
|
||||||
|
/** 净销售单量 */
|
||||||
|
orderCount: number;
|
||||||
|
/** 退款额(元),辅助展示 */
|
||||||
|
refundAmount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegionSalesPanel {
|
||||||
|
rows: RegionSalesRow[];
|
||||||
|
/** 演示数据标记 */
|
||||||
|
mock: boolean;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
+310
-127
@@ -1,16 +1,13 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
/**
|
/**
|
||||||
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
* 拼多多发布页右侧智能体栏:一草稿一会话,执行 client_tool 改表单。
|
||||||
|
* UI 对齐通用智能助手(气泡、加载、底栏输入与模型选择)。
|
||||||
*/
|
*/
|
||||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||||
|
|
||||||
import {
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
MenuFoldOutlined,
|
import { Empty, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
||||||
MenuUnfoldOutlined,
|
import { ChatItem, ChatLoading } from '@tdesign-vue-next/chat';
|
||||||
SendOutlined,
|
|
||||||
} from '@ant-design/icons-vue';
|
|
||||||
import { Button, Empty, Input, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
|
||||||
import { ChatItem } from '@tdesign-vue-next/chat';
|
|
||||||
import 'tdesign-vue-next/es/style/index.css';
|
import 'tdesign-vue-next/es/style/index.css';
|
||||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||||
|
|
||||||
@@ -22,13 +19,25 @@ import {
|
|||||||
streamAgentChat,
|
streamAgentChat,
|
||||||
type AgentVO,
|
type AgentVO,
|
||||||
} from '#/api/agent';
|
} from '#/api/agent';
|
||||||
|
import CatalogCiteSender from '#/views/agent/chat/catalog-cite-sender.vue';
|
||||||
|
import CatalogCiteRichText from '#/views/agent/chat/catalog-cite-rich-text.vue';
|
||||||
|
import {
|
||||||
|
composeMessageWithCites,
|
||||||
|
stripTrailingMention,
|
||||||
|
type CatalogCite,
|
||||||
|
} from '#/views/agent/chat/catalog-cite';
|
||||||
|
|
||||||
import type { PublishEditorAgentApi } from './commands';
|
import type { PublishEditorAgentApi } from './commands';
|
||||||
|
|
||||||
defineOptions({ name: 'PddPublishAgentPanel' });
|
defineOptions({ name: 'PddPublishAgentPanel' });
|
||||||
|
|
||||||
|
const AgentBrandIcon = createIconifyIcon('lucide:bot');
|
||||||
|
const PanelCloseIcon = createIconifyIcon('lucide:panel-right-close');
|
||||||
|
const PanelOpenIcon = createIconifyIcon('lucide:panel-right');
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
draftId: number;
|
/** 系统草稿 ID;null 表示尚未落库的新建编辑 */
|
||||||
|
draftId: number | null;
|
||||||
collapsed?: boolean;
|
collapsed?: boolean;
|
||||||
/** 编辑器命令面(ref) */
|
/** 编辑器命令面(ref) */
|
||||||
editorApi: PublishEditorAgentApi | null;
|
editorApi: PublishEditorAgentApi | null;
|
||||||
@@ -41,10 +50,38 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const SCENE = 'ecom_goods_publish' as const;
|
const SCENE = 'ecom_goods_publish' as const;
|
||||||
|
|
||||||
|
/** 未落库时用本地 sceneRef,落库后切到草稿 ID */
|
||||||
|
const localSceneKey = `local-${
|
||||||
|
typeof crypto !== 'undefined' && crypto.randomUUID
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const sceneRef = computed(() =>
|
||||||
|
props.draftId != null && props.draftId > 0
|
||||||
|
? String(props.draftId)
|
||||||
|
: localSceneKey,
|
||||||
|
);
|
||||||
|
|
||||||
|
const sessionTitle = computed(() =>
|
||||||
|
props.draftId != null && props.draftId > 0
|
||||||
|
? `发布草稿 #${props.draftId}`
|
||||||
|
: '发布草稿(未保存)',
|
||||||
|
);
|
||||||
|
|
||||||
const starterPrompts = [
|
const starterPrompts = [
|
||||||
'根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
{
|
||||||
'参考渠道商品帮我整理规格轴',
|
label: '按编码生成标题',
|
||||||
'把当前标题改得更适合拼多多搜索',
|
prompt: '根据已填的 SKU 商家编码,找相似拼多多商品并生成标题',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '整理规格轴',
|
||||||
|
prompt: '参考渠道商品帮我整理规格轴',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: '优化标题',
|
||||||
|
prompt: '把当前标题改得更适合拼多多搜索',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
type BubbleView = {
|
type BubbleView = {
|
||||||
@@ -64,6 +101,7 @@ const streamingText = ref('');
|
|||||||
const toolStatusLabel = ref('');
|
const toolStatusLabel = ref('');
|
||||||
const toolStatusActive = ref(false);
|
const toolStatusActive = ref(false);
|
||||||
const draft = ref('');
|
const draft = ref('');
|
||||||
|
const citations = ref<CatalogCite[]>([]);
|
||||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||||
const selectedModelKey = ref<string | undefined>(undefined);
|
const selectedModelKey = ref<string | undefined>(undefined);
|
||||||
const patchingModel = ref(false);
|
const patchingModel = ref(false);
|
||||||
@@ -111,6 +149,12 @@ const showStarter = computed(
|
|||||||
!loadingSession.value,
|
!loadingSession.value,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const showMessageLoading = computed(
|
||||||
|
() =>
|
||||||
|
(loadingSession.value || loadingMessages.value) &&
|
||||||
|
messages.value.length === 0,
|
||||||
|
);
|
||||||
|
|
||||||
const bubbleViews = computed<BubbleView[]>(() =>
|
const bubbleViews = computed<BubbleView[]>(() =>
|
||||||
messages.value.map((m, idx) => {
|
messages.value.map((m, idx) => {
|
||||||
const isStreamingAssistant =
|
const isStreamingAssistant =
|
||||||
@@ -148,6 +192,11 @@ function syncSelectedFromSession() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearToolStatus() {
|
||||||
|
toolStatusActive.value = false;
|
||||||
|
toolStatusLabel.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
/** 滚到消息区底部;多拍几次等 ChatItem 异步撑高后再定住 */
|
/** 滚到消息区底部;多拍几次等 ChatItem 异步撑高后再定住 */
|
||||||
function scrollChatToBottom() {
|
function scrollChatToBottom() {
|
||||||
const run = () => {
|
const run = () => {
|
||||||
@@ -194,11 +243,11 @@ async function ensureSession(): Promise<string | null> {
|
|||||||
if (session.value?.threadId) return session.value.threadId;
|
if (session.value?.threadId) return session.value.threadId;
|
||||||
const parsed = parseModelKey(selectedModelKey.value);
|
const parsed = parseModelKey(selectedModelKey.value);
|
||||||
const s = await createAgentSessionApi({
|
const s = await createAgentSessionApi({
|
||||||
title: `发布草稿 #${props.draftId}`,
|
title: sessionTitle.value,
|
||||||
llmProviderId: parsed?.providerId,
|
llmProviderId: parsed?.providerId,
|
||||||
llmModel: parsed?.model,
|
llmModel: parsed?.model,
|
||||||
scene: SCENE,
|
scene: SCENE,
|
||||||
sceneRef: String(props.draftId),
|
sceneRef: sceneRef.value,
|
||||||
reuseBySceneRef: true,
|
reuseBySceneRef: true,
|
||||||
});
|
});
|
||||||
session.value = s;
|
session.value = s;
|
||||||
@@ -232,6 +281,8 @@ async function bootstrap() {
|
|||||||
loadingSession.value = true;
|
loadingSession.value = true;
|
||||||
messages.value = [];
|
messages.value = [];
|
||||||
session.value = null;
|
session.value = null;
|
||||||
|
draft.value = '';
|
||||||
|
citations.value = [];
|
||||||
try {
|
try {
|
||||||
await loadEnabledModels();
|
await loadEnabledModels();
|
||||||
const threadId = await ensureSession();
|
const threadId = await ensureSession();
|
||||||
@@ -245,7 +296,11 @@ async function bootstrap() {
|
|||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.draftId,
|
() => props.draftId,
|
||||||
() => {
|
(id, prev) => {
|
||||||
|
// 新建落库后仅 URL 从 new→id:沿用当前会话,避免打断
|
||||||
|
if (prev == null && id != null && id > 0 && session.value?.threadId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
abort?.abort();
|
abort?.abort();
|
||||||
void bootstrap();
|
void bootstrap();
|
||||||
},
|
},
|
||||||
@@ -275,8 +330,7 @@ async function onModelChange(key: string) {
|
|||||||
|
|
||||||
function appendStreamToken(t: string) {
|
function appendStreamToken(t: string) {
|
||||||
if (toolStatusActive.value) {
|
if (toolStatusActive.value) {
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
streamingText.value += t;
|
streamingText.value += t;
|
||||||
const idx = messages.value.length - 1;
|
const idx = messages.value.length - 1;
|
||||||
@@ -293,9 +347,7 @@ function onStreamTool(payload: { phase: string; label: string }) {
|
|||||||
toolStatusLabel.value = payload.label;
|
toolStatusLabel.value = payload.label;
|
||||||
void nextTick().then(scrollChatToBottom);
|
void nextTick().then(scrollChatToBottom);
|
||||||
} else if (payload.phase === 'end') {
|
} else if (payload.phase === 'end') {
|
||||||
// 结束后清状态,避免卡在「读取发布表单…」直到下一段 token
|
clearToolStatus();
|
||||||
toolStatusActive.value = false;
|
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,8 +364,12 @@ async function onClientTool(call: AgentVO.ClientToolCall) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function send(textOverride?: string) {
|
async function send(rawOverride?: string) {
|
||||||
const text = (textOverride ?? draft.value).trim();
|
const raw = (rawOverride ?? draft.value).trim();
|
||||||
|
const text = composeMessageWithCites(
|
||||||
|
stripTrailingMention(raw),
|
||||||
|
citations.value,
|
||||||
|
);
|
||||||
if (!text || sending.value) return;
|
if (!text || sending.value) return;
|
||||||
|
|
||||||
sending.value = true;
|
sending.value = true;
|
||||||
@@ -333,9 +389,9 @@ async function send(textOverride?: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
draft.value = '';
|
draft.value = '';
|
||||||
|
citations.value = [];
|
||||||
messages.value.push({
|
messages.value.push({
|
||||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||||
role: 'user',
|
role: 'user',
|
||||||
@@ -376,8 +432,7 @@ async function send(textOverride?: string) {
|
|||||||
}
|
}
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
},
|
},
|
||||||
onError: (msg) => {
|
onError: (msg) => {
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
@@ -387,40 +442,48 @@ async function send(textOverride?: string) {
|
|||||||
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||||
}
|
}
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
message.error(msg);
|
message.error(msg);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onSenderSend(value: string) {
|
||||||
|
void send(value);
|
||||||
|
}
|
||||||
|
|
||||||
function applyStarterPrompt(text: string) {
|
function applyStarterPrompt(text: string) {
|
||||||
draft.value = text;
|
draft.value = text;
|
||||||
}
|
}
|
||||||
|
|
||||||
function onStop() {
|
function onSenderStop() {
|
||||||
abort?.abort();
|
abort?.abort();
|
||||||
sending.value = false;
|
sending.value = false;
|
||||||
toolStatusActive.value = false;
|
clearToolStatus();
|
||||||
toolStatusLabel.value = '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onBeforeUnmount(() => abort?.abort());
|
onBeforeUnmount(() => abort?.abort());
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<!-- 收起:窄条 -->
|
<!-- 收起:窄条(悬停 bot→展开图标,对齐智能助手) -->
|
||||||
<div
|
<div
|
||||||
v-if="collapsed"
|
v-if="collapsed"
|
||||||
class="border-border bg-card flex h-full w-14 shrink-0 flex-col items-center border-l py-3"
|
class="publish-agent-rail border-border flex h-full w-14 shrink-0 flex-col items-center border-l px-1.5 py-2"
|
||||||
>
|
>
|
||||||
<Tooltip title="展开发布助手" placement="left">
|
<Tooltip title="展开发布助手" placement="left">
|
||||||
<Button type="text" @click="emit('expand')">
|
<button
|
||||||
<template #icon><MenuUnfoldOutlined /></template>
|
type="button"
|
||||||
</Button>
|
class="hover:bg-muted group flex size-10 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="展开发布助手"
|
||||||
|
@click="emit('expand')"
|
||||||
|
>
|
||||||
|
<AgentBrandIcon class="size-5 group-hover:hidden" />
|
||||||
|
<PanelOpenIcon class="hidden size-5 group-hover:block" />
|
||||||
|
</button>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<div
|
<div
|
||||||
class="text-muted-foreground mt-4 write-vertical-right text-xs tracking-widest"
|
class="text-muted-foreground mt-3 text-xs tracking-widest"
|
||||||
style="writing-mode: vertical-rl"
|
style="writing-mode: vertical-rl"
|
||||||
>
|
>
|
||||||
发布助手
|
发布助手
|
||||||
@@ -430,64 +493,93 @@ onBeforeUnmount(() => abort?.abort());
|
|||||||
<!-- 展开 -->
|
<!-- 展开 -->
|
||||||
<aside
|
<aside
|
||||||
v-else
|
v-else
|
||||||
class="border-border bg-card flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
class="publish-agent-panel border-border flex h-full min-h-0 w-full min-w-[280px] flex-col border-l"
|
||||||
>
|
>
|
||||||
<header
|
<header class="flex h-12 shrink-0 items-center gap-1 px-3">
|
||||||
class="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"
|
<div class="min-w-0 flex-1 truncate text-sm font-semibold">发布助手</div>
|
||||||
|
<Tooltip title="收起">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted text-muted-foreground hover:text-foreground flex size-9 items-center justify-center rounded-lg transition-colors"
|
||||||
|
aria-label="收起发布助手"
|
||||||
|
@click="emit('collapse')"
|
||||||
>
|
>
|
||||||
<span class="min-w-0 flex-1 truncate text-sm font-medium">发布助手</span>
|
<PanelCloseIcon class="size-5" />
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="relative flex min-h-0 flex-1 flex-col">
|
||||||
|
<div
|
||||||
|
v-if="showMessageLoading"
|
||||||
|
class="text-muted-foreground absolute inset-0 z-10 flex items-center justify-center bg-background/60 text-sm"
|
||||||
|
>
|
||||||
|
<Spin size="small" class="mr-2" />
|
||||||
|
加载中…
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 空态:说明 + 居中输入 + chips -->
|
||||||
|
<div
|
||||||
|
v-if="showStarter"
|
||||||
|
class="flex min-h-0 flex-1 flex-col justify-center px-3 pb-6 pt-4"
|
||||||
|
>
|
||||||
|
<div class="mb-5 px-1">
|
||||||
|
<div class="text-base font-semibold tracking-tight">
|
||||||
|
帮你完善本页草稿
|
||||||
|
</div>
|
||||||
|
<p class="text-muted-foreground mt-1.5 text-xs leading-5">
|
||||||
|
可按已填 SKU 编码查商品、生成标题并写回规格轴;改表单会落到左侧编辑区。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="publish-agent-composer w-full">
|
||||||
|
<CatalogCiteSender
|
||||||
|
v-model="draft"
|
||||||
|
v-model:cites="citations"
|
||||||
|
:loading="sending"
|
||||||
|
placeholder="描述想改的标题、规格,或用 @ 引用"
|
||||||
|
@send="onSenderSend"
|
||||||
|
@stop="onSenderStop"
|
||||||
|
>
|
||||||
|
<template #footer-extra>
|
||||||
<Select
|
<Select
|
||||||
:value="selectedModelKey"
|
:value="selectedModelKey"
|
||||||
:options="modelOptions"
|
:options="modelOptions"
|
||||||
:loading="patchingModel"
|
:loading="patchingModel"
|
||||||
:disabled="sending || enabledModels.length === 0"
|
:disabled="sending || enabledModels.length === 0"
|
||||||
placeholder="模型"
|
placeholder="模型"
|
||||||
class="w-36 shrink-0"
|
|
||||||
size="small"
|
size="small"
|
||||||
|
class="publish-agent-model-select min-w-0 max-w-[160px] flex-1"
|
||||||
:allow-clear="false"
|
:allow-clear="false"
|
||||||
@change="(v) => onModelChange(String(v ?? ''))"
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
/>
|
/>
|
||||||
<Tooltip title="收起">
|
</template>
|
||||||
<Button type="text" size="small" @click="emit('collapse')">
|
</CatalogCiteSender>
|
||||||
<template #icon><MenuFoldOutlined /></template>
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
</Button>
|
<Tooltip
|
||||||
</Tooltip>
|
v-for="item in starterPrompts"
|
||||||
</header>
|
:key="item.label"
|
||||||
|
:title="item.prompt"
|
||||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
|
||||||
<div
|
|
||||||
v-if="loadingSession || loadingMessages"
|
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
|
||||||
>
|
>
|
||||||
<Spin size="small" />
|
<button
|
||||||
|
type="button"
|
||||||
|
class="hover:bg-muted border-border text-foreground/80 hover:text-foreground inline-flex cursor-pointer items-center rounded-full border bg-card px-3 py-1.5 text-xs transition-colors"
|
||||||
|
@click="applyStarterPrompt(item.prompt)"
|
||||||
|
>
|
||||||
|
{{ item.label }}
|
||||||
|
</button>
|
||||||
|
</Tooltip>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 对话态 -->
|
||||||
|
<template v-else>
|
||||||
<div
|
<div
|
||||||
ref="messagePaneRef"
|
ref="messagePaneRef"
|
||||||
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto py-3"
|
class="publish-agent-chat t-chat t-chat--normal min-h-0 flex-1 overflow-y-auto px-3 pb-3 pt-4"
|
||||||
>
|
>
|
||||||
<div
|
|
||||||
v-if="showStarter"
|
|
||||||
class="flex h-full flex-col justify-center px-1 py-4"
|
|
||||||
>
|
|
||||||
<div class="text-sm font-medium">帮你完善本页草稿</div>
|
|
||||||
<p class="text-muted-foreground mt-2 text-xs leading-5">
|
|
||||||
可按已填 SKU 编码查内部/拼多多商品,生成标题并写回规格轴。改表单会直接落到左侧编辑区。
|
|
||||||
</p>
|
|
||||||
<div class="mt-3 flex flex-col gap-1.5">
|
|
||||||
<button
|
|
||||||
v-for="item in starterPrompts"
|
|
||||||
:key="item"
|
|
||||||
type="button"
|
|
||||||
class="hover:border-primary hover:bg-primary/5 rounded-md border border-border bg-background px-2.5 py-1.5 text-left text-xs transition-colors"
|
|
||||||
@click="applyStarterPrompt(item)"
|
|
||||||
>
|
|
||||||
{{ item }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Empty
|
<Empty
|
||||||
v-else-if="!loadingSession && !loadingMessages && messages.length === 0"
|
v-if="!showMessageLoading && messages.length === 0"
|
||||||
class="mt-16"
|
class="mt-16"
|
||||||
description="开始提问吧"
|
description="开始提问吧"
|
||||||
/>
|
/>
|
||||||
@@ -495,85 +587,176 @@ onBeforeUnmount(() => abort?.abort());
|
|||||||
v-for="item in bubbleViews"
|
v-for="item in bubbleViews"
|
||||||
:key="item.id"
|
:key="item.id"
|
||||||
class="publish-agent-item"
|
class="publish-agent-item"
|
||||||
|
:class="[
|
||||||
|
item.role === 'user'
|
||||||
|
? 'publish-agent-item--user'
|
||||||
|
: 'publish-agent-item--assistant',
|
||||||
|
{ 'publish-agent-item--loading': item.textLoading },
|
||||||
|
]"
|
||||||
:role="item.role"
|
:role="item.role"
|
||||||
:name="item.name"
|
:name="item.name"
|
||||||
:content="item.content"
|
:content="
|
||||||
:text-loading="item.textLoading"
|
item.textLoading || item.role === 'user'
|
||||||
|
? undefined
|
||||||
|
: item.content
|
||||||
|
"
|
||||||
|
:text-loading="false"
|
||||||
variant="base"
|
variant="base"
|
||||||
animation="gradient"
|
>
|
||||||
/>
|
<template v-if="item.textLoading" #content>
|
||||||
|
<ChatLoading animation="dots" />
|
||||||
|
</template>
|
||||||
|
<template v-else-if="item.role === 'user'" #content>
|
||||||
|
<CatalogCiteRichText :text="item.content" />
|
||||||
|
</template>
|
||||||
|
</ChatItem>
|
||||||
<div
|
<div
|
||||||
v-if="toolStatusActive && toolStatusLabel"
|
v-if="toolStatusActive && toolStatusLabel"
|
||||||
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
class="text-muted-foreground flex items-center gap-2 px-1 py-1 text-xs"
|
||||||
>
|
>
|
||||||
<span
|
<ChatLoading animation="dots" :text="`${toolStatusLabel}…`" />
|
||||||
class="border-primary/40 inline-block size-3 animate-spin rounded-full border-2 border-t-transparent"
|
|
||||||
/>
|
|
||||||
<span>{{ toolStatusLabel }}…</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="shrink-0 border-t border-border p-2">
|
<div class="publish-agent-composer shrink-0 px-3 pb-3 pt-1">
|
||||||
<div class="flex gap-1.5">
|
<CatalogCiteSender
|
||||||
<Input.TextArea
|
v-model="draft"
|
||||||
v-model:value="draft"
|
v-model:cites="citations"
|
||||||
:auto-size="{ minRows: 2, maxRows: 5 }"
|
:loading="sending"
|
||||||
:disabled="sending"
|
placeholder="描述想改的标题、规格,或用 @ 引用"
|
||||||
placeholder="描述你想改的标题、规格…"
|
@send="onSenderSend"
|
||||||
class="flex-1"
|
@stop="onSenderStop"
|
||||||
@keydown.enter.exact.prevent="() => send()"
|
>
|
||||||
|
<template #footer-extra>
|
||||||
|
<Select
|
||||||
|
:value="selectedModelKey"
|
||||||
|
:options="modelOptions"
|
||||||
|
:loading="patchingModel"
|
||||||
|
:disabled="sending || enabledModels.length === 0"
|
||||||
|
placeholder="模型"
|
||||||
|
size="small"
|
||||||
|
class="publish-agent-model-select min-w-0 max-w-[160px] flex-1"
|
||||||
|
:allow-clear="false"
|
||||||
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
/>
|
/>
|
||||||
<div class="flex flex-col gap-1">
|
</template>
|
||||||
<Button
|
</CatalogCiteSender>
|
||||||
v-if="sending"
|
|
||||||
type="default"
|
|
||||||
size="small"
|
|
||||||
@click="onStop"
|
|
||||||
>
|
|
||||||
停止
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
v-else
|
|
||||||
type="primary"
|
|
||||||
size="small"
|
|
||||||
:disabled="!draft.trim()"
|
|
||||||
@click="() => send()"
|
|
||||||
>
|
|
||||||
<template #icon><SendOutlined /></template>
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
</aside>
|
</aside>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
.publish-agent-rail,
|
||||||
|
.publish-agent-panel {
|
||||||
|
background: hsl(var(--muted) / 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-rail,
|
||||||
|
html.dark .publish-agent-panel,
|
||||||
|
.dark .publish-agent-rail,
|
||||||
|
.dark .publish-agent-panel {
|
||||||
|
background: hsl(var(--background-deep, var(--background)));
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-composer :deep(.t-chat-sender) {
|
||||||
|
border-radius: 20px;
|
||||||
|
box-shadow: 0 0 0 1px hsl(var(--border) / 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-composer :deep(.t-chat-sender__textarea__wrapper) {
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-model-select :deep(.ant-select-selector) {
|
||||||
|
border-radius: 999px !important;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* TDesign `.t-chat { padding: 0 }` 会盖掉 Tailwind px-*,容器左右留白写这里。
|
* ChatItem 根节点就是 .t-chat__inner,padding / justify 必须打在本类上。
|
||||||
* 不要动 `.t-chat__detail` 的 padding,那是气泡内文字边距。
|
|
||||||
*/
|
*/
|
||||||
.publish-agent-chat.t-chat {
|
|
||||||
--td-bg-color-container: transparent;
|
|
||||||
padding: 12px 16px !important;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
.publish-agent-item {
|
.publish-agent-item {
|
||||||
margin-bottom: 10px;
|
display: flex;
|
||||||
}
|
|
||||||
.publish-agent-item :deep(.t-chat__inner) {
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
padding-inline: 4px;
|
width: 100%;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding-inline: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.publish-agent-item :deep(.t-chat__content) {
|
.publish-agent-item :deep(.t-chat__content) {
|
||||||
width: auto;
|
flex: 0 1 auto !important;
|
||||||
max-width: calc(100% - 8px);
|
width: fit-content !important;
|
||||||
|
max-width: calc(100% - 4px);
|
||||||
|
justify-content: flex-start !important;
|
||||||
}
|
}
|
||||||
.publish-agent-item :deep(.t-chat__inner.user) {
|
|
||||||
|
.publish-agent-item--assistant {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--assistant :deep(.t-chat__content) {
|
||||||
|
align-self: flex-start;
|
||||||
|
align-items: flex-start !important;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user {
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user :deep(.t-chat__content) {
|
||||||
|
align-self: flex-end;
|
||||||
|
align-items: flex-end !important;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.publish-agent-item :deep(.t-chat__avatar),
|
.publish-agent-item :deep(.t-chat__avatar),
|
||||||
.publish-agent-item :deep(.t-chat__name) {
|
.publish-agent-item :deep(.t-chat__name) {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 浅色:气泡边框与底色,避免与侧栏糊在一起 */
|
||||||
|
.publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
border: 1px solid hsl(var(--border));
|
||||||
|
border-radius: 12px;
|
||||||
|
background: hsl(var(--background));
|
||||||
|
padding-block: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
.publish-agent-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.1);
|
||||||
|
border-color: hsl(var(--primary) / 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .publish-agent-item :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .publish-agent-item :deep(.t-chat__detail) {
|
||||||
|
border-color: transparent;
|
||||||
|
background: hsl(var(--muted) / 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
|
html.dark .publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
html.dark .publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
html.dark .publish-agent-item.user :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item--user :deep(.t-chat__text--variant--base .t-chat__detail),
|
||||||
|
.dark .publish-agent-item--user :deep(.t-chat__detail),
|
||||||
|
.dark .publish-agent-item.user :deep(.t-chat__detail) {
|
||||||
|
background: hsl(var(--primary) / 0.22);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+47
-7
@@ -255,6 +255,24 @@ onMounted(() => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/** 路由 draftId 变化(含 new→真实 ID):已绑定同一草稿则跳过 hydrate */
|
||||||
|
watch(
|
||||||
|
() => props.draftId,
|
||||||
|
(id, prev) => {
|
||||||
|
if (
|
||||||
|
(prev == null || prev === undefined) &&
|
||||||
|
id != null &&
|
||||||
|
id > 0 &&
|
||||||
|
draft.boundDraftId.value === id
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (id != null && id > 0 && id !== draft.boundDraftId.value) {
|
||||||
|
void draft.hydrateFromDraft(id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
function resetAll() {
|
function resetAll() {
|
||||||
draft.submitting.value = false;
|
draft.submitting.value = false;
|
||||||
Object.assign(form, createEmptyPublishForm());
|
Object.assign(form, createEmptyPublishForm());
|
||||||
@@ -361,6 +379,7 @@ const {
|
|||||||
bindInternalSku,
|
bindInternalSku,
|
||||||
applyInternalSkusInOrder,
|
applyInternalSkusInOrder,
|
||||||
clearInternalSkuBindings,
|
clearInternalSkuBindings,
|
||||||
|
applySkuBatchFields,
|
||||||
} = sku;
|
} = sku;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -390,7 +409,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
<Teleport defer to="#pdd-publish-edit-header-fields">
|
<Teleport defer to="#pdd-publish-edit-header-fields">
|
||||||
<div class="w-full min-w-0 space-y-2">
|
<div class="w-full min-w-0 space-y-2">
|
||||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0 w-full">
|
||||||
<div class="mb-1 text-sm font-medium">
|
<div class="mb-1 text-sm font-medium">
|
||||||
渠道店铺 <span class="text-destructive">*</span>
|
渠道店铺 <span class="text-destructive">*</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -405,7 +424,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
@search="(kw: string) => loadShops(kw)"
|
@search="(kw: string) => loadShops(kw)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="min-w-0">
|
<div class="min-w-0 w-full">
|
||||||
<div class="mb-1 flex items-center gap-1.5 text-sm font-medium">
|
<div class="mb-1 flex items-center gap-1.5 text-sm font-medium">
|
||||||
<span>
|
<span>
|
||||||
叶子类目 <span class="text-destructive">*</span>
|
叶子类目 <span class="text-destructive">*</span>
|
||||||
@@ -436,10 +455,12 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
/>
|
/>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Cascader 默认不吃满格子,需显式 100% 与店铺 Select 对齐 -->
|
||||||
<Cascader
|
<Cascader
|
||||||
v-model:value="form.catPath"
|
v-model:value="form.catPath"
|
||||||
v-model:search-value="catCascaderSearch"
|
v-model:search-value="catCascaderSearch"
|
||||||
class="w-full"
|
class="w-full"
|
||||||
|
:style="{ width: '100%' }"
|
||||||
:options="displayCatOptions"
|
:options="displayCatOptions"
|
||||||
:load-data="catLoadData"
|
:load-data="catLoadData"
|
||||||
:show-search="{
|
:show-search="{
|
||||||
@@ -557,14 +578,17 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
</Space>
|
</Space>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="包邮省份" :span="2">
|
<Descriptions.Item label="包邮省份" :span="2">
|
||||||
<Space v-if="costTemplateDetail.freeProvinces?.length" wrap>
|
<div
|
||||||
|
v-if="costTemplateDetail.freeProvinces?.length"
|
||||||
|
class="free-province-tags"
|
||||||
|
>
|
||||||
<Tag
|
<Tag
|
||||||
v-for="(p, idx) in costTemplateDetail.freeProvinces"
|
v-for="(p, idx) in costTemplateDetail.freeProvinces"
|
||||||
:key="`${p.provinceId}-${idx}`"
|
:key="`${p.provinceId}-${idx}`"
|
||||||
>
|
>
|
||||||
{{ p.province || p.provinceId }}
|
{{ p.province || p.provinceId }}
|
||||||
</Tag>
|
</Tag>
|
||||||
</Space>
|
</div>
|
||||||
<span v-else>暂无</span>
|
<span v-else>暂无</span>
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item
|
<Descriptions.Item
|
||||||
@@ -640,9 +664,10 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
v-model:value="form.twoPiecesDiscount"
|
v-model:value="form.twoPiecesDiscount"
|
||||||
class="w-full"
|
class="w-full"
|
||||||
:min="0"
|
:min="0"
|
||||||
:max="100"
|
:max="10"
|
||||||
:precision="0"
|
:precision="1"
|
||||||
placeholder="95 表示 95 折,0 取消"
|
:step="0.1"
|
||||||
|
placeholder="9.5 表示 9.5 折,0 取消"
|
||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</div>
|
</div>
|
||||||
@@ -777,6 +802,7 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
@out-sku-sn-blur="onOutSkuSnBlur"
|
@out-sku-sn-blur="onOutSkuSnBlur"
|
||||||
@bind-internal-sku="bindInternalSku"
|
@bind-internal-sku="bindInternalSku"
|
||||||
@sku-thumb-file-list-change="onSkuThumbFileListChange"
|
@sku-thumb-file-list-change="onSkuThumbFileListChange"
|
||||||
|
@apply-batch="applySkuBatchFields"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -836,4 +862,18 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
|
|||||||
outline-offset: 4px;
|
outline-offset: 4px;
|
||||||
transition: outline-color 0.2s ease;
|
transition: outline-color 0.2s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Space wrap 负 margin 会裁切末行 Tag;用 flex gap 并给底部留一点余量 */
|
||||||
|
.free-province-tags {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
padding-bottom: 2px;
|
||||||
|
overflow: visible;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.free-province-tags :deep(.ant-tag) {
|
||||||
|
margin-inline-end: 0;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+285
@@ -2,7 +2,10 @@
|
|||||||
import type { UploadFile, UploadProps } from 'ant-design-vue';
|
import type { UploadFile, UploadProps } from 'ant-design-vue';
|
||||||
import type { SkuRow } from '../types';
|
import type { SkuRow } from '../types';
|
||||||
|
|
||||||
|
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||||
|
|
||||||
import { PlusOutlined } from '@ant-design/icons-vue';
|
import { PlusOutlined } from '@ant-design/icons-vue';
|
||||||
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Alert,
|
Alert,
|
||||||
@@ -14,6 +17,7 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
Table,
|
Table,
|
||||||
Upload,
|
Upload,
|
||||||
|
message,
|
||||||
} from 'ant-design-vue';
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
defineOptions({ name: 'SkuTableCard' });
|
defineOptions({ name: 'SkuTableCard' });
|
||||||
@@ -47,11 +51,144 @@ const emit = defineEmits<{
|
|||||||
'out-sku-sn-blur': [rowKey: number];
|
'out-sku-sn-blur': [rowKey: number];
|
||||||
'bind-internal-sku': [rowKey: number, skuId?: number];
|
'bind-internal-sku': [rowKey: number, skuId?: number];
|
||||||
'sku-thumb-file-list-change': [rowKey: number, list: UploadFile[]];
|
'sku-thumb-file-list-change': [rowKey: number, list: UploadFile[]];
|
||||||
|
'apply-batch': [
|
||||||
|
patch: {
|
||||||
|
priceYuan?: number;
|
||||||
|
multiPriceYuan?: number;
|
||||||
|
quantity?: number;
|
||||||
|
},
|
||||||
|
];
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
|
const BatchIcon = createIconifyIcon('lucide:layers-2');
|
||||||
|
|
||||||
|
/** 列头批量:Teleport 浮层,避免被 table header overflow 裁切 */
|
||||||
|
const colBatchPrice = ref<number | undefined>(undefined);
|
||||||
|
const colBatchMulti = ref<number | undefined>(undefined);
|
||||||
|
const colBatchQty = ref<number | undefined>(undefined);
|
||||||
|
const colBatchOpen = ref<'price' | 'multi' | 'qty' | null>(null);
|
||||||
|
const batchAnchorEl = ref<HTMLElement | null>(null);
|
||||||
|
const batchPanelStyle = ref<Record<string, string>>({
|
||||||
|
top: '0px',
|
||||||
|
left: '0px',
|
||||||
|
});
|
||||||
|
/** 本次打开只自动聚焦一次,避免输入时被再次 select 覆盖 */
|
||||||
|
let batchFocusedOnce = false;
|
||||||
|
|
||||||
function setTableWrapRef(el: unknown) {
|
function setTableWrapRef(el: unknown) {
|
||||||
emit('set-table-wrap-ref', (el as HTMLElement | null) ?? null);
|
emit('set-table-wrap-ref', (el as HTMLElement | null) ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function placeBatchPanel() {
|
||||||
|
const anchor = batchAnchorEl.value;
|
||||||
|
if (!anchor) return;
|
||||||
|
const rect = anchor.getBoundingClientRect();
|
||||||
|
const panelWidth = 176;
|
||||||
|
const left = Math.min(
|
||||||
|
Math.max(8, rect.left),
|
||||||
|
window.innerWidth - panelWidth - 8,
|
||||||
|
);
|
||||||
|
batchPanelStyle.value = {
|
||||||
|
top: `${rect.bottom + 6}px`,
|
||||||
|
left: `${left}px`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleColBatch(field: 'price' | 'multi' | 'qty', event: MouseEvent) {
|
||||||
|
const anchor = event.currentTarget as HTMLElement;
|
||||||
|
if (colBatchOpen.value === field) {
|
||||||
|
closeBatchPanel();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
batchFocusedOnce = false;
|
||||||
|
batchAnchorEl.value = anchor;
|
||||||
|
colBatchOpen.value = field;
|
||||||
|
placeBatchPanel();
|
||||||
|
void nextTick(placeBatchPanel);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** InputNumber 挂载后立刻聚焦;有旧值才全选,避免输入过程中被再次 select */
|
||||||
|
function onBatchInputMounted(el: unknown) {
|
||||||
|
if (!el) return;
|
||||||
|
if (batchFocusedOnce) return;
|
||||||
|
batchFocusedOnce = true;
|
||||||
|
void nextTick(() => {
|
||||||
|
const inst = el as { focus?: () => void; $el?: HTMLElement };
|
||||||
|
inst.focus?.();
|
||||||
|
const root = inst.$el instanceof HTMLElement ? inst.$el : null;
|
||||||
|
const input = root?.querySelector<HTMLInputElement>(
|
||||||
|
'input:not([type="hidden"])',
|
||||||
|
);
|
||||||
|
if (!input) return;
|
||||||
|
input.focus();
|
||||||
|
// 仅已有内容时全选,方便覆盖;空输入不要 select,否则易干扰后续按键
|
||||||
|
if (input.value) input.select();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeBatchPanel() {
|
||||||
|
colBatchOpen.value = null;
|
||||||
|
batchAnchorEl.value = null;
|
||||||
|
batchFocusedOnce = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDocPointerDown(event: PointerEvent) {
|
||||||
|
if (!colBatchOpen.value) return;
|
||||||
|
const target = event.target;
|
||||||
|
if (target instanceof Node) {
|
||||||
|
const el = target as HTMLElement;
|
||||||
|
if (el.closest?.('.sku-batch-header') || el.closest?.('.sku-batch-panel')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
closeBatchPanel();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onWinReposition() {
|
||||||
|
if (colBatchOpen.value) placeBatchPanel();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener('pointerdown', onDocPointerDown, true);
|
||||||
|
window.addEventListener('resize', onWinReposition);
|
||||||
|
window.addEventListener('scroll', onWinReposition, true);
|
||||||
|
});
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
document.removeEventListener('pointerdown', onDocPointerDown, true);
|
||||||
|
window.removeEventListener('resize', onWinReposition);
|
||||||
|
window.removeEventListener('scroll', onWinReposition, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
function applyColumnBatch(field: 'price' | 'multi' | 'qty') {
|
||||||
|
const value =
|
||||||
|
field === 'price'
|
||||||
|
? colBatchPrice.value
|
||||||
|
: field === 'multi'
|
||||||
|
? colBatchMulti.value
|
||||||
|
: colBatchQty.value;
|
||||||
|
if (value == null) {
|
||||||
|
message.warning('请先填写要设置的值');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const patch =
|
||||||
|
field === 'price'
|
||||||
|
? { priceYuan: value }
|
||||||
|
: field === 'multi'
|
||||||
|
? { multiPriceYuan: value }
|
||||||
|
: { quantity: value };
|
||||||
|
emit('apply-batch', patch);
|
||||||
|
closeBatchPanel();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onColumnBatchEnter(
|
||||||
|
field: 'price' | 'multi' | 'qty',
|
||||||
|
event: KeyboardEvent,
|
||||||
|
) {
|
||||||
|
if (event.isComposing || event.keyCode === 229) return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
applyColumnBatch(field);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -106,6 +243,55 @@ function setTableWrapRef(el: unknown) {
|
|||||||
:locale="{ emptyText: '暂无 SKU 组合' }"
|
:locale="{ emptyText: '暂无 SKU 组合' }"
|
||||||
:columns="skuTableColumns"
|
:columns="skuTableColumns"
|
||||||
>
|
>
|
||||||
|
<template #headerCell="{ column }">
|
||||||
|
<template v-if="column.key === 'price'">
|
||||||
|
<div class="sku-batch-header">
|
||||||
|
<span>单买价</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sku-batch-icon-btn"
|
||||||
|
title="批量设置单买价"
|
||||||
|
aria-label="批量设置单买价"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="toggleColBatch('price', $event)"
|
||||||
|
>
|
||||||
|
<BatchIcon class="sku-batch-icon" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="column.key === 'multi'">
|
||||||
|
<div class="sku-batch-header">
|
||||||
|
<span>拼单价</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sku-batch-icon-btn"
|
||||||
|
title="批量设置拼单价"
|
||||||
|
aria-label="批量设置拼单价"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="toggleColBatch('multi', $event)"
|
||||||
|
>
|
||||||
|
<BatchIcon class="sku-batch-icon" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="column.key === 'qty'">
|
||||||
|
<div class="sku-batch-header">
|
||||||
|
<span>库存</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="sku-batch-icon-btn"
|
||||||
|
title="批量设置库存"
|
||||||
|
aria-label="批量设置库存"
|
||||||
|
@mousedown.prevent
|
||||||
|
@click="toggleColBatch('qty', $event)"
|
||||||
|
>
|
||||||
|
<BatchIcon class="sku-batch-icon" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else>{{ column.title }}</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
<template #bodyCell="{ column, record }">
|
<template #bodyCell="{ column, record }">
|
||||||
<template v-if="String(column.key || '').startsWith('spec_')">
|
<template v-if="String(column.key || '').startsWith('spec_')">
|
||||||
<AutoComplete
|
<AutoComplete
|
||||||
@@ -259,9 +445,95 @@ function setTableWrapRef(el: unknown) {
|
|||||||
</Table>
|
</Table>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Teleport to="body">
|
||||||
|
<div
|
||||||
|
v-if="colBatchOpen"
|
||||||
|
class="sku-batch-panel"
|
||||||
|
:style="batchPanelStyle"
|
||||||
|
@mousedown.stop
|
||||||
|
>
|
||||||
|
<InputNumber
|
||||||
|
v-if="colBatchOpen === 'price'"
|
||||||
|
:ref="onBatchInputMounted"
|
||||||
|
:value="colBatchPrice"
|
||||||
|
:min="0.01"
|
||||||
|
:precision="2"
|
||||||
|
placeholder="统一单买价,回车应用"
|
||||||
|
class="w-40"
|
||||||
|
@update:value="
|
||||||
|
(v) => (colBatchPrice = v == null ? undefined : Number(v))
|
||||||
|
"
|
||||||
|
@keydown.enter="(e: KeyboardEvent) => onColumnBatchEnter('price', e)"
|
||||||
|
/>
|
||||||
|
<InputNumber
|
||||||
|
v-else-if="colBatchOpen === 'multi'"
|
||||||
|
:ref="onBatchInputMounted"
|
||||||
|
:value="colBatchMulti"
|
||||||
|
:min="0.01"
|
||||||
|
:precision="2"
|
||||||
|
placeholder="统一拼单价,回车应用"
|
||||||
|
class="w-40"
|
||||||
|
@update:value="
|
||||||
|
(v) => (colBatchMulti = v == null ? undefined : Number(v))
|
||||||
|
"
|
||||||
|
@keydown.enter="(e: KeyboardEvent) => onColumnBatchEnter('multi', e)"
|
||||||
|
/>
|
||||||
|
<InputNumber
|
||||||
|
v-else
|
||||||
|
:ref="onBatchInputMounted"
|
||||||
|
:value="colBatchQty"
|
||||||
|
:min="0"
|
||||||
|
placeholder="统一库存,回车应用"
|
||||||
|
class="w-40"
|
||||||
|
@update:value="(v) => (colBatchQty = v == null ? undefined : Number(v))"
|
||||||
|
@keydown.enter="(e: KeyboardEvent) => onColumnBatchEnter('qty', e)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
.sku-batch-header {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sku-batch-icon-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-shrink: 0;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
line-height: 1;
|
||||||
|
color: hsl(var(--muted-foreground));
|
||||||
|
cursor: pointer;
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
outline: none;
|
||||||
|
transition: color 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sku-batch-icon-btn:hover {
|
||||||
|
color: hsl(var(--primary));
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sku-batch-icon-btn:focus-visible {
|
||||||
|
color: hsl(var(--primary));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sku-batch-icon {
|
||||||
|
display: block;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
/* SKU 列内缩略图:更小的 picture-card,悬停仍显示预览/删除 */
|
/* SKU 列内缩略图:更小的 picture-card,悬停仍显示预览/删除 */
|
||||||
.sku-thumb-upload :deep(.ant-upload-select),
|
.sku-thumb-upload :deep(.ant-upload-select),
|
||||||
.sku-thumb-upload :deep(.ant-upload-list-item-container) {
|
.sku-thumb-upload :deep(.ant-upload-list-item-container) {
|
||||||
@@ -275,3 +547,16 @@ function setTableWrapRef(el: unknown) {
|
|||||||
padding: 2px;
|
padding: 2px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<!-- Teleport 到 body,需非 scoped 样式 -->
|
||||||
|
<style>
|
||||||
|
.sku-batch-panel {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 1100;
|
||||||
|
padding: 8px;
|
||||||
|
background: hsl(var(--popover, var(--background, 0 0% 100%)));
|
||||||
|
border: 1px solid hsl(var(--border, 0 0% 90%));
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
+24
-22
@@ -18,12 +18,14 @@ import {
|
|||||||
updatePddPublishDeskDraftApi,
|
updatePddPublishDeskDraftApi,
|
||||||
} from '#/api/channel/pdd/goods';
|
} from '#/api/channel/pdd/goods';
|
||||||
|
|
||||||
import type {
|
import {
|
||||||
PersistedUpload,
|
twoPiecesDiscountFromStored,
|
||||||
PublishFormFields,
|
twoPiecesDiscountToApi,
|
||||||
SpecAxis,
|
type PersistedUpload,
|
||||||
SpecCatalogItem,
|
type PublishFormFields,
|
||||||
SkuRow,
|
type SpecAxis,
|
||||||
|
type SpecCatalogItem,
|
||||||
|
type SkuRow,
|
||||||
} from '../types';
|
} from '../types';
|
||||||
|
|
||||||
type EmitDraft = {
|
type EmitDraft = {
|
||||||
@@ -185,9 +187,9 @@ export function usePublishDraft(options: {
|
|||||||
if (
|
if (
|
||||||
form.twoPiecesDiscount == null ||
|
form.twoPiecesDiscount == null ||
|
||||||
form.twoPiecesDiscount < 0 ||
|
form.twoPiecesDiscount < 0 ||
|
||||||
form.twoPiecesDiscount > 100
|
form.twoPiecesDiscount > 10
|
||||||
) {
|
) {
|
||||||
message.warning('请填写满两件折扣(0-100,95表示95折)');
|
message.warning('请填写正常折扣(0-10,9.5 表示 9.5 折)');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
for (const p of nonSaleProps.value) {
|
for (const p of nonSaleProps.value) {
|
||||||
@@ -362,7 +364,7 @@ export function usePublishDraft(options: {
|
|||||||
isPreSale: form.isPreSale,
|
isPreSale: form.isPreSale,
|
||||||
isRefundable: form.isRefundable,
|
isRefundable: form.isRefundable,
|
||||||
secondHand: form.secondHand,
|
secondHand: form.secondHand,
|
||||||
twoPiecesDiscount: form.twoPiecesDiscount,
|
twoPiecesDiscount: twoPiecesDiscountToApi(form.twoPiecesDiscount),
|
||||||
carouselImages: carouselFileIds.map(String),
|
carouselImages: carouselFileIds.map(String),
|
||||||
detailImages: detailFileIds.map(String),
|
detailImages: detailFileIds.map(String),
|
||||||
goodsProperties,
|
goodsProperties,
|
||||||
@@ -459,7 +461,7 @@ export function usePublishDraft(options: {
|
|||||||
}
|
}
|
||||||
if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand;
|
if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand;
|
||||||
if (typeof es.twoPiecesDiscount === 'number') {
|
if (typeof es.twoPiecesDiscount === 'number') {
|
||||||
form.twoPiecesDiscount = es.twoPiecesDiscount;
|
form.twoPiecesDiscount = twoPiecesDiscountFromStored(es.twoPiecesDiscount);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
es.goodsPropValues &&
|
es.goodsPropValues &&
|
||||||
@@ -777,8 +779,12 @@ export function usePublishDraft(options: {
|
|||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
if (!validateForm()) return;
|
if (!validateForm()) return;
|
||||||
submitting.value = true;
|
submitting.value = true;
|
||||||
const hide = message.loading('正在上传图片并发布…', 0);
|
const hide = message.loading('正在保存并发布…', 0);
|
||||||
try {
|
try {
|
||||||
|
// 先落/更新系统草稿(含 publishPayload),再发布以便回写 goods_commit_id / goods_id
|
||||||
|
const saved = await saveDeskDraft(true, { silentSuccess: true });
|
||||||
|
if (!saved?.id) return;
|
||||||
|
|
||||||
const pendingThumbs = skuRows.value
|
const pendingThumbs = skuRows.value
|
||||||
.map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] }))
|
.map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] }))
|
||||||
.filter((x): x is { rowKey: number; file: UploadFile } => !!x.file);
|
.filter((x): x is { rowKey: number; file: UploadFile } => !!x.file);
|
||||||
@@ -797,8 +803,8 @@ export function usePublishDraft(options: {
|
|||||||
const thumbPersisted = persistedAll.slice(p);
|
const thumbPersisted = persistedAll.slice(p);
|
||||||
const thumbFileIdBySkuKey = new Map<number, number>();
|
const thumbFileIdBySkuKey = new Map<number, number>();
|
||||||
pendingThumbs.forEach((item, i) => {
|
pendingThumbs.forEach((item, i) => {
|
||||||
const saved = thumbPersisted[i];
|
const savedThumb = thumbPersisted[i];
|
||||||
if (saved) thumbFileIdBySkuKey.set(item.rowKey, saved.fileId);
|
if (savedThumb) thumbFileIdBySkuKey.set(item.rowKey, savedThumb.fileId);
|
||||||
});
|
});
|
||||||
|
|
||||||
const payload = await buildPublishPayload(
|
const payload = await buildPublishPayload(
|
||||||
@@ -806,17 +812,13 @@ export function usePublishDraft(options: {
|
|||||||
detailFileIds,
|
detailFileIds,
|
||||||
thumbFileIdBySkuKey,
|
thumbFileIdBySkuKey,
|
||||||
);
|
);
|
||||||
// 确保有系统草稿并回传 ID,发布结果才能写入 goods_commit_id
|
|
||||||
if (boundDraftId.value) {
|
|
||||||
payload.systemDraftId = boundDraftId.value;
|
|
||||||
} else if (form.pddShopId) {
|
|
||||||
const saved = await saveDeskDraft(true, { silentSuccess: true });
|
|
||||||
if (saved?.id) {
|
|
||||||
payload.systemDraftId = saved.id;
|
payload.systemDraftId = saved.id;
|
||||||
}
|
|
||||||
}
|
|
||||||
const res = await publishPddGoodsApi(payload);
|
const res = await publishPddGoodsApi(payload);
|
||||||
message.success(`发布成功,goodsId=${res.goodsId}`);
|
message.success(
|
||||||
|
res.goodsId != null
|
||||||
|
? `发布成功,goodsId=${res.goodsId}`
|
||||||
|
: '发布成功',
|
||||||
|
);
|
||||||
emit('success');
|
emit('success');
|
||||||
closeEditor();
|
closeEditor();
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
|
|||||||
+42
@@ -636,6 +636,47 @@ export function usePublishSku(options: {
|
|||||||
message.success('已清空内部 SKU 关联');
|
message.success('已清空内部 SKU 关联');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 批量改价/库存:未传字段不覆盖;默认改全部行。 */
|
||||||
|
function applySkuBatchFields(patch: {
|
||||||
|
priceYuan?: number;
|
||||||
|
multiPriceYuan?: number;
|
||||||
|
quantity?: number;
|
||||||
|
}) {
|
||||||
|
const targets = skuRows.value;
|
||||||
|
if (targets.length === 0) {
|
||||||
|
message.warning('暂无 SKU 可更新');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasPrice = patch.priceYuan != null;
|
||||||
|
const hasMulti = patch.multiPriceYuan != null;
|
||||||
|
const hasQty = patch.quantity != null;
|
||||||
|
if (!hasPrice && !hasMulti && !hasQty) {
|
||||||
|
message.warning('请至少填写一项要批量设置的值');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hasPrice && (patch.priceYuan as number) < 0.01) {
|
||||||
|
message.warning('单买价不能小于 0.01');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hasMulti && (patch.multiPriceYuan as number) < 0.01) {
|
||||||
|
message.warning('拼单价不能小于 0.01');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hasQty && (patch.quantity as number) < 0) {
|
||||||
|
message.warning('库存不能为负数');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const row of targets) {
|
||||||
|
if (hasPrice) row.priceYuan = patch.priceYuan;
|
||||||
|
if (hasMulti) row.multiPriceYuan = patch.multiPriceYuan;
|
||||||
|
if (hasQty) row.quantity = patch.quantity as number;
|
||||||
|
}
|
||||||
|
message.success(`已更新 ${targets.length} 条 SKU`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/** 新增规格后滚到表体底部,方便继续编辑新行 */
|
/** 新增规格后滚到表体底部,方便继续编辑新行 */
|
||||||
async function scrollSkuTableToBottom() {
|
async function scrollSkuTableToBottom() {
|
||||||
await nextTick();
|
await nextTick();
|
||||||
@@ -689,6 +730,7 @@ export function usePublishSku(options: {
|
|||||||
onOutSkuSnBlur,
|
onOutSkuSnBlur,
|
||||||
applyInternalSkusInOrder,
|
applyInternalSkusInOrder,
|
||||||
clearInternalSkuBindings,
|
clearInternalSkuBindings,
|
||||||
|
applySkuBatchFields,
|
||||||
scrollSkuTableToBottom,
|
scrollSkuTableToBottom,
|
||||||
resetSkuRowSeq,
|
resetSkuRowSeq,
|
||||||
bumpSkuRowSeqFromKeys,
|
bumpSkuRowSeqFromKeys,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
/**
|
/**
|
||||||
* 发布编辑页路由入口(editor/index):Page 布局 + 左侧表单 + 右侧 Agent。
|
* 发布编辑页路由入口(editor/index):Page 布局 + 左侧表单 + 右侧 Agent。
|
||||||
* 表单实现见同目录 PddPublishEditor;智能体见 ../agent。
|
* 表单实现见同目录 PddPublishEditor;智能体见 ../agent。
|
||||||
|
* draftId=new 表示尚未落库的空编辑;保存/推送/发布时再创建系统草稿。
|
||||||
*/
|
*/
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
@@ -19,10 +20,20 @@ defineOptions({ name: 'PddGoodsPublishDeskEdit' });
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
/** 数字 ID;new / 非法 → null(尚未创建系统草稿) */
|
||||||
const draftId = computed(() => {
|
const draftId = computed(() => {
|
||||||
const raw = route.params.draftId;
|
const raw = route.params.draftId;
|
||||||
const n = Number(Array.isArray(raw) ? raw[0] : raw);
|
const s = String(Array.isArray(raw) ? raw[0] : raw ?? '');
|
||||||
return Number.isFinite(n) ? n : null;
|
if (!s || s === 'new') return null;
|
||||||
|
const n = Number(s);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const presetPddShopId = computed(() => {
|
||||||
|
const raw = route.query.shopId;
|
||||||
|
const s = String(Array.isArray(raw) ? raw[0] : raw ?? '');
|
||||||
|
const n = Number(s);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : null;
|
||||||
});
|
});
|
||||||
|
|
||||||
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
const editorRef = ref<PublishEditorAgentApi | null>(null);
|
||||||
@@ -47,6 +58,15 @@ const agentPaneStyle = computed(() => {
|
|||||||
function goBack() {
|
function goBack() {
|
||||||
void router.push('/pdd/goods/publish');
|
void router.push('/pdd/goods/publish');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 首次落库后把 URL 换成真实草稿 ID,便于刷新续编与 Agent 绑定 */
|
||||||
|
function onDraftSaved(id: number) {
|
||||||
|
if (!id || draftId.value === id) return;
|
||||||
|
void router.replace({
|
||||||
|
path: `/pdd/goods/publish/editor/${id}`,
|
||||||
|
query: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -60,33 +80,22 @@ function goBack() {
|
|||||||
>
|
>
|
||||||
<template #title>
|
<template #title>
|
||||||
<div class="w-full space-y-3">
|
<div class="w-full space-y-3">
|
||||||
<div class="mb-0 flex items-baseline text-lg font-semibold">
|
|
||||||
编辑系统草稿
|
|
||||||
<span
|
|
||||||
v-if="draftId"
|
|
||||||
class="text-muted-foreground ml-2 text-sm font-normal"
|
|
||||||
>
|
|
||||||
#{{ draftId }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<!-- Editor Teleport:店铺 / 类目 -->
|
<!-- Editor Teleport:店铺 / 类目 -->
|
||||||
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
|
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div
|
<div class="flex min-h-0 flex-1 overflow-hidden">
|
||||||
v-if="draftId"
|
|
||||||
class="flex min-h-0 flex-1 overflow-hidden"
|
|
||||||
>
|
|
||||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||||
<PddPublishEditor
|
<PddPublishEditor
|
||||||
ref="editorRef"
|
ref="editorRef"
|
||||||
class="h-full min-h-0"
|
class="h-full min-h-0"
|
||||||
:open="true"
|
:open="true"
|
||||||
:draft-id="draftId"
|
:draft-id="draftId"
|
||||||
|
:preset-pdd-shop-id="presetPddShopId"
|
||||||
@close="goBack"
|
@close="goBack"
|
||||||
@success="goBack"
|
@success="goBack"
|
||||||
@draft-saved="() => undefined"
|
@draft-saved="onDraftSaved"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -101,10 +101,23 @@ export type PublishFormFields = {
|
|||||||
isPreSale: boolean;
|
isPreSale: boolean;
|
||||||
isRefundable: boolean;
|
isRefundable: boolean;
|
||||||
secondHand: boolean;
|
secondHand: boolean;
|
||||||
|
/** 表单展示用折扣:0–10,9.5=9.5折;提交接口时 *10 */
|
||||||
twoPiecesDiscount: number;
|
twoPiecesDiscount: number;
|
||||||
goodsPropValues: Record<string, string>;
|
goodsPropValues: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 表单折扣 → 拼多多接口整数(9.5 → 95) */
|
||||||
|
export function twoPiecesDiscountToApi(ui: number | null | undefined): number {
|
||||||
|
if (ui == null || Number.isNaN(ui)) return 95;
|
||||||
|
return Math.round(ui * 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 接口/旧草稿整数 → 表单折扣(95 → 9.5;已是 0–10 则原样) */
|
||||||
|
export function twoPiecesDiscountFromStored(raw: number): number {
|
||||||
|
if (raw > 10) return Math.round((raw / 10) * 10) / 10;
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
/** 创建空白发布表单字段 */
|
/** 创建空白发布表单字段 */
|
||||||
export function createEmptyPublishForm(): PublishFormFields {
|
export function createEmptyPublishForm(): PublishFormFields {
|
||||||
return {
|
return {
|
||||||
@@ -117,11 +130,11 @@ export function createEmptyPublishForm(): PublishFormFields {
|
|||||||
costTemplateId: undefined,
|
costTemplateId: undefined,
|
||||||
marketPriceYuan: undefined,
|
marketPriceYuan: undefined,
|
||||||
shipmentLimitSecond: 172800,
|
shipmentLimitSecond: 172800,
|
||||||
isFolt: true,
|
isFolt: false,
|
||||||
isPreSale: false,
|
isPreSale: false,
|
||||||
isRefundable: true,
|
isRefundable: true,
|
||||||
secondHand: false,
|
secondHand: false,
|
||||||
twoPiecesDiscount: 95,
|
twoPiecesDiscount: 9.5,
|
||||||
goodsPropValues: {},
|
goodsPropValues: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import {
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
clonePddPublishDeskDraftApi,
|
clonePddPublishDeskDraftApi,
|
||||||
createPddPublishDeskDraftApi,
|
|
||||||
createPddPublishDeskJobApi,
|
createPddPublishDeskJobApi,
|
||||||
deletePddPublishDeskDraftApi,
|
deletePddPublishDeskDraftApi,
|
||||||
getPddPublishDeskJobApi,
|
getPddPublishDeskJobApi,
|
||||||
@@ -315,18 +314,15 @@ function selectUnassigned() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createDraft() {
|
async function createDraft() {
|
||||||
try {
|
const query =
|
||||||
const draft = await createPddPublishDeskDraftApi({
|
selectedShopId.value != null && selectedShopId.value > 0
|
||||||
title: '未命名草稿',
|
? { shopId: String(selectedShopId.value) }
|
||||||
pddShopId: selectedShopId.value,
|
: undefined;
|
||||||
status: 'EDITING',
|
// 先进空编辑页,用户保存/推送/发布时再落系统草稿
|
||||||
skuCount: 0,
|
await router.push({
|
||||||
|
path: '/pdd/goods/publish/editor/new',
|
||||||
|
query,
|
||||||
});
|
});
|
||||||
message.success('已创建系统草稿');
|
|
||||||
await router.push(`/pdd/goods/publish/editor/${draft.id}`);
|
|
||||||
} catch (e: any) {
|
|
||||||
message.error(e?.message || '创建失败');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEdit(id: number) {
|
function openEdit(id: number) {
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { OpTeamVO } from '#/api/ec/op-team';
|
||||||
|
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
|
||||||
|
import { useVbenModal } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Drawer,
|
||||||
|
Empty,
|
||||||
|
Form,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
message,
|
||||||
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
|
import {
|
||||||
|
addOpTeamMemberApi,
|
||||||
|
getOpTeamCandidatesApi,
|
||||||
|
getOpTeamMembersApi,
|
||||||
|
removeOpTeamMemberApi,
|
||||||
|
updateOpTeamMemberRoleApi,
|
||||||
|
} from '#/api/ec/op-team';
|
||||||
|
import { PermissionGate } from '#/components/permission';
|
||||||
|
import { usePermission } from '#/composables/use-permission';
|
||||||
|
|
||||||
|
const ROLE_LEADER = 1;
|
||||||
|
const ROLE_MEMBER = 2;
|
||||||
|
|
||||||
|
const { hasPermission } = usePermission();
|
||||||
|
const canUpdate = computed(() => hasPermission('ec:op-team:update'));
|
||||||
|
|
||||||
|
const roleOptions = [
|
||||||
|
{ label: '负责人', value: ROLE_LEADER },
|
||||||
|
{ label: '成员', value: ROLE_MEMBER },
|
||||||
|
];
|
||||||
|
|
||||||
|
const openFlag = ref(false);
|
||||||
|
const loading = ref(false);
|
||||||
|
const team = ref<null | OpTeamVO.Info>(null);
|
||||||
|
const members = ref<OpTeamVO.Member[]>([]);
|
||||||
|
const candidates = ref<OpTeamVO.Candidate[]>([]);
|
||||||
|
|
||||||
|
const [AddModal, addModalApi] = useVbenModal({
|
||||||
|
draggable: true,
|
||||||
|
class: 'w-[440px]',
|
||||||
|
zIndex: 2100,
|
||||||
|
onCancel() {
|
||||||
|
addModalApi.close();
|
||||||
|
},
|
||||||
|
onConfirm() {
|
||||||
|
void submitAdd();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const addFormRef = ref();
|
||||||
|
const addSubmitting = ref(false);
|
||||||
|
const addForm = ref({
|
||||||
|
companyMemberId: undefined as number | undefined,
|
||||||
|
role: ROLE_MEMBER,
|
||||||
|
});
|
||||||
|
|
||||||
|
const title = computed(() =>
|
||||||
|
team.value ? `团队成员 · ${team.value.name}` : '团队成员',
|
||||||
|
);
|
||||||
|
|
||||||
|
const memberCompanyMemberIds = computed(
|
||||||
|
() => new Set(members.value.map((m) => m.companyMemberId)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const candidateOptions = computed(() =>
|
||||||
|
candidates.value
|
||||||
|
.filter(
|
||||||
|
(c) =>
|
||||||
|
c.companyMemberId != null &&
|
||||||
|
!memberCompanyMemberIds.value.has(c.companyMemberId),
|
||||||
|
)
|
||||||
|
.map((c) => ({
|
||||||
|
value: c.companyMemberId,
|
||||||
|
label:
|
||||||
|
[c.realName, c.phone].filter(Boolean).join(' · ') ||
|
||||||
|
`成员#${c.companyMemberId}`,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 模态 zIndex=2100,下拉需挂到触发节点父级并抬高层级,否则点开看不见 */
|
||||||
|
function selectPopupContainer(node: HTMLElement) {
|
||||||
|
return (node.parentElement || document.body) as HTMLElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectDropdownStyle = { zIndex: 2300 };
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{ title: '姓名', dataIndex: 'realName', key: 'realName' },
|
||||||
|
{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 140 },
|
||||||
|
{ title: '角色', key: 'role', width: 140 },
|
||||||
|
{ title: '操作', key: 'action', width: 88 },
|
||||||
|
];
|
||||||
|
|
||||||
|
async function loadMembers() {
|
||||||
|
if (!team.value) return;
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
members.value = await getOpTeamMembersApi(team.value.id);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载团队成员失败:', error);
|
||||||
|
message.error('加载团队成员失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadCandidates() {
|
||||||
|
try {
|
||||||
|
candidates.value = await getOpTeamCandidatesApi();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载本公司成员失败:', error);
|
||||||
|
message.error('加载本公司成员失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAdd() {
|
||||||
|
addForm.value = { companyMemberId: undefined, role: ROLE_MEMBER };
|
||||||
|
await loadCandidates();
|
||||||
|
addModalApi.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitAdd() {
|
||||||
|
try {
|
||||||
|
await addFormRef.value?.validate();
|
||||||
|
if (!team.value || addForm.value.companyMemberId == null) return;
|
||||||
|
addSubmitting.value = true;
|
||||||
|
await addOpTeamMemberApi({
|
||||||
|
teamId: team.value.id,
|
||||||
|
companyMemberId: addForm.value.companyMemberId,
|
||||||
|
role: addForm.value.role,
|
||||||
|
});
|
||||||
|
message.success('已加入团队');
|
||||||
|
addModalApi.close();
|
||||||
|
await loadMembers();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('添加成员失败:', error);
|
||||||
|
message.error('添加成员失败');
|
||||||
|
} finally {
|
||||||
|
addSubmitting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changeRole(row: OpTeamVO.Member, role: number) {
|
||||||
|
try {
|
||||||
|
await updateOpTeamMemberRoleApi(row.id, { role });
|
||||||
|
message.success(role === ROLE_LEADER ? '已设为负责人' : '已改为成员');
|
||||||
|
await loadMembers();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('更新角色失败:', error);
|
||||||
|
message.error('更新角色失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeMember(row: OpTeamVO.Member) {
|
||||||
|
if (!team.value) return;
|
||||||
|
try {
|
||||||
|
await removeOpTeamMemberApi({
|
||||||
|
teamId: team.value.id,
|
||||||
|
companyMemberId: row.companyMemberId,
|
||||||
|
});
|
||||||
|
message.success('已移除');
|
||||||
|
await loadMembers();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('移除成员失败:', error);
|
||||||
|
message.error('移除成员失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function open(record: OpTeamVO.Info) {
|
||||||
|
team.value = record;
|
||||||
|
members.value = [];
|
||||||
|
openFlag.value = true;
|
||||||
|
void loadMembers();
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
openFlag.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ open, close });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Drawer
|
||||||
|
v-model:open="openFlag"
|
||||||
|
:title="title"
|
||||||
|
:width="640"
|
||||||
|
destroy-on-close
|
||||||
|
@close="close"
|
||||||
|
>
|
||||||
|
<div class="mb-3 flex justify-end">
|
||||||
|
<PermissionGate code="ec:op-team:update">
|
||||||
|
<Button type="primary" @click="openAdd">添加成员</Button>
|
||||||
|
</PermissionGate>
|
||||||
|
</div>
|
||||||
|
<Table
|
||||||
|
:columns="columns"
|
||||||
|
:data-source="members"
|
||||||
|
:loading="loading"
|
||||||
|
:pagination="false"
|
||||||
|
row-key="id"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
<template #bodyCell="{ column, record }">
|
||||||
|
<template v-if="column.key === 'role'">
|
||||||
|
<Select
|
||||||
|
v-if="canUpdate"
|
||||||
|
:value="(record as OpTeamVO.Member).role"
|
||||||
|
:options="roleOptions"
|
||||||
|
class="w-full"
|
||||||
|
size="small"
|
||||||
|
@change="(val) => changeRole(record as OpTeamVO.Member, Number(val))"
|
||||||
|
/>
|
||||||
|
<Tag
|
||||||
|
v-else
|
||||||
|
:color="(record as OpTeamVO.Member).role === ROLE_LEADER ? 'gold' : 'default'"
|
||||||
|
>
|
||||||
|
{{
|
||||||
|
(record as OpTeamVO.Member).roleName ||
|
||||||
|
((record as OpTeamVO.Member).role === ROLE_LEADER ? '负责人' : '成员')
|
||||||
|
}}
|
||||||
|
</Tag>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="column.key === 'action'">
|
||||||
|
<PermissionGate code="ec:op-team:update">
|
||||||
|
<Popconfirm
|
||||||
|
title="确定移出该成员?"
|
||||||
|
@confirm="removeMember(record as OpTeamVO.Member)"
|
||||||
|
>
|
||||||
|
<Button size="small" danger>移除</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</PermissionGate>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
<template #emptyText>
|
||||||
|
<Empty description="暂无成员" />
|
||||||
|
</template>
|
||||||
|
</Table>
|
||||||
|
</Drawer>
|
||||||
|
|
||||||
|
<AddModal title="添加成员" :confirm-loading="addSubmitting">
|
||||||
|
<Form
|
||||||
|
ref="addFormRef"
|
||||||
|
:model="addForm"
|
||||||
|
:label-col="{ span: 6 }"
|
||||||
|
:wrapper-col="{ span: 18 }"
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
label="成员"
|
||||||
|
name="companyMemberId"
|
||||||
|
:rules="[{ required: true, message: '请选择成员' }]"
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
v-model:value="addForm.companyMemberId"
|
||||||
|
show-search
|
||||||
|
option-filter-prop="label"
|
||||||
|
placeholder="请选择本公司成员"
|
||||||
|
:options="candidateOptions"
|
||||||
|
:get-popup-container="selectPopupContainer"
|
||||||
|
:dropdown-style="selectDropdownStyle"
|
||||||
|
:not-found-content="
|
||||||
|
candidateOptions.length === 0 ? '没有可添加的成员' : undefined
|
||||||
|
"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="角色" name="role">
|
||||||
|
<Select
|
||||||
|
v-model:value="addForm.role"
|
||||||
|
:options="roleOptions"
|
||||||
|
:get-popup-container="selectPopupContainer"
|
||||||
|
:dropdown-style="selectDropdownStyle"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</AddModal>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { OpTeamVO } from '#/api/ec/op-team';
|
||||||
|
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
|
||||||
|
import { useVbenModal } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import { Form, Input, InputNumber, message, Switch } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { createOpTeamApi, updateOpTeamApi } from '#/api/ec/op-team';
|
||||||
|
|
||||||
|
const emit = defineEmits<{ success: [] }>();
|
||||||
|
|
||||||
|
const [Modal, modalApi] = useVbenModal({
|
||||||
|
draggable: true,
|
||||||
|
class: 'w-[500px]',
|
||||||
|
// 高于 antd Drawer 的 zIndexPopupBase(2000)
|
||||||
|
zIndex: 2100,
|
||||||
|
onCancel() {
|
||||||
|
modalApi.close();
|
||||||
|
},
|
||||||
|
onConfirm() {
|
||||||
|
void handleSubmit();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const formRef = ref();
|
||||||
|
const loading = ref(false);
|
||||||
|
const isEdit = ref(false);
|
||||||
|
const current = ref<null | OpTeamVO.Info>(null);
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
name: string;
|
||||||
|
remark: string;
|
||||||
|
status: boolean;
|
||||||
|
sortOrder: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = ref<FormData>({
|
||||||
|
name: '',
|
||||||
|
remark: '',
|
||||||
|
status: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const modalTitle = computed(() => (isEdit.value ? '编辑运营团队' : '添加运营团队'));
|
||||||
|
|
||||||
|
function resetForm() {
|
||||||
|
formData.value = {
|
||||||
|
name: '',
|
||||||
|
remark: '',
|
||||||
|
status: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
};
|
||||||
|
formRef.value?.resetFields();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
try {
|
||||||
|
await formRef.value?.validate();
|
||||||
|
loading.value = true;
|
||||||
|
const payload = {
|
||||||
|
name: formData.value.name,
|
||||||
|
remark: formData.value.remark || undefined,
|
||||||
|
status: formData.value.status ? 1 : 0,
|
||||||
|
sortOrder: formData.value.sortOrder,
|
||||||
|
};
|
||||||
|
if (isEdit.value && current.value) {
|
||||||
|
await updateOpTeamApi(current.value.id, payload);
|
||||||
|
message.success('更新成功');
|
||||||
|
} else {
|
||||||
|
await createOpTeamApi(payload);
|
||||||
|
message.success('创建成功');
|
||||||
|
}
|
||||||
|
emit('success');
|
||||||
|
modalApi.close();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('保存运营团队失败:', error);
|
||||||
|
message.error('保存运营团队失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function open(editMode = false, record?: null | OpTeamVO.Info) {
|
||||||
|
isEdit.value = editMode;
|
||||||
|
current.value = record ?? null;
|
||||||
|
resetForm();
|
||||||
|
if (editMode && record) {
|
||||||
|
formData.value = {
|
||||||
|
name: record.name,
|
||||||
|
remark: record.remark || '',
|
||||||
|
status: record.status === 1,
|
||||||
|
sortOrder: record.sortOrder ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
modalApi.open();
|
||||||
|
}
|
||||||
|
|
||||||
|
defineExpose({ open });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Modal :title="modalTitle" :confirm-loading="loading">
|
||||||
|
<Form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formData"
|
||||||
|
:label-col="{ span: 6 }"
|
||||||
|
:wrapper-col="{ span: 18 }"
|
||||||
|
>
|
||||||
|
<Form.Item
|
||||||
|
label="团队名称"
|
||||||
|
name="name"
|
||||||
|
:rules="[{ required: true, message: '请输入团队名称' }]"
|
||||||
|
>
|
||||||
|
<Input v-model:value="formData.name" placeholder="请输入团队名称" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="备注" name="remark">
|
||||||
|
<Input.TextArea
|
||||||
|
v-model:value="formData.remark"
|
||||||
|
placeholder="请输入备注"
|
||||||
|
:rows="3"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="排序" name="sortOrder">
|
||||||
|
<InputNumber v-model:value="formData.sortOrder" :min="0" class="w-full" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="状态" name="status">
|
||||||
|
<Switch
|
||||||
|
v-model:checked="formData.status"
|
||||||
|
checked-children="启用"
|
||||||
|
un-checked-children="停用"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||||
|
import type { OpTeamDTO, OpTeamVO } from '#/api/ec/op-team';
|
||||||
|
import type { PageQueryDTO } from '#/types/common';
|
||||||
|
|
||||||
|
import { computed, ref } from 'vue';
|
||||||
|
|
||||||
|
import { Page } from '@vben/common-ui';
|
||||||
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
|
||||||
|
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||||
|
import { deleteOpTeamApi, getOpTeamPageApi } from '#/api/ec/op-team';
|
||||||
|
import { PermissionGate } from '#/components/permission';
|
||||||
|
import {
|
||||||
|
syncVxeGridColumns,
|
||||||
|
useActionColumnVisible,
|
||||||
|
} from '#/composables/use-vxe-action-column';
|
||||||
|
|
||||||
|
import OpTeamMemberDrawer from './components/OpTeamMemberDrawer.vue';
|
||||||
|
import OpTeamModal from './components/OpTeamModal.vue';
|
||||||
|
|
||||||
|
defineOptions({ name: 'OpTeamManagement' });
|
||||||
|
|
||||||
|
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const opTeamModalRef = ref();
|
||||||
|
const memberDrawerRef = ref();
|
||||||
|
|
||||||
|
const searchForm = ref({
|
||||||
|
name: '',
|
||||||
|
status: undefined as number | undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const statusOptions = [
|
||||||
|
{ label: '停用', value: 0 },
|
||||||
|
{ label: '启用', value: 1 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const actionCodes = [
|
||||||
|
'ec:op-team:create',
|
||||||
|
'ec:op-team:update',
|
||||||
|
'ec:op-team:delete',
|
||||||
|
];
|
||||||
|
const showActionColumn = useActionColumnVisible(actionCodes);
|
||||||
|
|
||||||
|
const tableBaseColumns: VxeGridProps<OpTeamVO.Info>['columns'] = [
|
||||||
|
{ type: 'seq' as const, minWidth: 'auto', title: '序号' },
|
||||||
|
{
|
||||||
|
field: 'name',
|
||||||
|
title: '团队名称',
|
||||||
|
minWidth: 160,
|
||||||
|
showOverflow: 'tooltip' as const,
|
||||||
|
},
|
||||||
|
{ title: '负责人', minWidth: 120, slots: { default: 'leader' } },
|
||||||
|
{ field: 'memberCount', title: '人数', minWidth: 80 },
|
||||||
|
{
|
||||||
|
field: 'remark',
|
||||||
|
title: '备注',
|
||||||
|
minWidth: 180,
|
||||||
|
showOverflow: 'tooltip' as const,
|
||||||
|
},
|
||||||
|
{ title: '状态', minWidth: 90, slots: { default: 'status' } },
|
||||||
|
{ field: 'createTime', title: '创建时间', minWidth: 180 },
|
||||||
|
];
|
||||||
|
|
||||||
|
const actionColumn: NonNullable<VxeGridProps<OpTeamVO.Info>['columns']>[number] =
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
minWidth: 220,
|
||||||
|
fixed: 'right' as const,
|
||||||
|
slots: { default: 'action' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const tableColumns = computed(() =>
|
||||||
|
showActionColumn.value
|
||||||
|
? [...(tableBaseColumns ?? []), actionColumn]
|
||||||
|
: (tableBaseColumns ?? []),
|
||||||
|
);
|
||||||
|
|
||||||
|
const gridReloadRef = ref<(() => void) | null>(null);
|
||||||
|
|
||||||
|
const formOptions = computed(() => ({
|
||||||
|
schema: [
|
||||||
|
{
|
||||||
|
component: 'Input',
|
||||||
|
componentProps: {
|
||||||
|
placeholder: '请输入团队名称(回车搜索)',
|
||||||
|
allowClear: true,
|
||||||
|
onChange: (e: Event) => {
|
||||||
|
searchForm.value.name = (e.target as HTMLInputElement).value;
|
||||||
|
},
|
||||||
|
onPressEnter: () => gridReloadRef.value?.(),
|
||||||
|
},
|
||||||
|
fieldName: 'name',
|
||||||
|
label: '团队名称',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
component: 'Select',
|
||||||
|
componentProps: {
|
||||||
|
placeholder: '请选择状态',
|
||||||
|
options: statusOptions,
|
||||||
|
allowClear: true,
|
||||||
|
onChange: (val: number | undefined) => {
|
||||||
|
searchForm.value.status = val;
|
||||||
|
gridReloadRef.value?.();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fieldName: 'status',
|
||||||
|
label: '状态',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
showDefaultActions: true,
|
||||||
|
collapsed: true,
|
||||||
|
collapsedRows: 1,
|
||||||
|
handleSubmit: async () => {
|
||||||
|
gridReloadRef.value?.();
|
||||||
|
},
|
||||||
|
handleReset: async () => {
|
||||||
|
searchForm.value = { name: '', status: undefined };
|
||||||
|
gridReloadRef.value?.();
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const gridOptions: VxeGridProps<OpTeamVO.Info> = {
|
||||||
|
columns: tableColumns.value,
|
||||||
|
height: 'auto',
|
||||||
|
border: true,
|
||||||
|
stripe: true,
|
||||||
|
rowConfig: { isHover: true },
|
||||||
|
showOverflow: true,
|
||||||
|
size: 'small',
|
||||||
|
toolbarConfig: {
|
||||||
|
custom: true,
|
||||||
|
refresh: true,
|
||||||
|
zoom: true,
|
||||||
|
},
|
||||||
|
data: [],
|
||||||
|
pagerConfig: {
|
||||||
|
enabled: true,
|
||||||
|
pageSizes: [10, 20, 50, 100],
|
||||||
|
layouts: [
|
||||||
|
'PrevJump',
|
||||||
|
'PrevPage',
|
||||||
|
'Number',
|
||||||
|
'NextPage',
|
||||||
|
'NextJump',
|
||||||
|
'Sizes',
|
||||||
|
'FullJump',
|
||||||
|
'Total',
|
||||||
|
] as (
|
||||||
|
| 'FullJump'
|
||||||
|
| 'NextJump'
|
||||||
|
| 'NextPage'
|
||||||
|
| 'Number'
|
||||||
|
| 'PrevJump'
|
||||||
|
| 'PrevPage'
|
||||||
|
| 'Sizes'
|
||||||
|
| 'Total'
|
||||||
|
)[],
|
||||||
|
},
|
||||||
|
proxyConfig: {
|
||||||
|
ajax: {
|
||||||
|
query: async ({ page }) => {
|
||||||
|
try {
|
||||||
|
loading.value = true;
|
||||||
|
const params: PageQueryDTO<OpTeamDTO.Filters> = {
|
||||||
|
page: page.currentPage,
|
||||||
|
pageSize: page.pageSize,
|
||||||
|
filters: {
|
||||||
|
name: searchForm.value.name || undefined,
|
||||||
|
status: searchForm.value.status,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const data = await getOpTeamPageApi(params);
|
||||||
|
return { items: data.records, total: data.total };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取运营团队列表失败:', error);
|
||||||
|
message.error('获取运营团队列表失败');
|
||||||
|
return { items: [], total: 0 };
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function refreshTable() {
|
||||||
|
gridApi?.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleAdd() {
|
||||||
|
memberDrawerRef.value?.close?.();
|
||||||
|
opTeamModalRef.value?.open(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEdit(row: OpTeamVO.Info) {
|
||||||
|
memberDrawerRef.value?.close?.();
|
||||||
|
opTeamModalRef.value?.open(true, row);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMembers(row: OpTeamVO.Info) {
|
||||||
|
memberDrawerRef.value?.open(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(row: OpTeamVO.Info) {
|
||||||
|
try {
|
||||||
|
await deleteOpTeamApi(row.id);
|
||||||
|
message.success('删除成功');
|
||||||
|
refreshTable();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('删除运营团队失败:', error);
|
||||||
|
message.error('删除运营团队失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const [Grid, gridApi] = useVbenVxeGrid({
|
||||||
|
gridOptions,
|
||||||
|
formOptions: formOptions.value,
|
||||||
|
showSearchForm: true,
|
||||||
|
tableTitle: '运营团队',
|
||||||
|
});
|
||||||
|
gridReloadRef.value = () => gridApi.reload();
|
||||||
|
syncVxeGridColumns(gridApi, tableColumns);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Page title="运营团队" auto-content-height>
|
||||||
|
<template #description>
|
||||||
|
<div class="text-foreground/80 mt-2">
|
||||||
|
管理内部店铺运营团队及成员;后续店铺将按团队收口数据范围
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<Grid :loading="loading">
|
||||||
|
<template #toolbar-tools>
|
||||||
|
<Space>
|
||||||
|
<PermissionGate code="ec:op-team:create">
|
||||||
|
<Button type="primary" @click="handleAdd">
|
||||||
|
<PlusIcon />
|
||||||
|
添加团队
|
||||||
|
</Button>
|
||||||
|
</PermissionGate>
|
||||||
|
</Space>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #leader="{ row }: { row: OpTeamVO.Info }">
|
||||||
|
<span>{{ row.leaderRealName || '—' }}</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template #status="{ row }: { row: OpTeamVO.Info }">
|
||||||
|
<Tag :color="row.status === 1 ? 'green' : 'red'">
|
||||||
|
{{ row.status === 1 ? '启用' : '停用' }}
|
||||||
|
</Tag>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-if="showActionColumn" #action="{ row }: { row: OpTeamVO.Info }">
|
||||||
|
<Space>
|
||||||
|
<PermissionGate code="ec:op-team:read">
|
||||||
|
<Button size="small" @click="handleMembers(row)">成员</Button>
|
||||||
|
</PermissionGate>
|
||||||
|
<PermissionGate code="ec:op-team:update">
|
||||||
|
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||||
|
</PermissionGate>
|
||||||
|
<PermissionGate code="ec:op-team:delete">
|
||||||
|
<Popconfirm
|
||||||
|
title="删除团队将同时移除全部成员,确定删除?"
|
||||||
|
@confirm="handleDelete(row)"
|
||||||
|
>
|
||||||
|
<Button size="small" danger>删除</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</PermissionGate>
|
||||||
|
</Space>
|
||||||
|
</template>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<OpTeamModal ref="opTeamModalRef" @success="refreshTable" />
|
||||||
|
<OpTeamMemberDrawer ref="memberDrawerRef" />
|
||||||
|
</Page>
|
||||||
|
</template>
|
||||||
@@ -1,279 +1,87 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
import type { MenuProps } from 'ant-design-vue';
|
||||||
|
|
||||||
import { computed, reactive, ref } from 'vue';
|
import { computed, onMounted, ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
import { Page } from '@vben/common-ui';
|
||||||
|
import { createIconifyIcon } from '@vben/icons';
|
||||||
|
|
||||||
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
import { Menu } from 'ant-design-vue';
|
||||||
|
|
||||||
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
import ChangePasswordCard from './modules/ChangePasswordCard.vue';
|
||||||
import { FileCategory } from '#/constants/file-category';
|
import ProfileInfoCard from './modules/ProfileInfoCard.vue';
|
||||||
import { uploadFile } from '#/utils/upload-file';
|
|
||||||
|
|
||||||
defineOptions({ name: 'PersonalProfile' });
|
defineOptions({ name: 'PersonalCenter' });
|
||||||
|
|
||||||
|
type TabKey = 'password' | 'profile';
|
||||||
|
|
||||||
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const loading = ref(false);
|
const ProfileIcon = createIconifyIcon('lucide:user');
|
||||||
const submitting = ref(false);
|
const LockIcon = createIconifyIcon('lucide:lock');
|
||||||
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
|
||||||
const avatarLoading = ref(false);
|
|
||||||
|
|
||||||
// 待上传的头像文件(用户选择后先缓存,保存时再上传)
|
const activeTab = ref<TabKey>('profile');
|
||||||
const pendingAvatarFile = ref<File | null>(null);
|
const selectedKeys = computed(() => [activeTab.value]);
|
||||||
|
|
||||||
// 计算属性:头像显示优先级:本地预览 > 已保存的头像 > 初始头像
|
/**
|
||||||
const avatarSrc = computed(() => {
|
* 页内切换只改本地状态,不要改 query。
|
||||||
if (pendingAvatarFile.value) {
|
* tabbar 用 fullPath 做标签 key,带 ?tab= 会开出两个系统标签。
|
||||||
return URL.createObjectURL(pendingAvatarFile.value);
|
*/
|
||||||
|
const onMenuClick: MenuProps['onClick'] = ({ key }) => {
|
||||||
|
activeTab.value = key === 'password' ? 'password' : 'profile';
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
// 兼容 /system/change-password → ?tab=password:读一次后清掉 query
|
||||||
|
if (route.query.tab === 'password') {
|
||||||
|
activeTab.value = 'password';
|
||||||
|
void router.replace({ path: route.path, query: {} });
|
||||||
}
|
}
|
||||||
if (userInfo.value?.avatar) {
|
|
||||||
return userInfo.value.avatar;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 表单数据(与更新接口 DTO 一致,头像 ID 用 undefined 表示未变更/未上传)
|
|
||||||
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
|
||||||
username: '',
|
|
||||||
realName: '',
|
|
||||||
phone: '',
|
|
||||||
remark: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const formRef = ref<any>(null);
|
|
||||||
|
|
||||||
async function fetchUserInfo() {
|
|
||||||
try {
|
|
||||||
loading.value = true;
|
|
||||||
const data = await getUserInfoApi();
|
|
||||||
userInfo.value = data;
|
|
||||||
formData.username = data.username || '';
|
|
||||||
formData.realName = data.realName || '';
|
|
||||||
formData.phone = data.phone || '';
|
|
||||||
formData.remark = data.remark || '';
|
|
||||||
// 重置待上传的头像
|
|
||||||
pendingAvatarFile.value = null;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('获取用户信息失败:', error);
|
|
||||||
message.error('获取用户信息失败');
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleAvatarChange({ file }: { file: any }) {
|
|
||||||
// 获取实际文件对象
|
|
||||||
const actualFile = file.originFileObj || file;
|
|
||||||
if (!actualFile) return;
|
|
||||||
|
|
||||||
if (!actualFile.type.startsWith('image/')) {
|
|
||||||
message.error('只能上传图片文件');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (actualFile.size > 2 * 1024 * 1024) {
|
|
||||||
message.error('图片大小不能超过 2MB');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 缓存头像文件,预览由 computed avatarSrc 自动处理
|
|
||||||
pendingAvatarFile.value = actualFile;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit() {
|
|
||||||
try {
|
|
||||||
await formRef.value?.validate();
|
|
||||||
submitting.value = true;
|
|
||||||
|
|
||||||
// 如果有待上传的头像,先上传
|
|
||||||
if (pendingAvatarFile.value) {
|
|
||||||
avatarLoading.value = true;
|
|
||||||
try {
|
|
||||||
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
|
||||||
category: FileCategory.AVATAR,
|
|
||||||
errorMessage: '头像上传失败',
|
|
||||||
});
|
|
||||||
formData.avatarImageId = fileInfo.id;
|
|
||||||
} finally {
|
|
||||||
avatarLoading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await updateUserInfoApi(formData);
|
|
||||||
message.success('保存成功');
|
|
||||||
formData.avatarImageId = undefined;
|
|
||||||
await fetchUserInfo();
|
|
||||||
} catch (error: any) {
|
|
||||||
if (error?.errorFields) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.error('保存失败:', error);
|
|
||||||
message.error('保存失败');
|
|
||||||
} finally {
|
|
||||||
submitting.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleReset() {
|
|
||||||
if (userInfo.value) {
|
|
||||||
formData.username = userInfo.value.username || '';
|
|
||||||
formData.realName = userInfo.value.realName || '';
|
|
||||||
formData.phone = userInfo.value.phone || '';
|
|
||||||
formData.remark = userInfo.value.remark || '';
|
|
||||||
}
|
|
||||||
formData.avatarImageId = undefined;
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
pendingAvatarFile.value = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchUserInfo();
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Page
|
<Page auto-content-height content-class="flex min-h-0 flex-col">
|
||||||
title="个人信息"
|
|
||||||
auto-content-height
|
|
||||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
|
||||||
>
|
|
||||||
<div class="mx-auto max-w-2xl">
|
|
||||||
<Spin :spinning="loading">
|
|
||||||
<div
|
<div
|
||||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
class="flex min-h-0 flex-1 overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
||||||
>
|
>
|
||||||
<!-- 头部 -->
|
<aside
|
||||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
class="flex w-52 shrink-0 flex-col border-r border-slate-100 bg-slate-50/60 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]"
|
||||||
<div class="flex items-start justify-between gap-3">
|
>
|
||||||
<div>
|
<div
|
||||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
class="border-b border-slate-100 px-4 py-4 text-sm font-medium text-slate-600 dark:border-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
|
>
|
||||||
|
设置
|
||||||
|
</div>
|
||||||
|
<Menu
|
||||||
|
:selected-keys="selectedKeys"
|
||||||
|
mode="inline"
|
||||||
|
class="!border-none !bg-transparent"
|
||||||
|
@click="onMenuClick"
|
||||||
|
>
|
||||||
|
<Menu.Item key="profile">
|
||||||
|
<template #icon>
|
||||||
|
<ProfileIcon class="size-4" />
|
||||||
|
</template>
|
||||||
个人信息
|
个人信息
|
||||||
</h2>
|
</Menu.Item>
|
||||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
<Menu.Item key="password">
|
||||||
编辑您的个人信息和头像
|
<template #icon>
|
||||||
</p>
|
<LockIcon class="size-4" />
|
||||||
</div>
|
</template>
|
||||||
<Button type="link" class="!px-0" @click="router.push('/feedback')">
|
修改密码
|
||||||
意见反馈
|
</Menu.Item>
|
||||||
</Button>
|
</Menu>
|
||||||
</div>
|
</aside>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 表单 -->
|
<div class="min-h-0 min-w-0 flex-1 overflow-y-auto p-6">
|
||||||
<div class="px-8 py-6">
|
<div class="mx-auto max-w-2xl">
|
||||||
<Form
|
<ProfileInfoCard v-if="activeTab === 'profile'" />
|
||||||
ref="formRef"
|
<ChangePasswordCard v-else />
|
||||||
:model="formData"
|
|
||||||
layout="vertical"
|
|
||||||
class="space-y-6"
|
|
||||||
>
|
|
||||||
<!-- 头像 -->
|
|
||||||
<div class="flex items-center">
|
|
||||||
<div class="mr-6">
|
|
||||||
<Upload
|
|
||||||
@change="handleAvatarChange"
|
|
||||||
:show-upload-list="false"
|
|
||||||
accept="image/*"
|
|
||||||
>
|
|
||||||
<div class="relative cursor-pointer">
|
|
||||||
<Spin
|
|
||||||
v-if="avatarLoading"
|
|
||||||
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
|
||||||
/>
|
|
||||||
<img
|
|
||||||
v-if="avatarSrc"
|
|
||||||
:src="avatarSrc"
|
|
||||||
alt="头像"
|
|
||||||
class="h-24 w-24 rounded-full object-cover"
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
v-else
|
|
||||||
class="flex h-24 w-24 items-center justify-center rounded-full bg-slate-200 text-2xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
|
||||||
>
|
|
||||||
{{ userInfo?.realName?.charAt(0) || '?' }}
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
|
||||||
>
|
|
||||||
<span class="text-sm text-white">点击更换</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Upload>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
|
||||||
头像
|
|
||||||
</p>
|
|
||||||
<p class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
|
||||||
点击选择新头像,保存后生效,建议大小不超过 2MB
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 登录用户名(可选,用于账号登录) -->
|
|
||||||
<Form.Item
|
|
||||||
label="登录用户名"
|
|
||||||
name="username"
|
|
||||||
:rules="[
|
|
||||||
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
|
||||||
{
|
|
||||||
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
|
||||||
message: '登录用户名只能包含字母、数字和下划线',
|
|
||||||
},
|
|
||||||
]"
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
v-model:value="formData.username"
|
|
||||||
placeholder="可选,设置后可用账号登录"
|
|
||||||
allow-clear
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 真实姓名 -->
|
|
||||||
<Form.Item
|
|
||||||
label="真实姓名"
|
|
||||||
name="realName"
|
|
||||||
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
|
||||||
>
|
|
||||||
<Input v-model:value="formData.realName" placeholder="请输入真实姓名" />
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 手机号 -->
|
|
||||||
<Form.Item
|
|
||||||
label="手机号"
|
|
||||||
name="phone"
|
|
||||||
:rules="[
|
|
||||||
{ required: true, message: '请输入手机号' },
|
|
||||||
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
|
||||||
]"
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
v-model:value="formData.phone"
|
|
||||||
placeholder="请输入手机号"
|
|
||||||
:maxlength="11"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 备注 -->
|
|
||||||
<Form.Item label="备注" name="remark">
|
|
||||||
<Input.TextArea
|
|
||||||
v-model:value="formData.remark"
|
|
||||||
placeholder="请输入备注"
|
|
||||||
:rows="3"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 底部按钮 -->
|
|
||||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<Button @click="handleReset">重置</Button>
|
|
||||||
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
|
||||||
保存
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Spin>
|
|
||||||
</div>
|
</div>
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { FormItemProps } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { reactive, ref } from 'vue';
|
||||||
|
|
||||||
|
import { Button, Form, Input, message } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { changePasswordApi } from '#/api/core/auth';
|
||||||
|
|
||||||
|
defineOptions({ name: 'ChangePasswordCard' });
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const formRef = ref<any>(null);
|
||||||
|
const formData = reactive({
|
||||||
|
oldPassword: '',
|
||||||
|
newPassword: '',
|
||||||
|
confirmPassword: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 确认密码校验放在 script,避免模板内 Promise 被误解析 */
|
||||||
|
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
||||||
|
{
|
||||||
|
required: true,
|
||||||
|
async validator(_rule: unknown, value: string) {
|
||||||
|
if (!value?.trim()) {
|
||||||
|
throw new Error('请确认密码');
|
||||||
|
}
|
||||||
|
if (value !== formData.newPassword) {
|
||||||
|
throw new Error('两次输入的密码不一致');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
trigger: 'change',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
try {
|
||||||
|
await formRef.value?.validate();
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
await changePasswordApi({
|
||||||
|
oldPassword: formData.oldPassword,
|
||||||
|
newPassword: formData.newPassword,
|
||||||
|
});
|
||||||
|
message.success('密码修改成功');
|
||||||
|
handleReset();
|
||||||
|
} catch (err: any) {
|
||||||
|
message.error(err?.message || '密码修改失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
formRef.value?.resetFields();
|
||||||
|
formData.oldPassword = '';
|
||||||
|
formData.newPassword = '';
|
||||||
|
formData.confirmPassword = '';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="mb-6">
|
||||||
|
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
修改密码
|
||||||
|
</h2>
|
||||||
|
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||||
|
请妥善保管您的新密码
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form ref="formRef" :model="formData" layout="vertical">
|
||||||
|
<Form.Item
|
||||||
|
label="旧密码"
|
||||||
|
name="oldPassword"
|
||||||
|
:rules="[{ required: true, message: '请输入旧密码' }]"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.oldPassword"
|
||||||
|
placeholder="请输入旧密码"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="新密码"
|
||||||
|
name="newPassword"
|
||||||
|
:rules="[
|
||||||
|
{ required: true, message: '请输入新密码' },
|
||||||
|
{ min: 6, max: 20, message: '密码长度为6-20个字符' },
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.newPassword"
|
||||||
|
placeholder="请输入新密码"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="确认密码"
|
||||||
|
name="confirmPassword"
|
||||||
|
:rules="confirmPasswordRules"
|
||||||
|
>
|
||||||
|
<Input.Password
|
||||||
|
v-model:value="formData.confirmPassword"
|
||||||
|
placeholder="请再次输入新密码"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<div class="mt-2 flex justify-end gap-3">
|
||||||
|
<Button @click="handleReset">重置</Button>
|
||||||
|
<Button type="primary" :loading="loading" @click="handleSubmit">
|
||||||
|
确定
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
<script lang="ts" setup>
|
|
||||||
import { reactive, ref } from 'vue';
|
|
||||||
import { useRouter } from 'vue-router';
|
|
||||||
|
|
||||||
import { Page } from '@vben/common-ui';
|
|
||||||
|
|
||||||
import type { FormItemProps } from 'ant-design-vue';
|
|
||||||
|
|
||||||
import { Button, Form, Input, message, Spin } from 'ant-design-vue';
|
|
||||||
|
|
||||||
import { changePasswordApi } from '#/api/core/auth';
|
|
||||||
|
|
||||||
defineOptions({ name: 'ChangePassword' });
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
const loading = ref(false);
|
|
||||||
|
|
||||||
const formRef = ref<any>(null);
|
|
||||||
const formData = reactive({
|
|
||||||
oldPassword: '',
|
|
||||||
newPassword: '',
|
|
||||||
confirmPassword: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
/** 放在 script 中,避免模板内联 validator 里 Promise 被误解析为组件属性 */
|
|
||||||
const confirmPasswordRules: NonNullable<FormItemProps['rules']> = [
|
|
||||||
{
|
|
||||||
required: true,
|
|
||||||
async validator(_rule: unknown, value: string) {
|
|
||||||
if (!value?.trim()) {
|
|
||||||
throw new Error('请确认密码');
|
|
||||||
}
|
|
||||||
if (value !== formData.newPassword) {
|
|
||||||
throw new Error('两次输入的密码不一致');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
trigger: 'change',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
async function handleSubmit() {
|
|
||||||
try {
|
|
||||||
await formRef.value?.validate();
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
loading.value = true;
|
|
||||||
try {
|
|
||||||
await changePasswordApi({
|
|
||||||
oldPassword: formData.oldPassword,
|
|
||||||
newPassword: formData.newPassword,
|
|
||||||
});
|
|
||||||
message.success('密码修改成功');
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
router.push('/system/profile');
|
|
||||||
} catch (err: any) {
|
|
||||||
message.error(err?.message || '密码修改失败');
|
|
||||||
} finally {
|
|
||||||
loading.value = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleReset() {
|
|
||||||
formRef.value?.resetFields();
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<Page
|
|
||||||
title="修改密码"
|
|
||||||
auto-content-height
|
|
||||||
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
|
||||||
>
|
|
||||||
<div class="mx-auto max-w-2xl">
|
|
||||||
<div
|
|
||||||
class="overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
|
|
||||||
>
|
|
||||||
<!-- 头部 -->
|
|
||||||
<div class="border-b border-slate-100 bg-slate-50/50 px-8 py-6 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<h2 class="text-xl font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
|
||||||
修改密码
|
|
||||||
</h2>
|
|
||||||
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
|
||||||
请妥善保管您的新密码
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 表单 -->
|
|
||||||
<div class="px-8 py-6">
|
|
||||||
<Spin :spinning="loading">
|
|
||||||
<Form
|
|
||||||
ref="formRef"
|
|
||||||
:model="formData"
|
|
||||||
layout="vertical"
|
|
||||||
class="space-y-6"
|
|
||||||
>
|
|
||||||
<!-- 旧密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="旧密码"
|
|
||||||
name="oldPassword"
|
|
||||||
:rules="[{ required: true, message: '请输入旧密码' }]"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.oldPassword"
|
|
||||||
placeholder="请输入旧密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 新密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="新密码"
|
|
||||||
name="newPassword"
|
|
||||||
:rules="[{ required: true, message: '请输入新密码' }]"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.newPassword"
|
|
||||||
placeholder="请输入新密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
|
|
||||||
<!-- 确认密码 -->
|
|
||||||
<Form.Item
|
|
||||||
label="确认密码"
|
|
||||||
name="confirmPassword"
|
|
||||||
:rules="confirmPasswordRules"
|
|
||||||
>
|
|
||||||
<Input.Password
|
|
||||||
v-model:value="formData.confirmPassword"
|
|
||||||
placeholder="请再次输入新密码"
|
|
||||||
/>
|
|
||||||
</Form.Item>
|
|
||||||
</Form>
|
|
||||||
</Spin>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 底部按钮 -->
|
|
||||||
<div class="flex justify-end gap-3 border-t border-slate-100 bg-slate-50/50 px-8 py-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]">
|
|
||||||
<Button @click="handleReset">重置</Button>
|
|
||||||
<Button type="primary" :loading="loading" @click="handleSubmit">
|
|
||||||
确定
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Page>
|
|
||||||
</template>
|
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { UserDTO, UserVO } from '#/api/sys/user/types';
|
||||||
|
|
||||||
|
import { computed, reactive, ref } from 'vue';
|
||||||
|
|
||||||
|
import { Button, Form, Input, message, Spin, Upload } from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { getUserInfoApi, updateUserInfoApi } from '#/api/sys/user';
|
||||||
|
import { FileCategory } from '#/constants/file-category';
|
||||||
|
import { useAuthStore } from '#/store';
|
||||||
|
import { uploadFile } from '#/utils/upload-file';
|
||||||
|
|
||||||
|
defineOptions({ name: 'ProfileInfoCard' });
|
||||||
|
|
||||||
|
const authStore = useAuthStore();
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const submitting = ref(false);
|
||||||
|
const userInfo = ref<UserVO.UserInfoVO | null>(null);
|
||||||
|
const avatarLoading = ref(false);
|
||||||
|
const pendingAvatarFile = ref<File | null>(null);
|
||||||
|
|
||||||
|
const avatarSrc = computed(() => {
|
||||||
|
if (pendingAvatarFile.value) {
|
||||||
|
return URL.createObjectURL(pendingAvatarFile.value);
|
||||||
|
}
|
||||||
|
if (userInfo.value?.avatar) {
|
||||||
|
return userInfo.value.avatar;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
|
||||||
|
username: '',
|
||||||
|
realName: '',
|
||||||
|
phone: '',
|
||||||
|
remark: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const formRef = ref<any>(null);
|
||||||
|
|
||||||
|
async function fetchUserInfo() {
|
||||||
|
try {
|
||||||
|
loading.value = true;
|
||||||
|
const data = await getUserInfoApi();
|
||||||
|
userInfo.value = data;
|
||||||
|
formData.username = data.username || '';
|
||||||
|
formData.realName = data.realName || '';
|
||||||
|
formData.phone = data.phone || '';
|
||||||
|
formData.remark = data.remark || '';
|
||||||
|
pendingAvatarFile.value = null;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取用户信息失败:', error);
|
||||||
|
message.error('获取用户信息失败');
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleAvatarChange({ file }: { file: any }) {
|
||||||
|
const actualFile = file.originFileObj || file;
|
||||||
|
if (!actualFile) return;
|
||||||
|
|
||||||
|
if (!actualFile.type.startsWith('image/')) {
|
||||||
|
message.error('只能上传图片文件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (actualFile.size > 2 * 1024 * 1024) {
|
||||||
|
message.error('图片大小不能超过 2MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pendingAvatarFile.value = actualFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
try {
|
||||||
|
await formRef.value?.validate();
|
||||||
|
submitting.value = true;
|
||||||
|
|
||||||
|
if (pendingAvatarFile.value) {
|
||||||
|
avatarLoading.value = true;
|
||||||
|
try {
|
||||||
|
const fileInfo = await uploadFile(pendingAvatarFile.value, {
|
||||||
|
category: FileCategory.AVATAR,
|
||||||
|
errorMessage: '头像上传失败',
|
||||||
|
});
|
||||||
|
formData.avatarImageId = fileInfo.id;
|
||||||
|
} finally {
|
||||||
|
avatarLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await updateUserInfoApi(formData);
|
||||||
|
message.success('保存成功');
|
||||||
|
formData.avatarImageId = undefined;
|
||||||
|
await fetchUserInfo();
|
||||||
|
await authStore.fetchUserInfo();
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error?.errorFields) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.error('保存失败:', error);
|
||||||
|
message.error('保存失败');
|
||||||
|
} finally {
|
||||||
|
submitting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleReset() {
|
||||||
|
if (userInfo.value) {
|
||||||
|
formData.username = userInfo.value.username || '';
|
||||||
|
formData.realName = userInfo.value.realName || '';
|
||||||
|
formData.phone = userInfo.value.phone || '';
|
||||||
|
formData.remark = userInfo.value.remark || '';
|
||||||
|
}
|
||||||
|
formData.avatarImageId = undefined;
|
||||||
|
formRef.value?.resetFields();
|
||||||
|
pendingAvatarFile.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchUserInfo();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="mb-6">
|
||||||
|
<h2 class="text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
个人信息
|
||||||
|
</h2>
|
||||||
|
<p class="mt-1 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
|
||||||
|
编辑头像、登录用户名与联系方式
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Spin :spinning="loading">
|
||||||
|
<Form ref="formRef" :model="formData" layout="vertical">
|
||||||
|
<div class="mb-6 flex items-center">
|
||||||
|
<div class="mr-5">
|
||||||
|
<Upload
|
||||||
|
accept="image/*"
|
||||||
|
:show-upload-list="false"
|
||||||
|
@change="handleAvatarChange"
|
||||||
|
>
|
||||||
|
<div class="relative cursor-pointer">
|
||||||
|
<Spin
|
||||||
|
v-if="avatarLoading"
|
||||||
|
class="absolute inset-0 z-10 flex items-center justify-center bg-white/80"
|
||||||
|
/>
|
||||||
|
<img
|
||||||
|
v-if="avatarSrc"
|
||||||
|
:src="avatarSrc"
|
||||||
|
alt="头像"
|
||||||
|
class="h-20 w-20 rounded-full object-cover"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="flex h-20 w-20 items-center justify-center rounded-full bg-slate-200 text-xl text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
|
>
|
||||||
|
{{ userInfo?.realName?.charAt(0) || '?' }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity hover:opacity-100"
|
||||||
|
>
|
||||||
|
<span class="text-xs text-white">更换</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Upload>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="font-medium text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
|
||||||
|
头像
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
class="mt-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||||
|
>
|
||||||
|
点击更换,保存后生效,不超过 2MB
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="登录用户名"
|
||||||
|
name="username"
|
||||||
|
:rules="[
|
||||||
|
{ min: 3, max: 20, message: '登录用户名长度为3-20个字符' },
|
||||||
|
{
|
||||||
|
pattern: /^$|^[a-zA-Z0-9_]+$/,
|
||||||
|
message: '登录用户名只能包含字母、数字和下划线',
|
||||||
|
},
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.username"
|
||||||
|
allow-clear
|
||||||
|
placeholder="可选,设置后可用账号登录"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="真实姓名"
|
||||||
|
name="realName"
|
||||||
|
:rules="[{ required: true, message: '请输入真实姓名' }]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.realName"
|
||||||
|
placeholder="请输入真实姓名"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item
|
||||||
|
label="手机号"
|
||||||
|
name="phone"
|
||||||
|
:rules="[
|
||||||
|
{ required: true, message: '请输入手机号' },
|
||||||
|
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<Input
|
||||||
|
v-model:value="formData.phone"
|
||||||
|
:maxlength="11"
|
||||||
|
placeholder="请输入手机号"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
|
||||||
|
<Form.Item label="备注" name="remark">
|
||||||
|
<Input.TextArea
|
||||||
|
v-model:value="formData.remark"
|
||||||
|
:rows="3"
|
||||||
|
placeholder="请输入备注"
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Spin>
|
||||||
|
|
||||||
|
<div class="mt-2 flex justify-end gap-3">
|
||||||
|
<Button @click="handleReset">重置</Button>
|
||||||
|
<Button type="primary" :loading="submitting" @click="handleSubmit">
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts';
|
import {
|
||||||
|
BarChart,
|
||||||
|
LineChart,
|
||||||
|
MapChart,
|
||||||
|
PieChart,
|
||||||
|
RadarChart,
|
||||||
|
} from 'echarts/charts';
|
||||||
import {
|
import {
|
||||||
DatasetComponent,
|
DatasetComponent,
|
||||||
DataZoomComponent,
|
DataZoomComponent,
|
||||||
|
GeoComponent,
|
||||||
GridComponent,
|
GridComponent,
|
||||||
LegendComponent,
|
LegendComponent,
|
||||||
TitleComponent,
|
TitleComponent,
|
||||||
ToolboxComponent,
|
ToolboxComponent,
|
||||||
TooltipComponent,
|
TooltipComponent,
|
||||||
TransformComponent,
|
TransformComponent,
|
||||||
|
VisualMapComponent,
|
||||||
} from 'echarts/components';
|
} from 'echarts/components';
|
||||||
import * as echarts from 'echarts/core';
|
import * as echarts from 'echarts/core';
|
||||||
import {
|
import {
|
||||||
@@ -21,8 +29,11 @@ echarts.use([
|
|||||||
TitleComponent,
|
TitleComponent,
|
||||||
PieChart,
|
PieChart,
|
||||||
RadarChart,
|
RadarChart,
|
||||||
|
MapChart,
|
||||||
TooltipComponent,
|
TooltipComponent,
|
||||||
GridComponent,
|
GridComponent,
|
||||||
|
GeoComponent,
|
||||||
|
VisualMapComponent,
|
||||||
DataZoomComponent,
|
DataZoomComponent,
|
||||||
DatasetComponent,
|
DatasetComponent,
|
||||||
TransformComponent,
|
TransformComponent,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from './echarts';
|
export * from './echarts';
|
||||||
|
export { default as echarts } from './echarts';
|
||||||
export { default as EchartsUI } from './echarts-ui.vue';
|
export { default as EchartsUI } from './echarts-ui.vue';
|
||||||
export * from './types';
|
export * from './types';
|
||||||
export * from './use-echarts';
|
export * from './use-echarts';
|
||||||
|
|||||||
Reference in New Issue
Block a user