mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:59:19 +08:00
Compare commits
31
Commits
master
..
7fa0729722
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fa0729722 | ||
|
|
aa87168437 | ||
|
|
e5050317ec | ||
|
|
68ef451ab3 | ||
|
|
3c16d538e0 | ||
|
|
650d3910ba | ||
|
|
4c340ce805 | ||
|
|
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` | 会话滚动摘要(可选) |
|
||||
| `llm_provider_id` | 会话选用的提供商 id |
|
||||
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
||||
| `llm_response_chain` | 可选;Responses 续链 `{provider_id,model,previous_response_id}` |
|
||||
| `created_at`, `updated_at`, `last_message_at` | |
|
||||
|
||||
唯一索引:`(company_id, user_id, thread_id)`
|
||||
@@ -225,6 +226,7 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model
|
||||
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
||||
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
||||
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
||||
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
|
||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
||||
| 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 约定。
|
||||
|
||||
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
|
||||
健康检查:`GET http://localhost:8200/health`
|
||||
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,
|
||||
MongoSessionRepository,
|
||||
)
|
||||
from infrastructure.persistence.redis.cache import RedisLlmRuntimeCache, get_redis
|
||||
from infrastructure.persistence.redis.cache import (
|
||||
RedisLlmProtocolCapabilityCache,
|
||||
RedisLlmRuntimeCache,
|
||||
get_redis,
|
||||
)
|
||||
|
||||
|
||||
async def current_actor(
|
||||
@@ -46,7 +50,11 @@ async def session_service(
|
||||
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
||||
) -> SessionService:
|
||||
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:
|
||||
@@ -68,5 +76,8 @@ async def chat_service(
|
||||
messages=MongoMessageRepository(db),
|
||||
llm_runtime=llm_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:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
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.system_prompt import build_system_prompt
|
||||
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
|
||||
|
||||
|
||||
@@ -63,7 +69,6 @@ class ChatService:
|
||||
provider_id=session.llm_provider_id,
|
||||
model=session.llm_model,
|
||||
)
|
||||
# 回落默认或消歧后写回会话,保证列表/选框稳定
|
||||
changed = False
|
||||
if session.llm_model != llm.model:
|
||||
session.llm_model = llm.model
|
||||
@@ -72,6 +77,13 @@ class ChatService:
|
||||
session.llm_provider_id = llm.provider_id
|
||||
changed = True
|
||||
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)
|
||||
|
||||
just_saved = None
|
||||
@@ -120,7 +132,6 @@ class ChatService:
|
||||
reserve_output_tokens=self._settings.context_reserve_output_tokens,
|
||||
reserve_tool_tokens=self._settings.context_reserve_tool_tokens,
|
||||
)
|
||||
# 本轮 tool 结果字符上限(与预留 tool token 粗对齐)
|
||||
max_tool_chars = max(
|
||||
500, self._settings.context_reserve_tool_tokens * 2
|
||||
)
|
||||
@@ -142,6 +153,7 @@ class ChatService:
|
||||
await self._session_repo.update(session)
|
||||
|
||||
parts: list[str] = []
|
||||
new_response_id: str | None = None
|
||||
async for event in self._streamer.stream_reply(
|
||||
llm=llm,
|
||||
history=history,
|
||||
@@ -149,7 +161,11 @@ class ChatService:
|
||||
system_prompt=system_prompt,
|
||||
tools=tools or None,
|
||||
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:
|
||||
parts.append(event.text)
|
||||
yield event
|
||||
@@ -167,4 +183,26 @@ class ChatService:
|
||||
)
|
||||
)
|
||||
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)
|
||||
|
||||
|
||||
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,
|
||||
provider_id=None,
|
||||
context_window=None,
|
||||
api_style="auto",
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import datetime
|
||||
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from domain.models import Actor, Session, SessionStatus
|
||||
from domain.ports import SessionRepository
|
||||
from domain.ports import MessageRepository, SessionRepository
|
||||
|
||||
|
||||
class SessionService:
|
||||
@@ -15,9 +15,11 @@ class SessionService:
|
||||
self,
|
||||
sessions: SessionRepository,
|
||||
llm_runtime: LlmRuntimeService | None = None,
|
||||
messages: MessageRepository | None = None,
|
||||
) -> None:
|
||||
self._sessions = sessions
|
||||
self._llm_runtime = llm_runtime
|
||||
self._messages = messages
|
||||
|
||||
async def create(
|
||||
self,
|
||||
@@ -103,11 +105,31 @@ class SessionService:
|
||||
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
||||
raise ValueError("提供商不能为空")
|
||||
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_model = model
|
||||
if switched:
|
||||
# 切换选型后厂商侧链不可复用
|
||||
session.llm_response_chain = None
|
||||
return await self._sessions.update(session)
|
||||
|
||||
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.status = SessionStatus.ARCHIVED
|
||||
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、字段名、更新时间或表格。"
|
||||
"问「有哪些记忆」:有则直接列举命中摘要,无则一句「暂时没有相关记忆」;"
|
||||
"不必强调「就这一条」,未问勿主动建议再记店铺/商品/口径。"
|
||||
|
||||
@@ -77,6 +77,8 @@ class Settings(BaseSettings):
|
||||
# 为模型输出与本轮 tool 预留的 token
|
||||
context_reserve_output_tokens: int = 4096
|
||||
context_reserve_tool_tokens: int = 8192
|
||||
# Responses/store 能力缓存 TTL(秒)
|
||||
llm_capability_ttl_seconds: int = 604800
|
||||
|
||||
@property
|
||||
def cors_origin_list(self) -> list[str]:
|
||||
|
||||
@@ -50,6 +50,15 @@ class Actor:
|
||||
return role in {"owner", "admin"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class LlmResponseChain:
|
||||
"""同提供商同模型下的 Responses 续链缓存(非真相源;失效则 Mongo rebuild)。"""
|
||||
|
||||
provider_id: int | None
|
||||
model: str
|
||||
previous_response_id: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
thread_id: str
|
||||
@@ -65,6 +74,8 @@ class Session:
|
||||
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||
llm_provider_id: int | None = None
|
||||
llm_model: str | None = None
|
||||
# Responses 续链;切换选型或链失效时清空
|
||||
llm_response_chain: LlmResponseChain | None = None
|
||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||
last_message_at: datetime | None = None
|
||||
@@ -118,19 +129,31 @@ class LlmRuntimeConfig:
|
||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
||||
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)
|
||||
class StreamEvent:
|
||||
"""流式片段:正文 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
|
||||
phase: str | None = None # start | end
|
||||
name: str | None = None
|
||||
label: str | None = None
|
||||
tool_call_id: str | None = None
|
||||
args: dict | None = None
|
||||
# Responses 本轮最终 response id(仅 kind=response_chain)
|
||||
response_id: str | None = None
|
||||
|
||||
@staticmethod
|
||||
def token(text: str) -> StreamEvent:
|
||||
@@ -159,3 +182,8 @@ class StreamEvent:
|
||||
@staticmethod
|
||||
def pending_client_tools() -> StreamEvent:
|
||||
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 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):
|
||||
@@ -51,6 +58,13 @@ class MessageRepository(ABC):
|
||||
@abstractmethod
|
||||
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):
|
||||
@abstractmethod
|
||||
@@ -111,6 +125,25 @@ class LlmRuntimeGateway(ABC):
|
||||
) -> 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):
|
||||
"""流式生成助手回复。"""
|
||||
|
||||
@@ -124,4 +157,5 @@ class ChatStreamer(ABC):
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 4000,
|
||||
previous_response_id: str | None = None,
|
||||
) -> 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
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
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.publish_ui import is_client_tool_name
|
||||
from domain.models import ChatMessage, LlmRuntimeConfig, MessageRole, StreamEvent
|
||||
from domain.ports import ChatStreamer
|
||||
from domain.models import (
|
||||
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):
|
||||
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(
|
||||
self,
|
||||
*,
|
||||
@@ -24,40 +54,331 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
system_prompt: str,
|
||||
tools: list[Any] | None = None,
|
||||
max_tool_result_chars: int = 8000,
|
||||
previous_response_id: str | None = None,
|
||||
) -> AsyncIterator[StreamEvent]:
|
||||
model = ChatOpenAI(
|
||||
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,
|
||||
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)
|
||||
)
|
||||
messages: list[Any] = [SystemMessage(content=system_prompt)]
|
||||
for m in history:
|
||||
if m.role == MessageRole.USER:
|
||||
messages.append(HumanMessage(content=m.content))
|
||||
elif m.role == MessageRole.ASSISTANT:
|
||||
messages.append(AIMessage(content=m.content))
|
||||
messages.append(HumanMessage(content=user_text))
|
||||
|
||||
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(
|
||||
api_key=llm.api_key,
|
||||
base_url=llm.base_url,
|
||||
model=llm.model,
|
||||
temperature=0,
|
||||
streaming=False,
|
||||
default_headers=llm.extra_headers or None,
|
||||
use_responses_api=True,
|
||||
output_version="responses/v1",
|
||||
store=True,
|
||||
use_previous_response_id=True,
|
||||
)
|
||||
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:
|
||||
if m.role == MessageRole.USER:
|
||||
messages.append(HumanMessage(content=m.content))
|
||||
elif m.role == MessageRole.ASSISTANT:
|
||||
messages.append(AIMessage(content=m.content))
|
||||
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:
|
||||
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)
|
||||
if text:
|
||||
yield StreamEvent.token(text)
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
# 工具轮:每轮用 astream 边生成边推 token;出现 tool_call 再执行工具后继续
|
||||
bound = model.bind_tools(tools)
|
||||
tool_map = {t.name: t for t in tools if getattr(t, "name", None)}
|
||||
tool_cap = max(500, max_tool_result_chars)
|
||||
for _ in range(5):
|
||||
for round_idx in range(5):
|
||||
gathered = None
|
||||
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
|
||||
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
|
||||
continue
|
||||
if saw_tool:
|
||||
@@ -65,12 +386,19 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
text = _chunk_text(getattr(chunk, "content", None))
|
||||
if text:
|
||||
yield StreamEvent.token(text)
|
||||
|
||||
if gathered is None:
|
||||
yield StreamEvent.token("(模型未返回内容)")
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
last_response_id = _response_id_of(gathered) or last_response_id
|
||||
messages.append(gathered)
|
||||
tool_calls = getattr(gathered, "tool_calls", None) or []
|
||||
if not tool_calls:
|
||||
if use_store and last_response_id:
|
||||
yield StreamEvent.response_chain(last_response_id)
|
||||
return
|
||||
|
||||
seen: set[str] = set()
|
||||
@@ -121,19 +449,44 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
)
|
||||
|
||||
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:
|
||||
"""兼容 Completions 字符串与 Responses 结构化 content 块。"""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
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")
|
||||
if t:
|
||||
parts.append(str(t))
|
||||
elif isinstance(part, str):
|
||||
parts.append(part)
|
||||
return "".join(parts)
|
||||
return ""
|
||||
|
||||
@@ -9,6 +9,7 @@ import httpx
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmRuntimeConfig
|
||||
from domain.ports import LlmRuntimeGateway
|
||||
from infrastructure.llm.api_style import normalize_api_style
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -53,6 +54,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
for k, v in (data.get("extraHeaders") or {}).items()
|
||||
},
|
||||
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:
|
||||
logger.exception(
|
||||
|
||||
@@ -11,6 +11,7 @@ from motor.motor_asyncio import AsyncIOMotorDatabase
|
||||
|
||||
from domain.models import (
|
||||
ChatMessage,
|
||||
LlmResponseChain,
|
||||
MemoryKind,
|
||||
MemoryStatus,
|
||||
MessageRole,
|
||||
@@ -36,6 +37,30 @@ def _optional_int(v: Any) -> int | 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):
|
||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||
self._col = db.agent_sessions
|
||||
@@ -52,6 +77,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"created_at": session.created_at,
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
@@ -135,6 +161,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"scene_ref": session.scene_ref,
|
||||
"llm_provider_id": session.llm_provider_id,
|
||||
"llm_model": session.llm_model,
|
||||
"llm_response_chain": _chain_to_doc(session.llm_response_chain),
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
}
|
||||
@@ -155,6 +182,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
scene_ref=doc.get("scene_ref"),
|
||||
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||
llm_model=doc.get("llm_model"),
|
||||
llm_response_chain=_chain_from_doc(doc.get("llm_response_chain")),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
updated_at=_dt(doc.get("updated_at")),
|
||||
last_message_at=doc.get("last_message_at"),
|
||||
@@ -194,7 +222,17 @@ class MongoMessageRepository(MessageRepository):
|
||||
) -> list[ChatMessage]:
|
||||
cursor = (
|
||||
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)
|
||||
.limit(limit)
|
||||
@@ -203,6 +241,24 @@ class MongoMessageRepository(MessageRepository):
|
||||
rows.reverse()
|
||||
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
|
||||
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
||||
return ChatMessage(
|
||||
|
||||
@@ -7,8 +7,9 @@ import json
|
||||
import redis.asyncio as redis
|
||||
|
||||
from config.settings import Settings
|
||||
from domain.models import LlmRuntimeConfig
|
||||
from domain.ports import LlmRuntimeCache
|
||||
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
|
||||
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
|
||||
from infrastructure.llm.api_style import normalize_api_style
|
||||
|
||||
|
||||
class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
@@ -43,6 +44,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
||||
extra_headers=data.get("extra_headers") or {},
|
||||
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:
|
||||
return None
|
||||
@@ -63,6 +65,7 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
"model": config.model,
|
||||
"extra_headers": config.extra_headers,
|
||||
"context_window": config.context_window,
|
||||
"api_style": normalize_api_style(config.api_style),
|
||||
}
|
||||
await self._r.set(
|
||||
self._key(company_id, config.provider_id, config.model),
|
||||
@@ -96,6 +99,53 @@ def get_redis(settings: Settings) -> redis.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:
|
||||
global _redis
|
||||
if _redis is not None:
|
||||
|
||||
@@ -8,7 +8,7 @@ motor>=3.6.0
|
||||
redis>=5.2.0
|
||||
httpx>=0.27.0
|
||||
langchain-core>=0.3.0
|
||||
langchain-openai>=0.2.0
|
||||
langchain-openai>=0.3.26
|
||||
langchain-mcp-adapters>=0.1.0
|
||||
langgraph>=0.2.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
|
||||
Binary file not shown.
@@ -0,0 +1,364 @@
|
||||
API文档/商品API/pdd.goods.cat.rule.get
|
||||
|
||||
# pdd.goods.cat.rule.get
|
||||
|
||||
## 类目商品发布规则查询接口
|
||||
|
||||
更新时间:2026-05-12 20:45:43
|
||||
|
||||
¥免费API
|
||||
|
||||
必须用户授权
|
||||
|
||||
通过叶子类目id获取该类目的发布规则,目前返回标品、商品服务、属性等规则。
|
||||
|
||||
### 公共参数
|
||||
|
||||
#### 请求地址(目前只提供正式环境,暂无沙箱环境)
|
||||
|
||||
| 环境 | HTTP地址 | HTTPS地址 |
|
||||
| --- | --- | --- |
|
||||
| 正式环境 | http://gw-api.pinduoduo.com/api/router | https://gw-api.pinduoduo.com/api/router |
|
||||
|
||||
#### 公共请求参数
|
||||
|
||||
| 参数名称 | 参数类型 | 是否必填 | 参数描述 |
|
||||
| --- | --- | --- | --- |
|
||||
| type | String | 必填 | API接口名称 |
|
||||
| client\_id | String | 必填 | POP分配给应用的client\_id |
|
||||
| access\_token | String | 非必填 | 通过code获取的access\_token |
|
||||
| timestamp | String | 必填 | UNIX时间戳,单位秒,需要与拼多多服务器时间差值在10分钟内 |
|
||||
| data\_type | String | 非必填 | 响应格式,即返回数据的格式,JSON或者XML(二选一),默认JSON,注意是大写 |
|
||||
| version | String | 非必填 | API协议版本号,默认为V1,可不填 |
|
||||
| sign | String | 必填 | API输入参数签名结果,签名算法参考开放平台接入指南第三部分底部。 |
|
||||
|
||||
### 请求参数说明
|
||||
|
||||
| 参数接口 | 参数类型 | 是否必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| cat\_id | LONG | 必填 | 类目id |
|
||||
| goods\_id | LONG | 非必填 | 商品id,编辑的时候需要传被编辑的商品id,发布商品时如果已有商品id也需要传 |
|
||||
| goods\_properties | OBJECT\[\] | 非必填 | 商品属性列表 |
|
||||
| group\_id | INTEGER | 非必填 | 属性值分组ID,非销售属性不用传 |
|
||||
| img\_url | STRING | 非必填 | 图片url,非销售属性不用传 |
|
||||
| note | STRING | 非必填 | 备注,非销售属性不用传 |
|
||||
| parent\_spec\_id | LONG | 非必填 | 父规格ID,非销售属性不用传 |
|
||||
| ref\_pid | LONG | 非必填 | LONG |
|
||||
| spec\_id | LONG | 非必填 | 规格ID,非销售属性不用传 |
|
||||
| table\_info | OBJECT | 非必填 | 成分表表单信息 |
|
||||
| table\_value\_list | OBJECT\[\] | 非必填 | 表单内容列表 |
|
||||
| column\_type | INTEGER | 非必填 | 列类型 1-材质成分百分比 |
|
||||
| unit | STRING | 非必填 | 表单单位,材质成分表时为:% |
|
||||
| value | STRING | 非必填 | 表单值,材质成分表时为:占比百分值 |
|
||||
| template\_pid | LONG | 非必填 | 模板属性id |
|
||||
| value | STRING | 非必填 | 属性值 |
|
||||
| value\_unit | STRING | 非必填 | 属性单位 |
|
||||
| vid | LONG | 非必填 | 属性值id |
|
||||
|
||||
### 返回参数说明
|
||||
|
||||
| 参数接口 | 参数类型 | 例子 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| cat\_rule\_get\_response | OBJECT | | 类目规则 |
|
||||
| goods\_properties\_rule | OBJECT | | 商品属性规则 |
|
||||
| choose\_all\_qualify\_spec | BOOLEAN | true | 多个销售属性是否需要同时传 |
|
||||
| input\_max\_spec\_num | LONG | 1 | 允许自定义的销售属性数量 |
|
||||
| properties | OBJECT\[\] | | 属性信息 |
|
||||
| can\_note | BOOLEAN | true | 是否允许填写备注,仅当是销售属性时有意义 |
|
||||
| choose\_max\_num | INTEGER | 1 | 可选择属性值数目,为0时代表不限。包括自定义的属性值和模版中给出的属性值。 |
|
||||
| input\_max\_num | INTEGER | 0 | 可自定义属性值数目,为0时代表不可自定义。 |
|
||||
| is\_important | BOOLEAN | true | 是否重要属性。填写重要属性有更多机会获取搜索、活动等场景流量。 |
|
||||
| is\_sale | BOOLEAN | true | 是否销售属性。销售属性需要在发商品时,商品属性上的属性值与规格中中的spec对应。 |
|
||||
| is\_sku | BOOLEAN | false | 是否sku属性,sku维度的属性在商品发布时入参在sku对象下 |
|
||||
| max\_value | STRING | 10 | 最大值。在不同的属性值类型下有不同的含义。 文本类型时,代表文本最大长度; 数值类型时,代表数字最大值; 时间类型且最大值为时间时,代表时间最大值; 时间类型且最大值为数字时,代表距离今天或者本月往后的天数或月数。 |
|
||||
| min\_value | STRING | 1 | 最小值。在不同的属性值类型下有不同的含义。 文本类型时,代表文本最小长度; 数值类型时,代表数字最小值; 时间类型且最小值为时间时,代表时间最小值; 时间类型且最小值为数字时,代表距离今天或者本月往前的天数或月数。 |
|
||||
| name | STRING | 品牌 | 属性名称 |
|
||||
| parent\_spec\_id | LONG | 111111 | 销售属性对应的父规格id。 |
|
||||
| property\_value\_type | INTEGER | 0 | 属性值类型。在发商品时传自定义的属性值时,有不同的格式。 0=文本; 1=数值,如“100”; 2=数值范围,如“10,20”,表示10到20之间; 3=数值乘积-二维,如“10,10”,表示10\*10; 4=数值乘积-三维,如“10,10,10”,表示10\*10\*10; 5=单项时间选择-年月日,如“2020-05-20”; 6=双项时间选择-年月日,如“2020-05-20,2020-06-20”; 7=单项时间选择-年月,如“2020-05”; 8=双项时间选择-年月,如“2020-05,2020-06”;9=材质成分表,支持补充材质百分比,在table\_info字段。 |
|
||||
| ref\_pid | LONG | 310 | 属性id |
|
||||
| required | BOOLEAN | true | 是否必填 |
|
||||
| required\_rule | STRING | | 必填规则具体内容,当required=true且required\_rule\_type=1时该字段有效,表示当出现哪些属性/属性值时,该属性需要必填,json格式,两层List结构,外层list代表"或"关系,内层list代表"且"关系,例如:\[\[{\\"ref\_pid\\":123,\\"vid\\":123}\]\] |
|
||||
| required\_rule\_type | INTEGER | 0 | required=true时,该字段有效,为“0”时表示当前属性必填,不受其他属性影响,为“1”时表示当前属性是否必填由已填写的其他属性值决定 |
|
||||
| show\_condition | OBJECT\[\] | | 该属性的父属性。只有parent\_pid下的show\_vids中的值被选择时才可入参该属性。有多组父属性时,为且的关系。 |
|
||||
| parent\_ref\_pid | LONG | 1111 | 父属性id。 |
|
||||
| parent\_vids | LONG\[\] | | 父属性值id。多个值任选其一即可。若为空表示任意值都可以。 |
|
||||
| value\_precision | INTEGER | 0 | 小数点允许最大精度,为0时代表不允许输入小数。对数值类属性值限制。 |
|
||||
| value\_unit | STRING\[\] | | 可选属性值单位,发商品填写自定义数值属性值时,选择其中之一作为单位。 |
|
||||
| values | OBJECT\[\] | | 属性值列表 |
|
||||
| extend\_info | STRING | (255,255,255,1) | 扩展信息,表示颜色的色号。格式为ARGB |
|
||||
| group | OBJECT | | 分组信息 |
|
||||
| id | INTEGER | 1 | 组id |
|
||||
| name | STRING | 红色系 | 组名称 |
|
||||
| parent\_vids | LONG\[\] | | 表示对应父属性值id。当其中父属性值被选中时该子属性值才可选。为空则表示无此限制。 |
|
||||
| spec\_id | LONG | 1122 | 规格id,发商品时需要和sku上的spec对应。 |
|
||||
| value | STRING | aaa | 属性值 |
|
||||
| vid | LONG | 1111 | 基础属性值id |
|
||||
| goods\_service\_rule | OBJECT | | 商品服务规则 |
|
||||
| goods\_service\_rule\_map | MAP | | |
|
||||
| $key | STRING | | 商品类型 |
|
||||
| $value | OBJECT | | |
|
||||
| bad\_claim\_rule | INTEGER | | 坏了包赔规则:0不可选、1可选、2必选 |
|
||||
| can\_select\_delivery\_type | BOOLEAN | | 是否可以选择物流方式 |
|
||||
| delivery\_one\_day\_rule | INTEGER | | 当日发货规则:0不可选、1可选 |
|
||||
| folt\_rule | INTEGER | | 假一赔十规则:0不可选、1可选、2必选 |
|
||||
| lack\_of\_weight\_claim\_rule | INTEGER | | 缺重包退规则:0不可选、1可选、2必选 |
|
||||
| need\_upload\_package\_label | BOOLEAN | | 可以上传包装标签图 |
|
||||
| need\_upload\_package\_label\_required | BOOLEAN | | 是否必填包装标签图 |
|
||||
| need\_upload\_package\_label\_type | INTEGER | | 包装标签图类型:1化妆品、2食品、3农药、4安全帽、5调压阀、6玩具 |
|
||||
| privacy\_delivery\_rule | INTEGER | | 保密发货:0不可选、1可选 |
|
||||
| quan\_guo\_lian\_bao\_rule | INTEGER | | 全国联保规则:0不可选、1可选 |
|
||||
| refundable\_rule | INTEGER | | 7天无理由退换货规则:0不可选、1可选、2必选 |
|
||||
| rule\_related\_ref\_pid\_map | MAP | | 规则相关属性,变更时需重新调用rule接口 |
|
||||
| $key | STRING | | 规则相关属性场景枚举值。1、packageLabelImg包装标签图 |
|
||||
| $value | LONG\[\] | | 属性id |
|
||||
| shipment\_limit\_second\_list | INTEGER\[\] | | 可选承诺发货时间列表,单位:秒 |
|
||||
| zhi\_huan\_bu\_xiu\_rule | INTEGER | | 只换不修规则:0不可选、1可选 |
|
||||
| goods\_type\_list | INTEGER\[\] | | 可选的商品类型列表 |
|
||||
| goods\_sku\_rule | OBJECT | | sku规则 |
|
||||
| price\_range\_ratio | DOUBLE | | 团购价最高差倍率 |
|
||||
| spec\_num\_limit | INTEGER | | 同个商品下规格值的加和数量上限 |
|
||||
| spu\_rule | OBJECT | | 标品规则 |
|
||||
| control\_type | INTEGER | | 标品管控类型。0=不管控;1=管控,表示商品发布时必须命中标品,且发布成功后不可更改关键属性;2=不可换品,表示发布成功后不可更改关键属性。 |
|
||||
| key\_prop | OBJECT\[\] | | 关键属性 |
|
||||
| pname | STRING | | 关键属性名 |
|
||||
| ref\_pid | LONG | | 关键属性id |
|
||||
| two\_pieces\_discount\_rule | OBJECT | | 满2件折扣相关规则 |
|
||||
| if\_must\_two\_pieces\_discount | BOOLEAN | | 是否必须设置 |
|
||||
| max\_two\_pieces\_discount | INTEGER | | 允许的最大折扣 |
|
||||
| min\_two\_pieces\_discount | INTEGER | | 允许的最小折扣 |
|
||||
| recommend\_two\_pieces\_discount | INTEGER | | 推荐的折扣 |
|
||||
|
||||
### 请求示例
|
||||
|
||||
JAVA
|
||||
|
||||
CURL
|
||||
|
||||
```
|
||||
package com.pdd.pop.sdk.http.demo;
|
||||
|
||||
import com.pdd.pop.sdk.common.util.JsonUtil;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatRuleGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsCatRuleGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatRuleGetRequest.GoodsPropertiesItem;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatRuleGetRequest.GoodsPropertiesItemTableInfo;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatRuleGetRequest.GoodsPropertiesItemTableInfoTableValueListItem;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class PopClientDemo {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String clientId = "your clientId";
|
||||
String clientSecret = "your clientSecret";
|
||||
String accessToken = "your accessToken";
|
||||
PopClient client = new PopHttpClient(clientId, clientSecret);
|
||||
|
||||
PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
|
||||
request.setCatId(123L);
|
||||
request.setGoodsId(123123L);
|
||||
List<GoodsPropertiesItem> goodsProperties = new ArrayList<GoodsPropertiesItem>();
|
||||
|
||||
GoodsPropertiesItem item = new GoodsPropertiesItem();
|
||||
item.setGroupId(0);
|
||||
item.setImgUrl("str");
|
||||
item.setNote("str");
|
||||
item.setParentSpecId(0L);
|
||||
item.setRefPid(0L);
|
||||
item.setSpecId(0L);
|
||||
|
||||
GoodsPropertiesItemTableInfo tableInfo = new GoodsPropertiesItemTableInfo();
|
||||
List<GoodsPropertiesItemTableInfoTableValueListItem> tableValueList = new ArrayList<GoodsPropertiesItemTableInfoTableValueListItem>();
|
||||
|
||||
GoodsPropertiesItemTableInfoTableValueListItem item1 = new GoodsPropertiesItemTableInfoTableValueListItem();
|
||||
item1.setColumnType(1);
|
||||
item1.setUnit("str");
|
||||
item1.setValue("str");
|
||||
tableValueList.add(item1);
|
||||
tableInfo.setTableValueList(tableValueList);
|
||||
item.setTableInfo(tableInfo);
|
||||
item.setTemplatePid(0L);
|
||||
item.setValue("str");
|
||||
item.setValueUnit("str");
|
||||
item.setVid(0L);
|
||||
goodsProperties.add(item);
|
||||
request.setGoodsProperties(goodsProperties);
|
||||
PddGoodsCatRuleGetResponse response = client.syncInvoke(request, accessToken);
|
||||
System.out.println(JsonUtil.transferToJson(response));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 响应示例
|
||||
|
||||
```
|
||||
{
|
||||
"cat_rule_get_response": {
|
||||
"goods_properties_rule": {
|
||||
"choose_all_qualify_spec": true,
|
||||
"input_max_spec_num": 1,
|
||||
"properties": [
|
||||
{
|
||||
"can_note": true,
|
||||
"choose_max_num": 1,
|
||||
"input_max_num": 0,
|
||||
"is_important": true,
|
||||
"is_sale": true,
|
||||
"is_sku": false,
|
||||
"max_value": "10",
|
||||
"min_value": "1",
|
||||
"name": "品牌",
|
||||
"parent_spec_id": 111111,
|
||||
"property_value_type": 0,
|
||||
"ref_pid": 310,
|
||||
"required": true,
|
||||
"required_rule": "str",
|
||||
"required_rule_type": 0,
|
||||
"show_condition": [
|
||||
{
|
||||
"parent_ref_pid": 1111,
|
||||
"parent_vids": [
|
||||
1234
|
||||
]
|
||||
}
|
||||
],
|
||||
"value_precision": 0,
|
||||
"value_unit": [
|
||||
"kg"
|
||||
],
|
||||
"values": [
|
||||
{
|
||||
"extend_info": "(255,255,255,1)",
|
||||
"group": {
|
||||
"id": 1,
|
||||
"name": "红色系"
|
||||
},
|
||||
"parent_vids": [
|
||||
12345
|
||||
],
|
||||
"spec_id": 1122,
|
||||
"value": "aaa",
|
||||
"vid": 1111
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"goods_service_rule": {
|
||||
"goods_service_rule_map": {
|
||||
"": {
|
||||
"bad_claim_rule": 0,
|
||||
"can_select_delivery_type": false,
|
||||
"delivery_one_day_rule": 0,
|
||||
"folt_rule": 0,
|
||||
"lack_of_weight_claim_rule": 0,
|
||||
"need_upload_package_label": false,
|
||||
"need_upload_package_label_required": false,
|
||||
"need_upload_package_label_type": 0,
|
||||
"privacy_delivery_rule": 0,
|
||||
"quan_guo_lian_bao_rule": 0,
|
||||
"refundable_rule": 0,
|
||||
"rule_related_ref_pid_map": {
|
||||
"": [
|
||||
0
|
||||
]
|
||||
},
|
||||
"shipment_limit_second_list": [
|
||||
0
|
||||
],
|
||||
"zhi_huan_bu_xiu_rule": 0
|
||||
}
|
||||
},
|
||||
"goods_type_list": [
|
||||
0
|
||||
]
|
||||
},
|
||||
"goods_sku_rule": {
|
||||
"price_range_ratio": 0.0,
|
||||
"spec_num_limit": 0
|
||||
},
|
||||
"spu_rule": {
|
||||
"control_type": 0,
|
||||
"key_prop": [
|
||||
{
|
||||
"pname": "str",
|
||||
"ref_pid": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"two_pieces_discount_rule": {
|
||||
"if_must_two_pieces_discount": false,
|
||||
"max_two_pieces_discount": 0,
|
||||
"min_two_pieces_discount": 0,
|
||||
"recommend_two_pieces_discount": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 异常示例
|
||||
|
||||
JSON
|
||||
|
||||
XML
|
||||
|
||||
```
|
||||
{
|
||||
"error_response": {
|
||||
"error_msg": "公共参数错误:type",
|
||||
"sub_msg": "",
|
||||
"sub_code": null,
|
||||
"error_code": 10001,
|
||||
"request_id": "15440104776643887"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 相关权限包
|
||||
|
||||
| 拥有此接口的权限包 | 可获得/可申请此权限包的应用类型 |
|
||||
| --- | --- |
|
||||
| 商品编辑 | 进销存、商品优化分析、虚拟商家后台系统、企业ERP、商家后台系统、电子凭证商家后台系统、跨境企业ERP报关版 |
|
||||
|
||||
### 返回错误码说明
|
||||
|
||||
| 主错误码 | 主错误描述 | 子错误码 | 子错误描述 | 解决办法 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 10000 | 参数错误 | 10000 | 参数错误 | 参数值有误,按照文档要求填写请求参数 |
|
||||
| 10001 | 公共参数错误 | 10001 | 公共参数错误 | 请检查请求的公共参数 |
|
||||
| 10016 | client下线或者clientId不正确 | 10016 | client下线或者clientId不正确 | 请核查您的client\_id是否正确 |
|
||||
| 10017 | type不正确 | 10017 | type不正确 | 检查type是否正确 |
|
||||
| 10018 | target\_client\_id下线或者target\_client\_id不正确 | 10018 | target\_client\_id下线或者target\_client\_id不正确 | 检查target\_client\_id 是否正确 |
|
||||
| 10019 | access\_token已过期 | 10019 | access\_token已过期 | 刷新access\_token或者重新授权再次获取access\_token |
|
||||
| 20004 | 签名sign校验失败 | 20004 | 签名sign校验失败 | 请按照接入指南第三部分指导,生成签名 |
|
||||
| 20005 | ip无权访问接口,请加入ip白名单 | 20005 | ip无权访问接口,请加入ip白名单 | 把ip白名单加入白名单 |
|
||||
| 20031 | 用户没有授权访问此接口 | 20031 | 用户没有授权访问此接口 | 您创建的应用中不包含此接口,请查看API文档,了解相关权限包 |
|
||||
| 20032 | access\_token或client\_id错误 | 20032 | access\_token或client\_id错误 | 检查access\_token或client\_id |
|
||||
| 20034 | 接口处于下线状态 | 20034 | 接口处于下线状态 | 检查接口状态 |
|
||||
| 20035 | 接口不属于当前网关 | 20035 | 接口不属于当前网关 | 判断调用网关url 是否正确 |
|
||||
| 21001 | 请求参数错误 | 21001 | 请求参数错误 | 业务参数输入错误 |
|
||||
| 21002 | 请求参数不能为空 | 21002 | 请求参数不能为空 | 检查业务参数必填是否已填 |
|
||||
| 30000 | 没有调用此target接口权限 | 30000 | 没有调用此target接口权限 | 检查是否获得调用此target接口权限 |
|
||||
| 30001 | client\_id和partner\_id不匹配 | 30001 | client\_id和partner\_id不匹配 | 检查partner\_id是否正确 |
|
||||
| 50000 | 系统内部错误 | 50000 | 系统内部错误 | 系统内部错误,请加群联系相关负责人 |
|
||||
| 50002 | 业务系统内部异常 | 50002 | 业务系统内部异常 | 请加群联系相关负责人 |
|
||||
| 52001 | 网关业务服务错误 | 52001 | 网关业务服务错误 | 联系技术支持解决 |
|
||||
| 52002 | 网关系统内部异常 | 52002 | 网关系统内部异常 | 联系技术支持解决 |
|
||||
| 52004 | 请求body 太大 | 52004 | 请求body 太大 | 检查请求体是否过大 |
|
||||
| 52101 | 当前接口被限流,请稍后重试 | 52101 | 当前接口被限流,请稍后重试 | 当前接口被限流,请稍后重试 |
|
||||
| 52102 | 当前接口暂时不可用,请稍后重试 | 52102 | 当前接口暂时不可用,请稍后重试 | 当前接口被降级,请稍后重试 |
|
||||
| 52103 | 服务暂时不可用,请稍后重试 | 52103 | 服务暂时不可用,请稍后重试 | 当前接口被降级,请稍后重试 |
|
||||
| 70031 | 调用过于频繁,请调整调用频率 | 70031 | 调用过于频繁,请调整调用频率 | 调用过于频繁,请调整调用频率 |
|
||||
| 70032 | 当前请求被禁止调用 | 70032 | 当前请求被禁止调用 | 当前请求被禁止调用 |
|
||||
| 70033 | 当前接口因系统维护,暂时下线,请稍后再试! | 70033 | 当前接口因系统维护,暂时下线,请稍后再试! | 当前接口因系统维护,暂时下线,请稍后再试! |
|
||||
| 70034 | 当前用户或应用存在风险,禁止调用! | 70034 | 当前用户或应用存在风险,禁止调用! | 当前用户或应用存在风险,禁止调用! |
|
||||
| 70035 | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com | 70035 | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com |
|
||||
| 70036 | 应用处于测试状态,调用次数被限制 | 70036 | 应用处于测试状态,调用次数被限制 | 应用处于测试状态,调用次数达到上限被限制 |
|
||||
| 50001 | 业务服务错误 | isv.###-not-exist:20002 | 类目不存在 | 输入正确的类目 |
|
||||
|
||||
### 限流规则
|
||||
|
||||
接口总限流频次:5000次/1秒
|
||||
@@ -0,0 +1,247 @@
|
||||
API文档/商品API/pdd.goods.cat.template.get
|
||||
|
||||
# pdd.goods.cat.template.get
|
||||
|
||||
## 获取商品类目属性(已废弃)
|
||||
|
||||
更新时间:2021-04-13 23:04:54
|
||||
|
||||
¥免费API
|
||||
|
||||
必须用户授权
|
||||
|
||||
商品发布前,需要查询该类目的商品发布需要的属性,获取商品发布需要的模板-属性-属性值。已废弃,建议使用pdd.goods.cat.rule.get代替
|
||||
|
||||
### 公共参数
|
||||
|
||||
#### 请求地址(目前只提供正式环境,暂无沙箱环境)
|
||||
|
||||
| 环境 | HTTP地址 | HTTPS地址 |
|
||||
| --- | --- | --- |
|
||||
| 正式环境 | http://gw-api.pinduoduo.com/api/router | https://gw-api.pinduoduo.com/api/router |
|
||||
|
||||
#### 公共请求参数
|
||||
|
||||
| 参数名称 | 参数类型 | 是否必填 | 参数描述 |
|
||||
| --- | --- | --- | --- |
|
||||
| type | String | 必填 | API接口名称 |
|
||||
| client\_id | String | 必填 | POP分配给应用的client\_id |
|
||||
| access\_token | String | 非必填 | 通过code获取的access\_token |
|
||||
| timestamp | String | 必填 | UNIX时间戳,单位秒,需要与拼多多服务器时间差值在10分钟内 |
|
||||
| data\_type | String | 非必填 | 响应格式,即返回数据的格式,JSON或者XML(二选一),默认JSON,注意是大写 |
|
||||
| version | String | 非必填 | API协议版本号,默认为V1,可不填 |
|
||||
| sign | String | 必填 | API输入参数签名结果,签名算法参考开放平台接入指南第三部分底部。 |
|
||||
|
||||
### 请求参数说明
|
||||
|
||||
| 参数接口 | 参数类型 | 是否必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| cat\_id | LONG | 必填 | 类目id |
|
||||
|
||||
### 返回参数说明
|
||||
|
||||
| 参数接口 | 参数类型 | 例子 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| open\_api\_response | OBJECT | | 属性信息 |
|
||||
| choose\_all\_qualify\_spec | BOOLEAN | | 限定规格不支持部分选取,为true时限定规格要么全选要么全不选 |
|
||||
| id | LONG | | 模板id |
|
||||
| input\_max\_spec\_num | LONG | | 模板允许的最大的自定义规格数量 |
|
||||
| is\_single\_item | BOOLEAN | | is\_single\_item |
|
||||
| max\_sku\_num | LONG | | 最大sku数目上限 |
|
||||
| properties | OBJECT\[\] | | 属性信息 |
|
||||
| can\_note | BOOLEAN | | 是否允许填写备注 |
|
||||
| choose\_max\_num | INTEGER | | 最大可勾选数目,为0时代表不限 |
|
||||
| control\_type | INTEGER | | 控件类型(0-可输入、1-可勾选、3-可输入又可勾选、5-单项时间选择器-年月日、6-双项时间选择器-年月日、7-单项时间选择器-年月、8-双项时间选择器-年月)9-调色盘、10-尺码选择器、11-输入数值范围、12-输入数值乘积-2维、13-输入数值乘积-3维 |
|
||||
| feature | INTEGER | | 属性特性:0普通,1颜色,2尺码 |
|
||||
| id | LONG | | 模板属性id |
|
||||
| input\_max\_num | INTEGER | | 最大可输入数目,为0时代表不可输入,非销售属性为null |
|
||||
| is\_condition\_show | BOOLEAN | | 是否按条件展示 |
|
||||
| is\_key | BOOLEAN | | is\_key |
|
||||
| is\_parent | BOOLEAN | | 是否父属性 |
|
||||
| is\_sale | BOOLEAN | | 是否销售属性 |
|
||||
| max\_value | STRING | | 输入最大值:文本类型代表文本最长长度、 数值类型代表数字最大值、时间类型代表时间最大值 |
|
||||
| min\_value | STRING | | 输入最小值:文本类型代表文本最小长度、数值类型代表数字最小值、时间类型代表时间最小值 |
|
||||
| name | STRING | | 属性名称 |
|
||||
| name\_alias | STRING | | 属性别名 |
|
||||
| parent\_id | LONG | | 父属性id |
|
||||
| ref\_pid | LONG | | 引用属性id |
|
||||
| required | BOOLEAN | | 是否必填 |
|
||||
| required\_rule | STRING | | 必填规则具体内容,当required=true且required\_rule\_type=1时该字段有效,表示当出现哪些属性/属性值时,该属性需要必填,json格式,两层List结构,外层list代表"或"关系,内层list代表"且"关系,例如:\[\[{\\"ref\_pid\\":123,\\"vid\\":123}\]\] |
|
||||
| required\_rule\_type | INTEGER | | required=true时,该字段有效,为“0”时表示当前属性必填,不受其他属性影响,为“1”时表示当前属性是否必填由已填写的其他属性值决定 |
|
||||
| show\_only\_standard | BOOLEAN | | show\_only\_standard |
|
||||
| show\_vids | LONG\[\] | | 若属性按条件展示,则只有show\_vids中的值被选择时属性才可使用 |
|
||||
| spec\_id | LONG | | 销售属性规格id,非销售属性为null |
|
||||
| values | OBJECT\[\] | | 属性值列表 |
|
||||
| extend\_info | STRING | | 扩展信息,颜色的话色号在这里,ARGB,非销售属性为null |
|
||||
| group | OBJECT | | 分组信息,非销售属性为null |
|
||||
| id | INTEGER | | 组id |
|
||||
| name | STRING | | 组名称 |
|
||||
| is\_parent | BOOLEAN | | 是否父属性值 |
|
||||
| parent\_vids | LONG\[\] | | 对应的父属性值id |
|
||||
| spec\_id | LONG | | 规格id,非销售属性为null |
|
||||
| value | STRING | | 属性值 |
|
||||
| vid | LONG | | 基础属性值id |
|
||||
| value\_precision | INTEGER | | 小数点允许最大精度,为0时代表不允许输入小数 |
|
||||
| value\_type | INTEGER | | 属性值类型(0-文本、1-数值、4-绝对时间、5-相对时间) |
|
||||
| value\_unit | STRING | | 属性值单位 |
|
||||
| single\_spec\_value\_num | LONG | | 单个自定义规格值上限 |
|
||||
|
||||
### 请求示例
|
||||
|
||||
JAVA
|
||||
|
||||
CURL
|
||||
|
||||
```
|
||||
package com.pdd.pop.sdk.http.demo;
|
||||
|
||||
import com.pdd.pop.sdk.common.util.JsonUtil;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatTemplateGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsCatTemplateGetResponse;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
|
||||
public class PopClientDemo {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String clientId = "your clientId";
|
||||
String clientSecret = "your clientSecret";
|
||||
String accessToken = "your accessToken";
|
||||
PopClient client = new PopHttpClient(clientId, clientSecret);
|
||||
|
||||
PddGoodsCatTemplateGetRequest request = new PddGoodsCatTemplateGetRequest();
|
||||
request.setCatId(0L);
|
||||
PddGoodsCatTemplateGetResponse response = client.syncInvoke(request, accessToken);
|
||||
System.out.println(JsonUtil.transferToJson(response));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 响应示例
|
||||
|
||||
```
|
||||
{
|
||||
"open_api_response": {
|
||||
"choose_all_qualify_spec": false,
|
||||
"id": 0,
|
||||
"input_max_spec_num": 0,
|
||||
"is_single_item": false,
|
||||
"max_sku_num": 0,
|
||||
"properties": [
|
||||
{
|
||||
"can_note": false,
|
||||
"choose_max_num": 0,
|
||||
"control_type": 0,
|
||||
"feature": 0,
|
||||
"id": 0,
|
||||
"input_max_num": 0,
|
||||
"is_condition_show": false,
|
||||
"is_key": false,
|
||||
"is_parent": false,
|
||||
"is_sale": false,
|
||||
"max_value": "str",
|
||||
"min_value": "str",
|
||||
"name": "str",
|
||||
"name_alias": "str",
|
||||
"parent_id": 0,
|
||||
"ref_pid": 0,
|
||||
"required": false,
|
||||
"required_rule": "str",
|
||||
"required_rule_type": 0,
|
||||
"show_only_standard": false,
|
||||
"show_vids": [
|
||||
0
|
||||
],
|
||||
"spec_id": 0,
|
||||
"value_precision": 0,
|
||||
"value_type": 0,
|
||||
"value_unit": "str",
|
||||
"values": [
|
||||
{
|
||||
"extend_info": "str",
|
||||
"group": {
|
||||
"id": 0,
|
||||
"name": "str"
|
||||
},
|
||||
"is_parent": false,
|
||||
"parent_vids": [
|
||||
0
|
||||
],
|
||||
"spec_id": 0,
|
||||
"value": "str",
|
||||
"vid": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"single_spec_value_num": 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 异常示例
|
||||
|
||||
JSON
|
||||
|
||||
XML
|
||||
|
||||
```
|
||||
{
|
||||
"error_response": {
|
||||
"error_msg": "公共参数错误:type",
|
||||
"sub_msg": "",
|
||||
"sub_code": null,
|
||||
"error_code": 10001,
|
||||
"request_id": "15440104776643887"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 相关权限包
|
||||
|
||||
| 拥有此接口的权限包 | 可获得/可申请此权限包的应用类型 |
|
||||
| --- | --- |
|
||||
| 商品类目属性权限包 | 进销存、商品优化分析、虚拟商家后台系统、企业ERP、商家后台系统、电子凭证商家后台系统、跨境企业ERP报关版 |
|
||||
|
||||
### 返回错误码说明
|
||||
|
||||
| 主错误码 | 主错误描述 | 子错误码 | 子错误描述 | 解决办法 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 10000 | 参数错误 | 10000 | 参数错误 | 参数值有误,按照文档要求填写请求参数 |
|
||||
| 10001 | 公共参数错误 | 10001 | 公共参数错误 | 请检查请求的公共参数 |
|
||||
| 10016 | client下线或者clientId不正确 | 10016 | client下线或者clientId不正确 | 请核查您的client\_id是否正确 |
|
||||
| 10017 | type不正确 | 10017 | type不正确 | 检查type是否正确 |
|
||||
| 10018 | target\_client\_id下线或者target\_client\_id不正确 | 10018 | target\_client\_id下线或者target\_client\_id不正确 | 检查target\_client\_id 是否正确 |
|
||||
| 10019 | access\_token已过期 | 10019 | access\_token已过期 | 刷新access\_token或者重新授权再次获取access\_token |
|
||||
| 20004 | 签名sign校验失败 | 20004 | 签名sign校验失败 | 请按照接入指南第三部分指导,生成签名 |
|
||||
| 20005 | ip无权访问接口,请加入ip白名单 | 20005 | ip无权访问接口,请加入ip白名单 | 把ip白名单加入白名单 |
|
||||
| 20031 | 用户没有授权访问此接口 | 20031 | 用户没有授权访问此接口 | 您创建的应用中不包含此接口,请查看API文档,了解相关权限包 |
|
||||
| 20032 | access\_token或client\_id错误 | 20032 | access\_token或client\_id错误 | 检查access\_token或client\_id |
|
||||
| 20034 | 接口处于下线状态 | 20034 | 接口处于下线状态 | 检查接口状态 |
|
||||
| 20035 | 接口不属于当前网关 | 20035 | 接口不属于当前网关 | 判断调用网关url 是否正确 |
|
||||
| 21001 | 请求参数错误 | 21001 | 请求参数错误 | 业务参数输入错误 |
|
||||
| 21002 | 请求参数不能为空 | 21002 | 请求参数不能为空 | 检查业务参数必填是否已填 |
|
||||
| 30000 | 没有调用此target接口权限 | 30000 | 没有调用此target接口权限 | 检查是否获得调用此target接口权限 |
|
||||
| 30001 | client\_id和partner\_id不匹配 | 30001 | client\_id和partner\_id不匹配 | 检查partner\_id是否正确 |
|
||||
| 50000 | 系统内部错误 | 50000 | 系统内部错误 | 系统内部错误,请加群联系相关负责人 |
|
||||
| 50002 | 业务系统内部异常 | 50002 | 业务系统内部异常 | 请加群联系相关负责人 |
|
||||
| 52001 | 网关业务服务错误 | 52001 | 网关业务服务错误 | 联系技术支持解决 |
|
||||
| 52002 | 网关系统内部异常 | 52002 | 网关系统内部异常 | 联系技术支持解决 |
|
||||
| 52004 | 请求body 太大 | 52004 | 请求body 太大 | 检查请求体是否过大 |
|
||||
| 52101 | 当前接口被限流,请稍后重试 | 52101 | 当前接口被限流,请稍后重试 | 当前接口被限流,请稍后重试 |
|
||||
| 52102 | 当前接口暂时不可用,请稍后重试 | 52102 | 当前接口暂时不可用,请稍后重试 | 当前接口被降级,请稍后重试 |
|
||||
| 52103 | 服务暂时不可用,请稍后重试 | 52103 | 服务暂时不可用,请稍后重试 | 当前接口被降级,请稍后重试 |
|
||||
| 70031 | 调用过于频繁,请调整调用频率 | 70031 | 调用过于频繁,请调整调用频率 | 调用过于频繁,请调整调用频率 |
|
||||
| 70032 | 当前请求被禁止调用 | 70032 | 当前请求被禁止调用 | 当前请求被禁止调用 |
|
||||
| 70033 | 当前接口因系统维护,暂时下线,请稍后再试! | 70033 | 当前接口因系统维护,暂时下线,请稍后再试! | 当前接口因系统维护,暂时下线,请稍后再试! |
|
||||
| 70034 | 当前用户或应用存在风险,禁止调用! | 70034 | 当前用户或应用存在风险,禁止调用! | 当前用户或应用存在风险,禁止调用! |
|
||||
| 70035 | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com | 70035 | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com | 当前用户或应用存在风险,禁止调用。请联系ddjb@pinduoduo.com |
|
||||
| 70036 | 应用处于测试状态,调用次数被限制 | 70036 | 应用处于测试状态,调用次数被限制 | 应用处于测试状态,调用次数达到上限被限制 |
|
||||
| 50001 | 业务服务错误 | | | |
|
||||
|
||||
### 限流规则
|
||||
|
||||
商家限流频次:2000次/10秒
|
||||
|
||||
接口总限流频次:2000次/10秒
|
||||
@@ -14,7 +14,6 @@ API文档/商品API/pdd.goods.submit.goods.commit
|
||||
|
||||
### 公共参数
|
||||
|
||||
|
||||
#### 请求地址(目前只提供正式环境,暂无沙箱环境)
|
||||
|
||||
| 环境 | HTTP地址 | HTTPS地址 |
|
||||
@@ -35,7 +34,6 @@ API文档/商品API/pdd.goods.submit.goods.commit
|
||||
|
||||
### 请求参数说明
|
||||
|
||||
|
||||
| 参数接口 | 参数类型 | 是否必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| auto\_fill\_spu\_property | BOOLEAN | 非必填 | 是否自动补充标品属性 |
|
||||
@@ -157,7 +155,6 @@ API文档/商品API/pdd.goods.submit.goods.commit
|
||||
|
||||
### 返回参数说明
|
||||
|
||||
|
||||
| 参数接口 | 参数类型 | 例子 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| goods\_update\_response | OBJECT | | 返回response |
|
||||
@@ -167,11 +164,6 @@ API文档/商品API/pdd.goods.submit.goods.commit
|
||||
|
||||
### 请求示例
|
||||
|
||||
|
||||
JAVA
|
||||
|
||||
CURL
|
||||
|
||||
```
|
||||
xxxxxxxxxx
|
||||
package com.pdd.pop.sdk.http.demo;
|
||||
@@ -374,8 +366,8 @@ public class PopClientDemo {
|
||||
}
|
||||
|
||||
```
|
||||
### 响应示例
|
||||
|
||||
### 响应示例
|
||||
|
||||
```
|
||||
xxxxxxxxxx
|
||||
@@ -387,13 +379,9 @@ xxxxxxxxxx
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 异常示例
|
||||
|
||||
|
||||
JSON
|
||||
|
||||
XML
|
||||
|
||||
```
|
||||
xxxxxxxxxx
|
||||
|
||||
@@ -407,8 +395,8 @@ xxxxxxxxxx
|
||||
}
|
||||
}
|
||||
```
|
||||
### 相关权限包
|
||||
|
||||
### 相关权限包
|
||||
|
||||
| 拥有此接口的权限包 | 可获得/可申请此权限包的应用类型 |
|
||||
| --- | --- |
|
||||
@@ -416,7 +404,6 @@ xxxxxxxxxx
|
||||
|
||||
### 返回错误码说明
|
||||
|
||||
|
||||
| 主错误码 | 主错误描述 | 子错误码 | 子错误描述 | 解决办法 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 10000 | 参数错误 | 10000 | 参数错误 | 参数值有误,按照文档要求填写请求参数 |
|
||||
@@ -453,10 +440,6 @@ xxxxxxxxxx
|
||||
|
||||
### 限流规则
|
||||
|
||||
|
||||
接口总限流频次:3750次/10秒
|
||||
|
||||
应用限流频次:100次/1秒
|
||||
|
||||
### API工具
|
||||
|
||||
|
||||
+68
-234
@@ -77,265 +77,102 @@ API文档/商品API/pdd.one.express.cost.template
|
||||
|
||||
### 请求示例
|
||||
|
||||
JAVA
|
||||
|
||||
CURL
|
||||
|
||||
195
|
||||
|
||||
```
|
||||
package com.pdd.pop.sdk.http.demo;
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
|
||||
import com.pdd.pop.sdk.common.util.JsonUtil;
|
||||
```
|
||||
```
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddOneExpressCostTemplateRequest;
|
||||
```
|
||||
```
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddOneExpressCostTemplateResponse;
|
||||
```
|
||||
```
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
```
|
||||
```
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
|
||||
public class PopClientDemo {
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
public static void main(String[] args) throws Exception {
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
String clientId = "your clientId";
|
||||
```
|
||||
```
|
||||
String clientSecret = "your clientSecret";
|
||||
```
|
||||
```
|
||||
String accessToken = "your accessToken";
|
||||
```
|
||||
```
|
||||
PopClient client = new PopHttpClient(clientId, clientSecret);
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
PddOneExpressCostTemplateRequest request = new PddOneExpressCostTemplateRequest();
|
||||
```
|
||||
```
|
||||
request.setCostTemplateId(0L);
|
||||
```
|
||||
```
|
||||
PddOneExpressCostTemplateResponse response = client.syncInvoke(request, accessToken);
|
||||
```
|
||||
```
|
||||
System.out.println(JsonUtil.transferToJson(response));
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String clientId = "your clientId";
|
||||
String clientSecret = "your clientSecret";
|
||||
String accessToken = "your accessToken";
|
||||
PopClient client = new PopHttpClient(clientId, clientSecret);
|
||||
|
||||
PddOneExpressCostTemplateRequest request = new PddOneExpressCostTemplateRequest();
|
||||
request.setCostTemplateId(0L);
|
||||
PddOneExpressCostTemplateResponse response = client.syncInvoke(request, accessToken);
|
||||
System.out.println(JsonUtil.transferToJson(response));
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
### 响应示例
|
||||
|
||||
7
|
||||
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"one_express_cost_template_response": {
|
||||
```
|
||||
```
|
||||
"additional_service_type": 0,
|
||||
```
|
||||
```
|
||||
"city_id": 0,
|
||||
```
|
||||
```
|
||||
"cost_template_list": [
|
||||
```
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"add_cost": 0,
|
||||
```
|
||||
```
|
||||
"add_standard": 0,
|
||||
```
|
||||
```
|
||||
"cost_province_list": [
|
||||
```
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"province": "str",
|
||||
```
|
||||
```
|
||||
"province_id": 0
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
```
|
||||
],
|
||||
```
|
||||
```
|
||||
"first_cost": 0,
|
||||
```
|
||||
```
|
||||
"first_standard": 0,
|
||||
```
|
||||
```
|
||||
"have_free_min_amount": 0,
|
||||
```
|
||||
```
|
||||
"have_free_min_count": 0,
|
||||
```
|
||||
```
|
||||
"is_have_free_min_amount": false,
|
||||
```
|
||||
```
|
||||
"is_have_free_min_count": false
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
```
|
||||
],
|
||||
```
|
||||
```
|
||||
"cost_type": 0,
|
||||
```
|
||||
```
|
||||
"district_id": 0,
|
||||
```
|
||||
```
|
||||
"free_deliver_house": false,
|
||||
```
|
||||
```
|
||||
"free_deliver_house_area_list": [
|
||||
```
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"city": "str",
|
||||
```
|
||||
```
|
||||
"city_id": 0,
|
||||
```
|
||||
```
|
||||
"province": "str",
|
||||
```
|
||||
```
|
||||
"province_id": 0,
|
||||
```
|
||||
```
|
||||
"town": "str",
|
||||
```
|
||||
```
|
||||
"town_id": 0
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
```
|
||||
],
|
||||
```
|
||||
```
|
||||
"free_province_list": [
|
||||
```
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"province": "str",
|
||||
```
|
||||
```
|
||||
"province_id": 0
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
```
|
||||
],
|
||||
```
|
||||
```
|
||||
"province_id": 0,
|
||||
```
|
||||
```
|
||||
"sf_free_type": 0,
|
||||
```
|
||||
```
|
||||
"template_id": 0,
|
||||
```
|
||||
```
|
||||
"template_name": "str"
|
||||
```
|
||||
```
|
||||
"one_express_cost_template_response": {
|
||||
"additional_service_type": 0,
|
||||
"city_id": 0,
|
||||
"cost_template_list": [
|
||||
{
|
||||
"add_cost": 0,
|
||||
"add_standard": 0,
|
||||
"cost_province_list": [
|
||||
{
|
||||
"province": "str",
|
||||
"province_id": 0
|
||||
}
|
||||
],
|
||||
"first_cost": 0,
|
||||
"first_standard": 0,
|
||||
"have_free_min_amount": 0,
|
||||
"have_free_min_count": 0,
|
||||
"is_have_free_min_amount": false,
|
||||
"is_have_free_min_count": false
|
||||
}
|
||||
],
|
||||
"cost_type": 0,
|
||||
"district_id": 0,
|
||||
"free_deliver_house": false,
|
||||
"free_deliver_house_area_list": [
|
||||
{
|
||||
"city": "str",
|
||||
"city_id": 0,
|
||||
"province": "str",
|
||||
"province_id": 0,
|
||||
"town": "str",
|
||||
"town_id": 0
|
||||
}
|
||||
],
|
||||
"free_province_list": [
|
||||
{
|
||||
"province": "str",
|
||||
"province_id": 0
|
||||
}
|
||||
],
|
||||
"province_id": 0,
|
||||
"sf_free_type": 0,
|
||||
"template_id": 0,
|
||||
"template_name": "str"
|
||||
}
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
### 异常示例
|
||||
|
||||
JSON
|
||||
|
||||
XML
|
||||
|
||||
```
|
||||
|
||||
```
|
||||
```
|
||||
{
|
||||
```
|
||||
```
|
||||
"error_response": {
|
||||
```
|
||||
```
|
||||
"error_msg": "公共参数错误:type",
|
||||
```
|
||||
```
|
||||
"sub_msg": "",
|
||||
```
|
||||
```
|
||||
"sub_code": null,
|
||||
```
|
||||
```
|
||||
"error_code": 10001,
|
||||
```
|
||||
```
|
||||
"request_id": "15440104776643887"
|
||||
```
|
||||
```
|
||||
"error_response": {
|
||||
"error_msg": "公共参数错误:type",
|
||||
"sub_msg": "",
|
||||
"sub_code": null,
|
||||
"error_code": 10001,
|
||||
"request_id": "15440104776643887"
|
||||
}
|
||||
```
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
### 相关权限包
|
||||
|
||||
| 拥有此接口的权限包 | 可获得/可申请此权限包的应用类型 |
|
||||
@@ -381,6 +218,3 @@ XML
|
||||
### 限流规则
|
||||
|
||||
接口总限流频次:2500次/1秒
|
||||
|
||||
### API工具
|
||||
|
||||
|
||||
Executable
+313
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env python3
|
||||
"""清理拼多多开放平台文档抓取污染。
|
||||
|
||||
处理内容:
|
||||
1. 将「一行一个代码块 + 行号」合并为完整代码块
|
||||
2. 去掉 xxxxxxxxxx 占位、行号、零宽字符 / 不间断空格
|
||||
3. 去掉「点击收起」「点击展开」等页面交互文案
|
||||
4. 去掉仅含空内容的「### API工具」小节
|
||||
|
||||
用法:
|
||||
python clean_scraped_md.py # 交互选择
|
||||
python clean_scraped_md.py --all # 处理目录下全部 md
|
||||
python clean_scraped_md.py a.md b.md # 指定文件(相对本脚本目录或绝对路径)
|
||||
python clean_scraped_md.py --dry-run --all
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
NUM_LINE = re.compile(r"^\d+\s*$")
|
||||
UI_TOGGLE = re.compile(r"^(点击收起|点击展开)\s*$")
|
||||
EMPTY_API_TOOLS = re.compile(r"\n### API工具\s*$")
|
||||
MULTI_BLANK = re.compile(r"\n{3,}")
|
||||
TAB_LABEL = re.compile(r"^(JAVA|CURL|JSON|XML)\s*$", re.I)
|
||||
|
||||
|
||||
def list_md_files() -> list[Path]:
|
||||
"""列出本目录下全部 md,相对 ROOT 排序。"""
|
||||
files = sorted(ROOT.rglob("*.md"), key=lambda p: str(p.relative_to(ROOT)))
|
||||
return [p for p in files if p.is_file()]
|
||||
|
||||
|
||||
def resolve_targets(raw: list[str]) -> list[Path]:
|
||||
"""把用户输入的路径解析为绝对路径。"""
|
||||
out: list[Path] = []
|
||||
for item in raw:
|
||||
p = Path(item)
|
||||
if not p.is_absolute():
|
||||
cand = (ROOT / p).resolve()
|
||||
if not cand.exists():
|
||||
cand = Path.cwd().joinpath(p).resolve()
|
||||
p = cand
|
||||
else:
|
||||
p = p.resolve()
|
||||
if not p.is_file() or p.suffix.lower() != ".md":
|
||||
raise FileNotFoundError(f"不是有效的 md 文件: {item}")
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
|
||||
def normalize_content(s: str) -> str:
|
||||
"""规范化代码行:nbsp→空格,纯零宽行→空行。"""
|
||||
s = s.replace("\xa0", " ").replace("\u00a0", " ")
|
||||
if "\u200b" in s and s.strip("\u200b").strip() == "":
|
||||
return ""
|
||||
return s.replace("\u200b", "")
|
||||
|
||||
|
||||
def is_xxxx_placeholder(s: str) -> bool:
|
||||
t = s.strip()
|
||||
return bool(t) and set(t) <= {"x"} and len(t) >= 4
|
||||
|
||||
|
||||
def merge_polluted_fences(text: str) -> str:
|
||||
"""合并抓取产生的单行代码块序列。"""
|
||||
raw = text.split("\n")
|
||||
n = len(raw)
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
|
||||
def is_fence(idx: int) -> bool:
|
||||
return idx < n and raw[idx].strip() == "```"
|
||||
|
||||
while i < n:
|
||||
if not is_fence(i):
|
||||
line = raw[i]
|
||||
if "\u200b" in line or "\xa0" in line:
|
||||
if "\u200b" in line and line.strip("\u200b").strip() == "":
|
||||
out.append("")
|
||||
else:
|
||||
out.append(line.replace("\xa0", " ").replace("\u200b", ""))
|
||||
else:
|
||||
out.append(line)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 解析当前 fence
|
||||
j = i + 1
|
||||
content_lines: list[str] = []
|
||||
while j < n and raw[j].strip() != "```":
|
||||
content_lines.append(raw[j])
|
||||
j += 1
|
||||
if j >= n:
|
||||
out.append(raw[i])
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 已是多行代码块,保持原样
|
||||
if len(content_lines) > 1:
|
||||
out.extend(raw[i : j + 1])
|
||||
i = j + 1
|
||||
continue
|
||||
|
||||
content = content_lines[0] if content_lines else ""
|
||||
|
||||
# 跳过 xxxxxxxxxx 占位及其后的行号
|
||||
if is_xxxx_placeholder(content):
|
||||
k = j + 1
|
||||
while k < n and (raw[k].strip() == "" or NUM_LINE.match(raw[k].strip())):
|
||||
k += 1
|
||||
i = k
|
||||
continue
|
||||
|
||||
seq_start = i
|
||||
code_parts: list[str] = []
|
||||
cur = i
|
||||
end = j + 1
|
||||
|
||||
while is_fence(cur):
|
||||
j2 = cur + 1
|
||||
cl: list[str] = []
|
||||
while j2 < n and raw[j2].strip() != "```":
|
||||
cl.append(raw[j2])
|
||||
j2 += 1
|
||||
if j2 >= n or len(cl) > 1:
|
||||
break
|
||||
|
||||
c = cl[0] if cl else ""
|
||||
if not is_xxxx_placeholder(c):
|
||||
code_parts.append(normalize_content(c))
|
||||
|
||||
k = j2 + 1
|
||||
while k < n and (raw[k].strip() == "" or NUM_LINE.match(raw[k].strip())):
|
||||
k += 1
|
||||
|
||||
if is_fence(k):
|
||||
pj = k + 1
|
||||
pcl: list[str] = []
|
||||
while pj < n and raw[pj].strip() != "```":
|
||||
pcl.append(raw[pj])
|
||||
pj += 1
|
||||
if pj < n and len(pcl) <= 1:
|
||||
cur = k
|
||||
end = k
|
||||
continue
|
||||
end = k
|
||||
break
|
||||
|
||||
had_numbers = any(
|
||||
NUM_LINE.match(raw[t].strip()) for t in range(seq_start, min(end, n))
|
||||
)
|
||||
|
||||
if len(code_parts) >= 2 or (len(code_parts) == 1 and had_numbers):
|
||||
out.append("```")
|
||||
out.extend(code_parts)
|
||||
out.append("```")
|
||||
i = end
|
||||
continue
|
||||
|
||||
out.extend(raw[i : j + 1])
|
||||
i = j + 1
|
||||
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def polish_fences(text: str) -> str:
|
||||
"""整理代码块内外空白。"""
|
||||
|
||||
def repl(m: re.Match[str]) -> str:
|
||||
body = m.group(1).strip("\n")
|
||||
return f"```\n{body}\n```"
|
||||
|
||||
text = re.sub(r"```\n(.*?)```", repl, text, flags=re.S)
|
||||
text = re.sub(r"```\n(#{1,6} )", r"```\n\n\1", text)
|
||||
return text
|
||||
|
||||
|
||||
def strip_ui_noise(text: str) -> str:
|
||||
"""去掉点击收起/展开、语言 Tab 标签、空 API工具 小节。"""
|
||||
lines = text.split("\n")
|
||||
kept: list[str] = []
|
||||
for line in lines:
|
||||
if UI_TOGGLE.match(line) or TAB_LABEL.match(line):
|
||||
continue
|
||||
kept.append(line)
|
||||
text = "\n".join(kept)
|
||||
text = EMPTY_API_TOOLS.sub("\n", text)
|
||||
text = MULTI_BLANK.sub("\n\n", text)
|
||||
return text.rstrip() + "\n"
|
||||
|
||||
|
||||
def clean_markdown(text: str) -> str:
|
||||
"""对单份文档做完整清理。"""
|
||||
text = merge_polluted_fences(text)
|
||||
text = polish_fences(text)
|
||||
text = strip_ui_noise(text)
|
||||
return text
|
||||
|
||||
|
||||
def interactive_select(files: list[Path]) -> list[Path]:
|
||||
"""终端交互多选 md 文件。"""
|
||||
if not files:
|
||||
print("未找到任何 .md 文件。")
|
||||
return []
|
||||
|
||||
print(f"目录: {ROOT}")
|
||||
print("可选文档(输入序号,逗号/空格分隔;a=全部;q=退出):\n")
|
||||
for idx, path in enumerate(files, 1):
|
||||
rel = path.relative_to(ROOT)
|
||||
print(f" {idx:3d}. {rel}")
|
||||
|
||||
print()
|
||||
raw = input("> ").strip()
|
||||
if not raw or raw.lower() in {"q", "quit", "exit"}:
|
||||
return []
|
||||
if raw.lower() in {"a", "all", "*"}:
|
||||
return files
|
||||
|
||||
tokens = re.split(r"[\s,,]+", raw)
|
||||
selected: list[Path] = []
|
||||
for tok in tokens:
|
||||
if not tok:
|
||||
continue
|
||||
if not tok.isdigit():
|
||||
print(f"无效输入: {tok}", file=sys.stderr)
|
||||
return []
|
||||
num = int(tok)
|
||||
if num < 1 or num > len(files):
|
||||
print(f"序号越界: {num}", file=sys.stderr)
|
||||
return []
|
||||
selected.append(files[num - 1])
|
||||
# 保序去重
|
||||
seen: set[Path] = set()
|
||||
uniq: list[Path] = []
|
||||
for p in selected:
|
||||
if p not in seen:
|
||||
seen.add(p)
|
||||
uniq.append(p)
|
||||
return uniq
|
||||
|
||||
|
||||
def process_file(path: Path, *, dry_run: bool) -> bool:
|
||||
"""处理单个文件;有实质改动返回 True。"""
|
||||
original = path.read_text(encoding="utf-8")
|
||||
cleaned = clean_markdown(original)
|
||||
rel = path.relative_to(ROOT) if path.is_relative_to(ROOT) else path
|
||||
|
||||
# 仅补文件末尾换行不算实质改动,避免反复误报
|
||||
if cleaned.rstrip("\n") == original.rstrip("\n"):
|
||||
print(f" skip {rel}(无需清理)")
|
||||
return False
|
||||
|
||||
stats = (
|
||||
f"lines {original.count(chr(10))}→{cleaned.count(chr(10))}, "
|
||||
f"fences {original.count('```')}→{cleaned.count('```')}"
|
||||
)
|
||||
if dry_run:
|
||||
print(f" dry {rel}({stats})")
|
||||
return True
|
||||
|
||||
path.write_text(cleaned, encoding="utf-8")
|
||||
print(f" ok {rel}({stats})")
|
||||
return True
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="清理拼多多文档抓取污染")
|
||||
parser.add_argument(
|
||||
"paths",
|
||||
nargs="*",
|
||||
help="要处理的 md(相对 docs/pdd 或绝对路径);省略则交互选择",
|
||||
)
|
||||
parser.add_argument("--all", action="store_true", help="处理目录下全部 md")
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="只预览改动统计,不写回文件",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
all_md = list_md_files()
|
||||
try:
|
||||
if args.all:
|
||||
targets = all_md
|
||||
elif args.paths:
|
||||
targets = resolve_targets(args.paths)
|
||||
else:
|
||||
targets = interactive_select(all_md)
|
||||
except FileNotFoundError as e:
|
||||
print(str(e), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if not targets:
|
||||
print("未选择文件。")
|
||||
return 0
|
||||
|
||||
print(("预览" if args.dry_run else "处理") + f" {len(targets)} 个文件:")
|
||||
changed = 0
|
||||
for path in targets:
|
||||
if process_file(path, dry_run=args.dry_run):
|
||||
changed += 1
|
||||
print(f"完成:改动 {changed}/{len(targets)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||
`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 '可选额外请求头',
|
||||
`create_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_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 displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;空则 auto
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
|
||||
+5
@@ -16,4 +16,9 @@ public class UpdateAgentLlmProviderDTO {
|
||||
|
||||
/** 传 null 表示不改;传空串可清空备注 */
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;null 不改
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
|
||||
+6
@@ -33,6 +33,12 @@ public class AgentCompanyLlmProviderPO {
|
||||
@TableField("display_name")
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
@TableField("api_style")
|
||||
private String apiStyle;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
|
||||
+4
@@ -16,5 +16,9 @@ public class AgentLlmProviderVO {
|
||||
private String displayName;
|
||||
private String apiKeyMasked;
|
||||
private String updateTime;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||
}
|
||||
|
||||
+4
@@ -15,5 +15,9 @@ public class AgentLlmRuntimeVO {
|
||||
private String model;
|
||||
/** 上下文窗口 token;可能为 null */
|
||||
private Integer contextWindow;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private Map<String, String> extraHeaders;
|
||||
}
|
||||
|
||||
+20
-8
@@ -98,6 +98,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
providerMapper.insert(po);
|
||||
@@ -123,6 +124,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
if (dto.getDisplayName() != null) {
|
||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
}
|
||||
if (dto.getApiStyle() != null) {
|
||||
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
}
|
||||
existing.setUpdateBy(userId);
|
||||
providerMapper.updateById(existing);
|
||||
evictRuntimeCache(companyId);
|
||||
@@ -432,6 +436,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||
vo.setModel(model.getModel());
|
||||
vo.setContextWindow(model.getContextWindow());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||
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) {
|
||||
if (raw == null || raw <= 0) {
|
||||
return null;
|
||||
@@ -494,14 +510,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
.orderByAsc(AgentCompanyLlmProviderPO::getId));
|
||||
}
|
||||
|
||||
private List<AgentCompanyLlmModelPO> listModels(Long companyId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getProviderId)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
/** 聊天/runtime:仅启用中的模型 */
|
||||
private List<AgentCompanyLlmModelPO> listEnabledModels(Long companyId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
@@ -546,6 +554,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
vo.setConfigured(true);
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setDisplayName(provider.getDisplayName());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||
if (provider.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||
@@ -570,6 +579,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
payload.put("api_key", runtime.getApiKey());
|
||||
payload.put("model", runtime.getModel());
|
||||
payload.put("context_window", runtime.getContextWindow());
|
||||
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
|
||||
payload.put("extra_headers",
|
||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
@@ -612,6 +622,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
} else {
|
||||
vo.setContextWindow(null);
|
||||
}
|
||||
Object style = map.get("api_style");
|
||||
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
|
||||
Object headers = map.get("extra_headers");
|
||||
if (headers instanceof Map<?, ?> m) {
|
||||
Map<String, String> h = new HashMap<>();
|
||||
|
||||
+1
-1
@@ -167,7 +167,7 @@ public class CatalogLookupAdapter {
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return productMapper.selectBatchIds(ids).stream()
|
||||
return productMapper.selectByIds(ids).stream()
|
||||
.filter(p -> companyId.equals(p.getCompanyId()))
|
||||
.collect(Collectors.toMap(ProductPO::getId, Function.identity(), (a, b) -> a));
|
||||
}
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ public class PddGoodsLookupAdapter {
|
||||
return new Slice<>(List.of(), false);
|
||||
}
|
||||
|
||||
List<PddGoodsPO> goods = pddGoodsMapper.selectBatchIds(goodsRowIds).stream()
|
||||
List<PddGoodsPO> goods = pddGoodsMapper.selectByIds(goodsRowIds).stream()
|
||||
.filter(g -> companyId.equals(g.getCompanyId()))
|
||||
.filter(g -> !Integer.valueOf(1).equals(g.getIsPlatformDeleted()))
|
||||
.filter(g -> shopId == null || shopId.equals(g.getShopId()))
|
||||
|
||||
+8
@@ -13,6 +13,7 @@ import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStat
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.common.time.BizClock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatCalcTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.OrderDailyStatComputeService;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
@@ -33,6 +34,7 @@ public class BiStatIncConsumer {
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final OrderDailyStatComputeService orderDailyStatComputeService;
|
||||
|
||||
@RabbitListener(
|
||||
queues = OrderMqConstants.QUEUE_BI_STAT_INC,
|
||||
@@ -104,6 +106,12 @@ public class BiStatIncConsumer {
|
||||
message.getShopDelta(),
|
||||
message.getProductDeltas(),
|
||||
message.getSkuDeltas());
|
||||
// INC 消息无省维 delta:同锁内轻量扫单重算 region,避免省分布落后
|
||||
orderDailyStatComputeService.recomputeRegionDay(
|
||||
message.getCompanyId(),
|
||||
message.getShopId(),
|
||||
statDate,
|
||||
message.getPlatformCode());
|
||||
calcTaskService.recordIncAppliedThrottled(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getOrderId(), false);
|
||||
log.info("BI inc delta 已累加 shopId={} statDate={} orderId={}",
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 店铺×省×日订单汇聚。province 为规范化全称;净销售由读侧 deal − refund 推导。
|
||||
*/
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_region")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(
|
||||
name = "uk_company_shop_province_date",
|
||||
def = "{'companyId':1,'shopId':1,'province':1,'statDate':1}",
|
||||
unique = true),
|
||||
@CompoundIndex(name = "idx_company_date", def = "{'companyId':1,'statDate':1}"),
|
||||
@CompoundIndex(name = "idx_company_shop_date", def = "{'companyId':1,'shopId':1,'statDate':1}")
|
||||
})
|
||||
public class BiOrderStatDailyRegionDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private LocalDate statDate;
|
||||
|
||||
/** 规范化省名(与 DataV geoJSON 对齐;未知为 {@code __UNKNOWN__}) */
|
||||
private String province;
|
||||
|
||||
private BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
private Integer dealOrderCount = 0;
|
||||
private Integer dealQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private Integer refundOrderCount = 0;
|
||||
private Integer refundQuantitySum = 0;
|
||||
private BigDecimal serviceFee = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+95
@@ -4,9 +4,11 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyRegionDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
@@ -38,6 +40,99 @@ public class BiOrderStatQueryService {
|
||||
return repository.listShopDocs(companyId, shopIds, start, end);
|
||||
}
|
||||
|
||||
/** 区间内区域(省)日文档。 */
|
||||
public List<BiOrderStatDailyRegionDoc> listRegionDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listRegionDocs(companyId, shopIds, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区域日文档按省合并区间;净销售三件套 = 成交 − 退款。
|
||||
* 默认跳过 {@link BiRegionNormalizer#UNKNOWN}(地图/排行不展示未知省)。
|
||||
*/
|
||||
public List<ProvincePeriodMetrics> sumRegionDocsByProvince(List<BiOrderStatDailyRegionDoc> docs) {
|
||||
return sumRegionDocsByProvince(docs, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param skipUnknown true 时过滤 {@link BiRegionNormalizer#UNKNOWN}
|
||||
*/
|
||||
public List<ProvincePeriodMetrics> sumRegionDocsByProvince(List<BiOrderStatDailyRegionDoc> docs,
|
||||
boolean skipUnknown) {
|
||||
Map<String, ProvincePeriodMetrics> merged = new HashMap<>();
|
||||
if (docs == null) {
|
||||
return List.of();
|
||||
}
|
||||
for (BiOrderStatDailyRegionDoc doc : docs) {
|
||||
if (doc == null) {
|
||||
continue;
|
||||
}
|
||||
String province = doc.getProvince() != null ? doc.getProvince() : BiRegionNormalizer.UNKNOWN;
|
||||
if (skipUnknown && BiRegionNormalizer.isUnknown(province)) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal deal = nz(doc.getDealAmount());
|
||||
BigDecimal refund = nz(doc.getRefundAmount());
|
||||
int dealOrders = nzInt(doc.getDealOrderCount());
|
||||
int refundOrders = nzInt(doc.getRefundOrderCount());
|
||||
int dealQty = nzInt(doc.getDealQuantitySum());
|
||||
int refundQty = nzInt(doc.getRefundQuantitySum());
|
||||
ProvincePeriodMetrics cur = merged.get(province);
|
||||
if (cur == null) {
|
||||
merged.put(province, new ProvincePeriodMetrics(
|
||||
province,
|
||||
netAmount(deal, refund),
|
||||
refund,
|
||||
nz(doc.getProductCost()),
|
||||
nz(doc.getFreightCost()),
|
||||
nz(doc.getOtherCost()),
|
||||
netCount(dealOrders, refundOrders),
|
||||
netCount(dealQty, refundQty),
|
||||
deal, dealOrders, dealQty,
|
||||
refundOrders, refundQty));
|
||||
} else {
|
||||
BigDecimal nextDeal = cur.dealAmount().add(deal);
|
||||
BigDecimal nextRefund = cur.refundAmount().add(refund);
|
||||
int nextDealOrders = cur.dealOrderCount() + dealOrders;
|
||||
int nextRefundOrders = cur.refundOrderCount() + refundOrders;
|
||||
int nextDealQty = cur.dealQuantitySum() + dealQty;
|
||||
int nextRefundQty = cur.refundQuantitySum() + refundQty;
|
||||
merged.put(province, new ProvincePeriodMetrics(
|
||||
province,
|
||||
netAmount(nextDeal, nextRefund),
|
||||
nextRefund,
|
||||
cur.productCost().add(nz(doc.getProductCost())),
|
||||
cur.freightCost().add(nz(doc.getFreightCost())),
|
||||
cur.otherCost().add(nz(doc.getOtherCost())),
|
||||
netCount(nextDealOrders, nextRefundOrders),
|
||||
netCount(nextDealQty, nextRefundQty),
|
||||
nextDeal, nextDealOrders, nextDealQty,
|
||||
nextRefundOrders, nextRefundQty));
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(merged.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 省区间指标。{@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套。
|
||||
*/
|
||||
public record ProvincePeriodMetrics(
|
||||
String province,
|
||||
BigDecimal salesAmount,
|
||||
BigDecimal refundAmount,
|
||||
BigDecimal productCost,
|
||||
BigDecimal freightCost,
|
||||
BigDecimal otherCost,
|
||||
int salesOrderCount,
|
||||
int salesQuantitySum,
|
||||
BigDecimal dealAmount,
|
||||
int dealOrderCount,
|
||||
int dealQuantitySum,
|
||||
int refundOrderCount,
|
||||
int refundQuantitySum
|
||||
) {
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listProductDocs(companyId, shopIds, start, end);
|
||||
|
||||
+32
-1
@@ -11,6 +11,7 @@ import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSkuStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyRegionDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
|
||||
@@ -45,6 +46,20 @@ public class BiOrderStatDailyRepository {
|
||||
return mongoTemplate.find(q, BiOrderStatDailyShopDoc.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间内区域(省)日文档。{@code shopIds} 为空返回空列表。
|
||||
*/
|
||||
public List<BiOrderStatDailyRegionDoc> listRegionDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || shopIds == null || shopIds.isEmpty() || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").in(shopIds)
|
||||
.and("statDate").gte(start).lte(end));
|
||||
return mongoTemplate.find(q, BiOrderStatDailyRegionDoc.class);
|
||||
}
|
||||
|
||||
/** 区间内商品日文档(闭区间)。shopIds 为空返回空列表。 */
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
@@ -116,7 +131,8 @@ public class BiOrderStatDailyRepository {
|
||||
|
||||
public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc,
|
||||
List<BiOrderStatDailyProductDoc> products,
|
||||
List<BiOrderStatDailySkuDoc> skus) {
|
||||
List<BiOrderStatDailySkuDoc> skus,
|
||||
List<BiOrderStatDailyRegionDoc> regions) {
|
||||
Long companyId = shopDoc.getCompanyId();
|
||||
Long shopId = shopDoc.getShopId();
|
||||
LocalDate statDate = shopDoc.getStatDate();
|
||||
@@ -141,6 +157,21 @@ public class BiOrderStatDailyRepository {
|
||||
if (skus != null && !skus.isEmpty()) {
|
||||
mongoTemplate.insertAll(skus);
|
||||
}
|
||||
replaceRegionDay(companyId, shopId, statDate, regions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换某店某日全部区域日文档(先删后插)。仅写 region 集合,供 INC 后轻量重算。
|
||||
*/
|
||||
public void replaceRegionDay(Long companyId, Long shopId, LocalDate statDate,
|
||||
List<BiOrderStatDailyRegionDoc> regions) {
|
||||
Query dayQ = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
mongoTemplate.remove(dayQ, BiOrderStatDailyRegionDoc.class);
|
||||
if (regions != null && !regions.isEmpty()) {
|
||||
mongoTemplate.insertAll(regions);
|
||||
}
|
||||
}
|
||||
|
||||
/** 将转换侧算出的增量累加到日文档(无文档则按 delta 新建)。 */
|
||||
|
||||
+81
-14
@@ -8,9 +8,11 @@ import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyRegionDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.BiRegionNormalizer;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.OrderItemCostResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
@@ -114,6 +116,19 @@ public class OrderDailyStatComputeService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅重算并替换某店某日的区域日文档(扫单写 region,不动 shop/product/sku)。
|
||||
* 供 INC delta 成功后补齐省维;调用方须已持有同店同日计算锁。
|
||||
*/
|
||||
public void recomputeRegionDay(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
|
||||
Instant now = Instant.now();
|
||||
List<BiOrderStatDailyRegionDoc> regions = buildRegionDocs(agg, null, now, "INC");
|
||||
repository.replaceRegionDay(companyId, shopId, statDate, regions);
|
||||
log.info("BI 区域日重算完成 companyId={} shopId={} statDate={} provinces={}",
|
||||
companyId, shopId, statDate, regions.size());
|
||||
}
|
||||
|
||||
private DayAgg aggregateDay(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
LocalDateTime start = statDate.atStartOfDay();
|
||||
LocalDateTime end = statDate.plusDays(1).atStartOfDay();
|
||||
@@ -151,6 +166,7 @@ public class OrderDailyStatComputeService {
|
||||
Metric shop = new Metric();
|
||||
Map<String, Metric> productMap = new HashMap<>();
|
||||
Map<String, Metric> skuMap = new HashMap<>();
|
||||
Map<String, Metric> regionMap = new HashMap<>();
|
||||
Map<String, DimKey> productKeys = new HashMap<>();
|
||||
Map<String, DimKey> skuKeys = new HashMap<>();
|
||||
|
||||
@@ -168,17 +184,26 @@ public class OrderDailyStatComputeService {
|
||||
}
|
||||
BigDecimal received = OrderStatusStatSets.receivedAmount(order);
|
||||
BigDecimal fee = deal ? nz(order.getServiceFee()) : BigDecimal.ZERO;
|
||||
String province = BiRegionNormalizer.normalize(order.getProvince());
|
||||
Metric region = regionMap.computeIfAbsent(province, k -> new Metric());
|
||||
|
||||
if (deal) {
|
||||
shop.dealAmount = shop.dealAmount.add(received);
|
||||
shop.dealOrderCount++;
|
||||
shop.dealQuantitySum += qtySum;
|
||||
shop.serviceFee = shop.serviceFee.add(fee);
|
||||
region.dealAmount = region.dealAmount.add(received);
|
||||
region.dealOrderCount++;
|
||||
region.dealQuantitySum += qtySum;
|
||||
region.serviceFee = region.serviceFee.add(fee);
|
||||
}
|
||||
if (refund) {
|
||||
shop.refundAmount = shop.refundAmount.add(received);
|
||||
shop.refundOrderCount++;
|
||||
shop.refundQuantitySum += qtySum;
|
||||
region.refundAmount = region.refundAmount.add(received);
|
||||
region.refundOrderCount++;
|
||||
region.refundQuantitySum += qtySum;
|
||||
}
|
||||
|
||||
Set<String> countedProductDeal = new HashSet<>();
|
||||
@@ -195,6 +220,9 @@ public class OrderDailyStatComputeService {
|
||||
int qty = OrderStatusStatSets.quantity(item);
|
||||
BigDecimal lineReceived = allocateLine(received, item, items);
|
||||
BigDecimal lineFee = deal ? allocateLine(fee, item, items) : BigDecimal.ZERO;
|
||||
BigDecimal linePc = lineProductCost(order, item, stat, unitCostBySku);
|
||||
BigDecimal lineFc = lineFreightCost(order, item, stat, unitCostBySku);
|
||||
BigDecimal lineOc = lineOtherCost(order, item, stat, unitCostBySku);
|
||||
|
||||
String pk = companyId + ":" + shopId + ":" + productId;
|
||||
Metric pm = productMap.computeIfAbsent(pk, k -> new Metric());
|
||||
@@ -214,9 +242,9 @@ public class OrderDailyStatComputeService {
|
||||
pm.refundOrderCount++;
|
||||
}
|
||||
}
|
||||
pm.productCost = pm.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
pm.freightCost = pm.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
pm.otherCost = pm.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
pm.productCost = pm.productCost.add(linePc);
|
||||
pm.freightCost = pm.freightCost.add(lineFc);
|
||||
pm.otherCost = pm.otherCost.add(lineOc);
|
||||
|
||||
String sk = companyId + ":" + shopId + ":" + skuId;
|
||||
Metric sm = skuMap.computeIfAbsent(sk, k -> new Metric());
|
||||
@@ -236,13 +264,16 @@ public class OrderDailyStatComputeService {
|
||||
sm.refundOrderCount++;
|
||||
}
|
||||
}
|
||||
sm.productCost = sm.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
sm.freightCost = sm.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
sm.otherCost = sm.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
sm.productCost = sm.productCost.add(linePc);
|
||||
sm.freightCost = sm.freightCost.add(lineFc);
|
||||
sm.otherCost = sm.otherCost.add(lineOc);
|
||||
|
||||
shop.productCost = shop.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
shop.freightCost = shop.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
shop.otherCost = shop.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
shop.productCost = shop.productCost.add(linePc);
|
||||
shop.freightCost = shop.freightCost.add(lineFc);
|
||||
shop.otherCost = shop.otherCost.add(lineOc);
|
||||
region.productCost = region.productCost.add(linePc);
|
||||
region.freightCost = region.freightCost.add(lineFc);
|
||||
region.otherCost = region.otherCost.add(lineOc);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +282,8 @@ public class OrderDailyStatComputeService {
|
||||
platform = orders.get(0).getPlatformCode();
|
||||
}
|
||||
|
||||
return new DayAgg(companyId, shopId, statDate, platform, shop, productMap, productKeys, skuMap, skuKeys);
|
||||
return new DayAgg(companyId, shopId, statDate, platform, shop,
|
||||
productMap, productKeys, skuMap, skuKeys, regionMap);
|
||||
}
|
||||
|
||||
private void persist(DayAgg agg, Instant snapshotTime, String mode) {
|
||||
@@ -297,9 +329,30 @@ public class OrderDailyStatComputeService {
|
||||
skus.add(doc);
|
||||
}
|
||||
|
||||
repository.replaceShopDay(shopDoc, products, skus);
|
||||
log.info("BI 日汇聚完成 mode={} companyId={} shopId={} statDate={} ordersShopDeal={}",
|
||||
mode, agg.companyId(), agg.shopId(), agg.statDate(), agg.shop().dealOrderCount);
|
||||
List<BiOrderStatDailyRegionDoc> regions = buildRegionDocs(agg, snapshotTime, now, mode);
|
||||
repository.replaceShopDay(shopDoc, products, skus, regions);
|
||||
log.info("BI 日汇聚完成 mode={} companyId={} shopId={} statDate={} ordersShopDeal={} provinces={}",
|
||||
mode, agg.companyId(), agg.shopId(), agg.statDate(),
|
||||
agg.shop().dealOrderCount, regions.size());
|
||||
}
|
||||
|
||||
private static List<BiOrderStatDailyRegionDoc> buildRegionDocs(
|
||||
DayAgg agg, Instant snapshotTime, Instant computedAt, String mode) {
|
||||
List<BiOrderStatDailyRegionDoc> regions = new ArrayList<>();
|
||||
for (Map.Entry<String, Metric> e : agg.regionMap().entrySet()) {
|
||||
BiOrderStatDailyRegionDoc doc = new BiOrderStatDailyRegionDoc();
|
||||
doc.setCompanyId(agg.companyId());
|
||||
doc.setShopId(agg.shopId());
|
||||
doc.setPlatformCode(agg.platformCode());
|
||||
doc.setStatDate(agg.statDate());
|
||||
doc.setProvince(e.getKey());
|
||||
applyMetric(doc, e.getValue());
|
||||
doc.setDbSnapshotTime(snapshotTime);
|
||||
doc.setComputedAt(computedAt);
|
||||
doc.setComputeMode(mode);
|
||||
regions.add(doc);
|
||||
}
|
||||
return regions;
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) {
|
||||
@@ -341,6 +394,19 @@ public class OrderDailyStatComputeService {
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyRegionDoc doc, Metric m) {
|
||||
doc.setDealAmount(m.dealAmount);
|
||||
doc.setDealOrderCount(m.dealOrderCount);
|
||||
doc.setDealQuantitySum(m.dealQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setRefundOrderCount(m.refundOrderCount);
|
||||
doc.setRefundQuantitySum(m.refundQuantitySum);
|
||||
doc.setServiceFee(m.serviceFee);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
/** 按行金额占比分摊订单实收;无行金额则均分。 */
|
||||
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
|
||||
BigDecimal totalLine = BigDecimal.ZERO;
|
||||
@@ -415,6 +481,7 @@ public class OrderDailyStatComputeService {
|
||||
Map<String, Metric> productMap,
|
||||
Map<String, DimKey> productKeys,
|
||||
Map<String, Metric> skuMap,
|
||||
Map<String, DimKey> skuKeys) {
|
||||
Map<String, DimKey> skuKeys,
|
||||
Map<String, Metric> regionMap) {
|
||||
}
|
||||
}
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单收货省名规范化:统一为 DataV 省级 geoJSON 全称,供区域日汇聚与地图着色对齐。
|
||||
* <p>
|
||||
* 空/无法识别 → {@link #UNKNOWN}。
|
||||
*/
|
||||
public final class BiRegionNormalizer {
|
||||
|
||||
/** 空或无法映射的省份占位键 */
|
||||
public static final String UNKNOWN = "__UNKNOWN__";
|
||||
|
||||
private static final Map<String, String> ALIAS_TO_FULL = buildAliasMap();
|
||||
|
||||
private BiRegionNormalizer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将渠道侧省名规范为地图全称;空白或未知返回 {@link #UNKNOWN}。
|
||||
*/
|
||||
public static String normalize(String raw) {
|
||||
if (raw == null) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
String s = raw.trim();
|
||||
if (s.isEmpty()) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
// 去掉常见空白与全角空格
|
||||
s = s.replace('\u3000', ' ').replace(" ", "");
|
||||
String hit = ALIAS_TO_FULL.get(s);
|
||||
if (hit != null) {
|
||||
return hit;
|
||||
}
|
||||
// 英文忽略大小写再试一次(偶发 HK / Beijing)
|
||||
hit = ALIAS_TO_FULL.get(s.toLowerCase(Locale.ROOT));
|
||||
return hit != null ? hit : UNKNOWN;
|
||||
}
|
||||
|
||||
/** 是否为未知省占位 */
|
||||
public static boolean isUnknown(String province) {
|
||||
return UNKNOWN.equals(province);
|
||||
}
|
||||
|
||||
private static Map<String, String> buildAliasMap() {
|
||||
Map<String, String> m = new LinkedHashMap<>();
|
||||
put(m, "北京市", "北京", "北京省", "beijing");
|
||||
put(m, "天津市", "天津", "天津省", "tianjin");
|
||||
put(m, "河北省", "河北", "hebei");
|
||||
put(m, "山西省", "山西", "shanxi");
|
||||
put(m, "内蒙古自治区", "内蒙古", "内蒙古省", "内蒙", "neimenggu", "inner mongolia");
|
||||
put(m, "辽宁省", "辽宁", "liaoning");
|
||||
put(m, "吉林省", "吉林", "jilin");
|
||||
put(m, "黑龙江省", "黑龙江", "heilongjiang");
|
||||
put(m, "上海市", "上海", "上海省", "shanghai");
|
||||
put(m, "江苏省", "江苏", "jiangsu");
|
||||
put(m, "浙江省", "浙江", "zhejiang");
|
||||
put(m, "安徽省", "安徽", "anhui");
|
||||
put(m, "福建省", "福建", "fujian");
|
||||
put(m, "江西省", "江西", "jiangxi");
|
||||
put(m, "山东省", "山东", "shandong");
|
||||
put(m, "河南省", "河南", "henan");
|
||||
put(m, "湖北省", "湖北", "hubei");
|
||||
put(m, "湖南省", "湖南", "hunan");
|
||||
put(m, "广东省", "广东", "guangdong");
|
||||
put(m, "广西壮族自治区", "广西", "广西省", "广西自治区", "guangxi");
|
||||
put(m, "海南省", "海南", "hainan");
|
||||
put(m, "重庆市", "重庆", "重庆省", "chongqing");
|
||||
put(m, "四川省", "四川", "sichuan");
|
||||
put(m, "贵州省", "贵州", "guizhou");
|
||||
put(m, "云南省", "云南", "yunnan");
|
||||
put(m, "西藏自治区", "西藏", "西藏省", "xizang", "tibet");
|
||||
put(m, "陕西省", "陕西", "shaanxi");
|
||||
put(m, "甘肃省", "甘肃", "gansu");
|
||||
put(m, "青海省", "青海", "qinghai");
|
||||
put(m, "宁夏回族自治区", "宁夏", "宁夏省", "宁夏自治区", "ningxia");
|
||||
put(m, "新疆维吾尔自治区", "新疆", "新疆省", "新疆自治区", "xinjiang");
|
||||
put(m, "台湾省", "台湾", "taiwan");
|
||||
put(m, "香港特别行政区", "香港", "香港特区", "hongkong", "hong kong", "hk");
|
||||
put(m, "澳门特别行政区", "澳门", "澳门特区", "macao", "macau", "mo");
|
||||
return Map.copyOf(m);
|
||||
}
|
||||
|
||||
/** 标准全称自身 + 若干别名都映射到 full */
|
||||
private static void put(Map<String, String> m, String full, String... aliases) {
|
||||
m.put(full, full);
|
||||
if (aliases != null) {
|
||||
for (String a : aliases) {
|
||||
if (a != null && !a.isBlank()) {
|
||||
m.put(a.trim(), full);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.dto.RegionOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo.RegionOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.service.BiRegionOverviewService;
|
||||
|
||||
/**
|
||||
* 区域销量概览:省级净销售(地图 + 排行)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/region")
|
||||
public class BiRegionOverviewController {
|
||||
|
||||
private final BiRegionOverviewService biRegionOverviewService;
|
||||
|
||||
public BiRegionOverviewController(BiRegionOverviewService biRegionOverviewService) {
|
||||
this.biRegionOverviewService = biRegionOverviewService;
|
||||
}
|
||||
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询区域销量概览", allowSuper = true)
|
||||
public ApiResponse<RegionOverviewVO> overview(@Valid @RequestBody RegionOverviewQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取区域销量成功", biRegionOverviewService.overview(queryDTO));
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 区域销量概览查询:日期 + 可选平台/店铺筛选(与工作台筛选对齐)。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class RegionOverviewQueryDTO {
|
||||
|
||||
@NotEmpty(message = "日期范围不能为空")
|
||||
@Size(min = 1, max = 2, message = "日期范围必须包含 1~2 个日期")
|
||||
private List<LocalDate> dateRange;
|
||||
|
||||
/** 平台代码,不传表示全平台 */
|
||||
private String platformCode;
|
||||
|
||||
/** 店铺 ID,不传表示当前筛选下全部门店 */
|
||||
private Long shopId;
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 区域销量概览:省级净销售列表。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RegionOverviewVO {
|
||||
|
||||
private List<RegionProvinceRowVO> provinces;
|
||||
|
||||
/** 查询区间开始 */
|
||||
private String startDate;
|
||||
|
||||
/** 查询区间结束 */
|
||||
private String endDate;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 省级净销售汇总行(地图色阶 + 排行)。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class RegionProvinceRowVO {
|
||||
|
||||
/** 规范化省名,与 DataV geoJSON 对齐 */
|
||||
private String province;
|
||||
|
||||
/** 净销售额(元)= 成交 − 退款 */
|
||||
private BigDecimal salesAmount;
|
||||
|
||||
/** 净销量(件) */
|
||||
private Integer salesQuantitySum;
|
||||
|
||||
/** 净销售单量 */
|
||||
private Integer salesOrderCount;
|
||||
|
||||
/** 退款额(元) */
|
||||
private BigDecimal refundAmount;
|
||||
|
||||
/** 成交额(元) */
|
||||
private BigDecimal dealAmount;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.dto.RegionOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo.RegionOverviewVO;
|
||||
|
||||
/**
|
||||
* 区域销量概览:Mongo 省日汇聚按省 rollup。
|
||||
*/
|
||||
public interface BiRegionOverviewService {
|
||||
|
||||
RegionOverviewVO overview(RegionOverviewQueryDTO queryDTO);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.regionoverview.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.dto.RegionOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo.RegionOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.model.vo.RegionProvinceRowVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.regionoverview.service.BiRegionOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 区域销量:按当前公司店铺筛选读 Mongo 省日文档,再按省汇总净销售。
|
||||
*/
|
||||
@Service
|
||||
public class BiRegionOverviewServiceImpl implements BiRegionOverviewService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopService shopService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
|
||||
public BiRegionOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
BiOrderStatQueryService orderStatQueryService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RegionOverviewVO overview(RegionOverviewQueryDTO queryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
DateRange range = parseDateRange(queryDTO);
|
||||
List<ShopPO> shops = loadFilteredShops(companyId, queryDTO.getPlatformCode(), queryDTO.getShopId());
|
||||
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
|
||||
if (shopIds.isEmpty()) {
|
||||
return empty(range);
|
||||
}
|
||||
|
||||
var docs = orderStatQueryService.listRegionDocs(
|
||||
companyId, shopIds, range.start(), range.end());
|
||||
List<RegionProvinceRowVO> rows = orderStatQueryService.sumRegionDocsByProvince(docs).stream()
|
||||
.map(m -> RegionProvinceRowVO.builder()
|
||||
.province(m.province())
|
||||
.salesAmount(nz(m.salesAmount()))
|
||||
.salesQuantitySum(m.salesQuantitySum())
|
||||
.salesOrderCount(m.salesOrderCount())
|
||||
.refundAmount(nz(m.refundAmount()))
|
||||
.dealAmount(nz(m.dealAmount()))
|
||||
.build())
|
||||
.sorted(Comparator.comparing(RegionProvinceRowVO::getSalesAmount,
|
||||
Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.toList();
|
||||
|
||||
return RegionOverviewVO.builder()
|
||||
.provinces(rows)
|
||||
.startDate(range.start().toString())
|
||||
.endDate(range.end().toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
private RegionOverviewVO empty(DateRange range) {
|
||||
return RegionOverviewVO.builder()
|
||||
.provinces(List.of())
|
||||
.startDate(range.start().toString())
|
||||
.endDate(range.end().toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<ShopPO> loadFilteredShops(Long companyId, String platformCode, Long shopId) {
|
||||
if (shopId != null) {
|
||||
ShopPO one = shopService.getById(shopId);
|
||||
if (one == null || !companyId.equals(one.getCompanyId())) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
if (platformCode != null && !platformCode.isBlank()
|
||||
&& one.getPlatformCode() != null && !platformCode.equals(one.getPlatformCode())) {
|
||||
throw new BusinessException("店铺与所选平台不一致");
|
||||
}
|
||||
return List.of(one);
|
||||
}
|
||||
LambdaQueryWrapper<ShopPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ShopPO::getCompanyId, companyId);
|
||||
if (platformCode != null && !platformCode.isBlank()) {
|
||||
w.eq(ShopPO::getPlatformCode, platformCode.trim());
|
||||
}
|
||||
return shopService.list(w);
|
||||
}
|
||||
|
||||
private static DateRange parseDateRange(RegionOverviewQueryDTO queryDTO) {
|
||||
List<LocalDate> dates = queryDTO.getDateRange();
|
||||
if (dates == null || dates.isEmpty()) {
|
||||
throw new BusinessException("日期范围不能为空");
|
||||
}
|
||||
LocalDate start = dates.get(0);
|
||||
LocalDate end = dates.size() >= 2 && dates.get(1) != null ? dates.get(1) : start;
|
||||
if (start == null) {
|
||||
throw new BusinessException("开始日期不能为空");
|
||||
}
|
||||
if (end.isBefore(start)) {
|
||||
LocalDate tmp = start;
|
||||
start = end;
|
||||
end = tmp;
|
||||
}
|
||||
return new DateRange(start, end);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private record DateRange(LocalDate start, LocalDate end) {
|
||||
}
|
||||
}
|
||||
-21
@@ -10,8 +10,6 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
|
||||
/**
|
||||
* BI 工作台查询:订单指标来自 Mongo 日汇聚,推广/刷单来自 MySQL。
|
||||
@@ -31,23 +29,4 @@ public class BiWorkbenchController {
|
||||
public ApiResponse<WorkbenchFinanceSliceVO> finance(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取经营概览成功", biWorkbenchService.financeSlice(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/multi-analysis")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台多维分析", allowSuper = true)
|
||||
public ApiResponse<WorkbenchMultiAnalysisPanelVO> multiAnalysis(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取多维分析成功", biWorkbenchService.multiAnalysis(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/sales-rank")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台销售额排行", allowSuper = true)
|
||||
public ApiResponse<WorkbenchMultiAnalysisPanelVO> salesRank(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取销售额排行成功", biWorkbenchService.salesRank(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/period-compare/slice")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台区间对比", allowSuper = true)
|
||||
public ApiResponse<WorkbenchPeriodCompareSliceVO> periodCompareSlice(
|
||||
@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取区间对比数据成功", biWorkbenchService.periodCompareSlice(queryDTO));
|
||||
}
|
||||
}
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 金额字段为「元」保留两位小数;前端可自行换算为「万」展示。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchDimRowVO {
|
||||
|
||||
private String key;
|
||||
|
||||
private String name;
|
||||
|
||||
private BigDecimal salesYuan;
|
||||
|
||||
private BigDecimal grossProfitYuan;
|
||||
|
||||
private BigDecimal netProfitYuan;
|
||||
|
||||
private BigDecimal refundYuan;
|
||||
|
||||
private BigDecimal grossMarginPct;
|
||||
|
||||
private BigDecimal netMarginPct;
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchMultiAnalysisPanelVO {
|
||||
|
||||
private List<WorkbenchDimRowVO> platform;
|
||||
|
||||
private List<WorkbenchDimRowVO> shop;
|
||||
|
||||
private List<WorkbenchDimRowVO> category;
|
||||
|
||||
private List<WorkbenchDimRowVO> product;
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 工作台「区间对比」单段日期聚合:与底部店铺汇总表「合计」行同源({@link CompanyOverviewVO.ShopSummary})。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchPeriodCompareSliceVO {
|
||||
|
||||
private LocalDate startDate;
|
||||
|
||||
private LocalDate endDate;
|
||||
|
||||
private CompanyOverviewVO.ShopSummary total;
|
||||
}
|
||||
-8
@@ -4,8 +4,6 @@ import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
|
||||
/**
|
||||
* BI 工作台:读 Mongo 订单日汇聚 + MySQL 推广/刷单。
|
||||
@@ -14,12 +12,6 @@ public interface BiWorkbenchService {
|
||||
|
||||
WorkbenchFinanceSliceVO financeSlice(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchMultiAnalysisPanelVO multiAnalysis(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchMultiAnalysisPanelVO salesRank(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchPeriodCompareSliceVO periodCompareSlice(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
/** 与 finance 四表同口径,供导出使用 */
|
||||
CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto);
|
||||
}
|
||||
|
||||
+5
-267
@@ -9,20 +9,13 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStat
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchDimRowVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinancePanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
@@ -38,11 +31,9 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -50,14 +41,11 @@ import java.util.stream.Collectors;
|
||||
* <p>
|
||||
* 口径约定:
|
||||
* <ul>
|
||||
* <li>「净销售额、成本、退款、多维行、趋势」等:Mongo 存成交/退款分桶,读侧净销售 = 成交 − 退款;
|
||||
* <li>「净销售额、成本、退款、趋势」等:Mongo 存成交/退款分桶,读侧净销售 = 成交 − 退款;
|
||||
* 成交不含已取消/未知;成本按状态开关计入。</li>
|
||||
* <li>「成交金额」为同店铺、同时间范围内<strong>全部订单状态</strong>的商家实收合计(由汇总表 KPI 提供)。</li>
|
||||
* <li>推广费、刷单费为区间汇总;多维行与趋势中的「净利润」按销售额占比将区间推广、刷单、税额<strong>分摊</strong>到各维度或各日,
|
||||
* 与 {@link #totalsFromOrderRows} 得到的区间总毛利润、总税额自洽。</li>
|
||||
* <li>「成交金额」为同店铺、同时间范围内成交状态商家实收合计。</li>
|
||||
* <li>推广费、刷单费为区间汇总;趋势中的「净利润」按销售额占比将区间推广、刷单、税额分摊到各日。</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* 分 Tab 输出:{@link #financeSlice}、{@link #multiAnalysis}、{@link #salesRank}。
|
||||
*/
|
||||
@Service
|
||||
public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
@@ -70,8 +58,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopService shopService;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ProductMapper productMapper;
|
||||
private final CategoryService categoryService;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
private final BiWorkbenchFeeLoader feeLoader;
|
||||
@@ -79,16 +65,12 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
public BiWorkbenchServiceImpl(CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ProductMapper productMapper,
|
||||
CategoryService categoryService,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
BiOrderStatQueryService orderStatQueryService,
|
||||
BiWorkbenchFeeLoader feeLoader) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.productMapper = productMapper;
|
||||
this.categoryService = categoryService;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.feeLoader = feeLoader;
|
||||
@@ -120,52 +102,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return WorkbenchFinanceSliceVO.builder().finance(finance).summaryTables(summaryTables).build();
|
||||
}
|
||||
|
||||
/** 多维分析 Tab:SQL 聚合 + 内存 rollup */
|
||||
@Override
|
||||
public WorkbenchMultiAnalysisPanelVO multiAnalysis(WorkbenchQueryDTO queryDTO) {
|
||||
ShopContext ctx = resolveShopContext(queryDTO);
|
||||
if (ctx.shops().isEmpty() || ctx.stat().isUnionEmpty()) {
|
||||
return emptyMultiPanel();
|
||||
}
|
||||
SqlAggBundle agg = loadSqlAgg(ctx);
|
||||
Totals cur = totalsFromOrderRows(agg.orderRows(), agg.promoTotal(), agg.brushTotal(), ctx.taxRate());
|
||||
return buildMultiPanel(aggregateDimensionsFromSql(agg.orderRows(), ctx), cur);
|
||||
}
|
||||
|
||||
/** 销售额排行 Tab:与多维同源,按销售额降序 */
|
||||
@Override
|
||||
public WorkbenchMultiAnalysisPanelVO salesRank(WorkbenchQueryDTO queryDTO) {
|
||||
return buildSalesRankPanel(multiAnalysis(queryDTO));
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间对比单段:只返回该段日期下店铺维表「合计」行,供前端与另一段日期并排对比;不组装完整工作台。
|
||||
*/
|
||||
@Override
|
||||
public WorkbenchPeriodCompareSliceVO periodCompareSlice(WorkbenchQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
DateRange range = parseDateRange(queryDTO);
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
if (stat.isUnionEmpty()) {
|
||||
return WorkbenchPeriodCompareSliceVO.builder()
|
||||
.startDate(range.startDate()).endDate(range.endDate())
|
||||
.total(new CompanyOverviewVO.ShopSummary()).build();
|
||||
}
|
||||
List<ShopPO> shops = loadFilteredShops(companyId, queryDTO.getPlatformCode(), queryDTO.getShopId());
|
||||
ShopContext ctx = new ShopContext(taxRate, companyId, range, stat, shops,
|
||||
shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(),
|
||||
shops.stream().collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a)));
|
||||
SqlAggBundle agg = loadSqlAgg(ctx);
|
||||
CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, agg.orderRows(), agg.promotionRows(), agg.brushRows(),
|
||||
range.startDate(), range.endDate(), agg.skuRows());
|
||||
CompanyOverviewVO.ShopSummary total = bundle.getShopTable() != null && bundle.getShopTable().getTotal() != null
|
||||
? bundle.getShopTable().getTotal() : new CompanyOverviewVO.ShopSummary();
|
||||
return WorkbenchPeriodCompareSliceVO.builder()
|
||||
.startDate(range.startDate()).endDate(range.endDate()).total(total).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) {
|
||||
WorkbenchQueryDTO query = new WorkbenchQueryDTO();
|
||||
@@ -209,15 +145,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO emptyMultiPanel() {
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(Collections.emptyList())
|
||||
.shop(Collections.emptyList())
|
||||
.category(Collections.emptyList())
|
||||
.product(Collections.emptyList())
|
||||
.build();
|
||||
}
|
||||
|
||||
/** 解析筛选上下文:公司、税率、日期、店铺列表等 */
|
||||
private ShopContext resolveShopContext(WorkbenchQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
@@ -292,63 +219,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private DimensionAggMaps aggregateDimensionsFromSql(List<OverviewAggRows.ShopProductRow> rows, ShopContext ctx) {
|
||||
Map<String, Agg> platformAgg = new HashMap<>();
|
||||
Map<String, Agg> shopAgg = new HashMap<>();
|
||||
Map<String, Agg> categoryAgg = new HashMap<>();
|
||||
Map<String, Agg> productAgg = new HashMap<>();
|
||||
Set<Long> productIds = new HashSet<>();
|
||||
Set<Long> categoryIds = new HashSet<>();
|
||||
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
String platformKey = blankPlatformKey(row.getPlatformCode());
|
||||
long shopKey = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
long categoryKey = productId <= 0 ? -1L
|
||||
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
|
||||
platformAgg.computeIfAbsent(platformKey, k -> new Agg()).addFromAggRow(row);
|
||||
shopAgg.computeIfAbsent(String.valueOf(shopKey), k -> new Agg()).addFromAggRow(row);
|
||||
categoryAgg.computeIfAbsent(String.valueOf(categoryKey), k -> new Agg()).addFromAggRow(row);
|
||||
productAgg.computeIfAbsent(String.valueOf(productId), k -> new Agg()).addFromAggRow(row);
|
||||
if (productId > 0) {
|
||||
productIds.add(productId);
|
||||
}
|
||||
if (categoryKey > 0) {
|
||||
categoryIds.add(categoryKey);
|
||||
}
|
||||
}
|
||||
Map<Long, ProductPO> productById = loadProducts(productIds);
|
||||
Map<Long, String> categoryNames = loadCategoryNamesByIds(categoryIds);
|
||||
return new DimensionAggMaps(platformAgg, shopAgg, categoryAgg, productAgg,
|
||||
loadPlatformNames(ctx.shops()), categoryNames, productById, ctx.shopById());
|
||||
}
|
||||
|
||||
private Totals totalsFromOrderRows(List<OverviewAggRows.ShopProductRow> rows,
|
||||
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate) {
|
||||
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO;
|
||||
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
|
||||
BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
int orderCount = 0;
|
||||
int salesQty = 0;
|
||||
int dealOrderCount = 0;
|
||||
int dealQuantitySum = 0;
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
sales = sales.add(nz(row.getSalesAmount()));
|
||||
refund = refund.add(nz(row.getRefundAmount()));
|
||||
pc = pc.add(nz(row.getProductCost()));
|
||||
fc = fc.add(nz(row.getFreightCost()));
|
||||
oc = oc.add(nz(row.getOtherCost()));
|
||||
dealAmount = dealAmount.add(nz(row.getDealAmount()));
|
||||
orderCount += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
|
||||
salesQty += row.getSalesQuantitySum() != null ? row.getSalesQuantitySum().intValue() : 0;
|
||||
dealOrderCount += row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
|
||||
dealQuantitySum += row.getDealQuantitySum() != null ? row.getDealQuantitySum().intValue() : 0;
|
||||
}
|
||||
// 注意:商品粒度单量跨商品会重复计;多维/排行仅用销售额等金额字段,KPI 走店铺日文档
|
||||
return buildTotals(sales, refund, pc, fc, oc, promotion, brush, taxRate, orderCount, salesQty,
|
||||
dealAmount, dealOrderCount, dealQuantitySum);
|
||||
}
|
||||
|
||||
private Totals buildTotals(BigDecimal sales, BigDecimal refund, BigDecimal pc, BigDecimal fc, BigDecimal oc,
|
||||
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate,
|
||||
int orderCount, int salesQuantitySum,
|
||||
@@ -411,14 +281,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCategoryNamesByIds(Set<Long> categoryIds) {
|
||||
if (categoryIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().in(CategoryPO::getId, categoryIds))
|
||||
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
@@ -438,44 +300,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
}
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO buildMultiPanel(DimensionAggMaps aggs, Totals cur) {
|
||||
BigDecimal salesAllocBase = cur.totalSales();
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(buildDimRows(aggs.platformAgg(),
|
||||
k -> aggs.platformNames().getOrDefault(k, PlatformCode.labelOf(k)),
|
||||
salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.shop(buildDimRows(aggs.shopAgg(), k -> {
|
||||
ShopPO s = aggs.shopById().get(Long.parseLong(k));
|
||||
return s != null ? s.getName() : "未知店铺";
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.category(buildDimRows(aggs.categoryAgg(), k -> {
|
||||
if ("0".equals(k)) {
|
||||
return "未分类";
|
||||
}
|
||||
if ("-1".equals(k)) {
|
||||
return "其他品类";
|
||||
}
|
||||
return aggs.categoryNames().getOrDefault(Long.parseLong(k), "类目" + k);
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.product(buildDimRows(aggs.productAgg(), k -> {
|
||||
if (k.startsWith("-") || "0".equals(k)) {
|
||||
return "未匹配商品";
|
||||
}
|
||||
ProductPO p = aggs.productById().get(Long.parseLong(k));
|
||||
return p != null ? p.getName() : ("商品" + k);
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO buildSalesRankPanel(WorkbenchMultiAnalysisPanelVO multi) {
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(sortByDealAmountDesc(multi.getPlatform()))
|
||||
.shop(sortByDealAmountDesc(multi.getShop()))
|
||||
.category(sortByDealAmountDesc(multi.getCategory()))
|
||||
.product(sortByDealAmountDesc(multi.getProduct()))
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按公司 + 可选平台/单店筛选店铺列表;指定 {@code shopId} 时校验归属与平台一致性。
|
||||
*/
|
||||
@@ -499,22 +323,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return shopService.list(w);
|
||||
}
|
||||
|
||||
/** 按商品 id 批量加载主数据,供类目解析与商品名称展示 */
|
||||
private Map<Long, ProductPO> loadProducts(Iterable<Long> productIds) {
|
||||
List<Long> ids = new ArrayList<>();
|
||||
for (Long id : productIds) {
|
||||
if (id != null && id > 0) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
ids = ids.stream().distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
List<ProductPO> list = productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, ids));
|
||||
return list.stream().collect(Collectors.toMap(ProductPO::getId, p -> p, (a, b) -> a));
|
||||
}
|
||||
|
||||
/** 从店铺收集平台 code,映射为展示名称 */
|
||||
private Map<String, String> loadPlatformNames(List<ShopPO> shops) {
|
||||
return shops.stream()
|
||||
@@ -528,65 +336,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return platformCode != null && !platformCode.isBlank() ? platformCode : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 将「字符串 key → 聚合桶」转为多维表格行:每行毛利润 = 净销售额−成本;
|
||||
* 推广费、刷单费、税额均按该行净销售额占 {@code salesTotalCompany} 比例分摊;
|
||||
* 净利润 = 毛利润 − 分摊推广 − 分摊刷单 − 分摊税。
|
||||
*/
|
||||
private List<WorkbenchDimRowVO> buildDimRows(Map<String, Agg> aggs,
|
||||
java.util.function.Function<String, String> nameFn,
|
||||
BigDecimal salesTotalCompany,
|
||||
BigDecimal promoTotal,
|
||||
BigDecimal brushTotal,
|
||||
BigDecimal taxTotal) {
|
||||
List<WorkbenchDimRowVO> rows = new ArrayList<>();
|
||||
for (Map.Entry<String, Agg> e : aggs.entrySet()) {
|
||||
Agg a = e.getValue();
|
||||
if (a.sales.compareTo(BigDecimal.ZERO) <= 0 && a.refund.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal gross = a.sales.subtract(a.cost);
|
||||
BigDecimal promoB = allocShare(a.sales, salesTotalCompany, promoTotal);
|
||||
BigDecimal brushB = allocShare(a.sales, salesTotalCompany, brushTotal);
|
||||
BigDecimal taxB = allocShare(a.sales, salesTotalCompany.max(BigDecimal.ONE), taxTotal);
|
||||
if (salesTotalCompany.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
taxB = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal net = gross.subtract(promoB).subtract(brushB).subtract(taxB);
|
||||
|
||||
BigDecimal salesYuan = yuan2(a.sales);
|
||||
BigDecimal grossYuan = yuan2(gross);
|
||||
BigDecimal netYuan = yuan2(net);
|
||||
BigDecimal refundYuan = yuan2(a.refund);
|
||||
|
||||
BigDecimal grossMarginPct = safePct(gross, a.sales);
|
||||
BigDecimal netMarginPct = safePct(net, a.sales);
|
||||
|
||||
rows.add(WorkbenchDimRowVO.builder()
|
||||
.key(e.getKey())
|
||||
.name(nameFn.apply(e.getKey()))
|
||||
.salesYuan(salesYuan)
|
||||
.grossProfitYuan(grossYuan)
|
||||
.netProfitYuan(netYuan)
|
||||
.refundYuan(refundYuan)
|
||||
.grossMarginPct(grossMarginPct)
|
||||
.netMarginPct(netMarginPct)
|
||||
.build());
|
||||
}
|
||||
rows.sort(Comparator.comparing(WorkbenchDimRowVO::getSalesYuan, Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 按净销售额降序复制排序,用于销售额排行 */
|
||||
private List<WorkbenchDimRowVO> sortByDealAmountDesc(List<WorkbenchDimRowVO> in) {
|
||||
if (in == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return in.stream()
|
||||
.sorted(Comparator.comparing(WorkbenchDimRowVO::getSalesYuan, Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 比例分摊:{@code amount * part / total},四舍五入到 4 位小数;总额或金额为 0 时返回 0。
|
||||
* 用于将区间总推广、刷单、税额拆到各维度行或各日趋势点。
|
||||
@@ -602,7 +351,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 各平台净销售额占比:与多维分析「平台」维度同源订单聚合;分母为当前筛选下公司净销售额合计。
|
||||
* 各平台净销售额占比;分母为当前筛选下公司净销售额合计。
|
||||
*/
|
||||
private List<WorkbenchCostSliceVO> buildPlatformSalesSlices(Map<String, Agg> platformAgg,
|
||||
Map<String, String> platformNames,
|
||||
@@ -836,17 +585,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
private record ComparePeriodBundle(DateRange lastRange, DateRange yoyRange, Totals prev, Totals yoy) {
|
||||
}
|
||||
|
||||
/** 四维聚合桶 + 展示名称 */
|
||||
private record DimensionAggMaps(Map<String, Agg> platformAgg,
|
||||
Map<String, Agg> shopAgg,
|
||||
Map<String, Agg> categoryAgg,
|
||||
Map<String, Agg> productAgg,
|
||||
Map<String, String> platformNames,
|
||||
Map<Long, String> categoryNames,
|
||||
Map<Long, ProductPO> productById,
|
||||
Map<Long, ShopPO> shopById) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单时间段店铺财务 KPI 总量(与汇总表 + 推广/刷单区间一致)。
|
||||
*/
|
||||
@@ -872,7 +610,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
BigDecimal dealPiecePrice) {
|
||||
}
|
||||
|
||||
/** 多维或按日聚合用的累加桶:累计销售额、退款、成本 */
|
||||
/** 平台占比等聚合用的累加桶:累计销售额、退款、成本 */
|
||||
private static final class Agg {
|
||||
BigDecimal sales = BigDecimal.ZERO;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
|
||||
+6
-6
@@ -10,7 +10,7 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddGoodsPublishDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatAuthQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCostTemplateDetailQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatTemplateQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatRuleQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishLogisticsQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishShopCatQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishSpecIdCreateDTO;
|
||||
@@ -19,7 +19,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.Pdd
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddGoodsPublishResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatAuthVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCostTemplateDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatRuleVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishLogisticsPageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishParentSpecVO;
|
||||
@@ -68,11 +68,11 @@ public class PddGoodsPublishController {
|
||||
return ApiResponse.success("获取成功", publishService.getCostTemplateDetail(query));
|
||||
}
|
||||
|
||||
@PostMapping("/meta/cat-template")
|
||||
@PostMapping("/meta/cat-rule")
|
||||
@RequirePermission(value = "channel:pdd:goods:create", description = "创建拼多多商品", allowSuper = true)
|
||||
public ApiResponse<PddPublishCatTemplateVO> getCatTemplate(
|
||||
@Valid @RequestBody PddPublishCatTemplateQueryDTO query) {
|
||||
return ApiResponse.success("获取成功", publishService.getCatTemplate(query));
|
||||
public ApiResponse<PddPublishCatRuleVO> getCatRule(
|
||||
@Valid @RequestBody PddPublishCatRuleQueryDTO query) {
|
||||
return ApiResponse.success("获取成功", publishService.getCatRule(query));
|
||||
}
|
||||
|
||||
@PostMapping("/meta/specs")
|
||||
|
||||
+4
-1
@@ -3,8 +3,11 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 类目发布规则查询(pdd.goods.cat.rule.get)。
|
||||
*/
|
||||
@Data
|
||||
public class PddPublishCatTemplateQueryDTO {
|
||||
public class PddPublishCatRuleQueryDTO {
|
||||
|
||||
@NotNull(message = "渠道店铺ID不能为空")
|
||||
private Long pddShopId;
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 属性条件展示:父属性 refPid + 可选父属性值 vids。 */
|
||||
@Data
|
||||
public class PddPublishCatPropertyShowConditionVO {
|
||||
|
||||
private Long parentRefPid;
|
||||
private List<Long> parentVids;
|
||||
}
|
||||
+22
-8
@@ -4,22 +4,36 @@ import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 类目发布属性规则项(来自 cat.rule.get → goods_properties_rule.properties)。
|
||||
*/
|
||||
@Data
|
||||
public class PddPublishCatPropertyVO {
|
||||
|
||||
private Long templatePid;
|
||||
private String name;
|
||||
private String nameAlias;
|
||||
private Long refPid;
|
||||
private Long specId;
|
||||
private Long parentId;
|
||||
/** 销售属性对应的父规格 id */
|
||||
private Long parentSpecId;
|
||||
private Boolean required;
|
||||
private Boolean sale;
|
||||
private Integer controlType;
|
||||
private Integer feature;
|
||||
private Integer valueType;
|
||||
private String valueUnit;
|
||||
/** SKU 维度属性(发品时入参在 sku 下) */
|
||||
private Boolean sku;
|
||||
private Boolean important;
|
||||
private Boolean canNote;
|
||||
/**
|
||||
* 属性值类型:0 文本;1 数值;2 数值范围;3 二维乘积;4 三维乘积;
|
||||
* 5/6 年月日单/双;7/8 年月单/双;9 材质成分表。
|
||||
*/
|
||||
private Integer propertyValueType;
|
||||
private String maxValue;
|
||||
private String minValue;
|
||||
private Integer valuePrecision;
|
||||
/** 可选单位列表 */
|
||||
private List<String> valueUnits;
|
||||
private Integer inputMaxNum;
|
||||
private Integer chooseMaxNum;
|
||||
private Integer requiredRuleType;
|
||||
private String requiredRule;
|
||||
private List<PddPublishCatPropertyShowConditionVO> showCondition;
|
||||
private List<PddPublishCatPropertyValueVO> values;
|
||||
}
|
||||
|
||||
+2
-1
@@ -11,6 +11,7 @@ public class PddPublishCatPropertyValueVO {
|
||||
private String value;
|
||||
private Long specId;
|
||||
private String extendInfo;
|
||||
private Boolean parent;
|
||||
private List<Long> parentVids;
|
||||
private Integer groupId;
|
||||
private String groupName;
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 类目发布规则(属性规则 + SKU 规则摘要)。
|
||||
*/
|
||||
@Data
|
||||
public class PddPublishCatRuleVO {
|
||||
|
||||
/** 多个销售属性是否需要同时传 */
|
||||
private Boolean chooseAllQualifySpec;
|
||||
|
||||
/** 允许自定义的销售属性数量 */
|
||||
private Long inputMaxSpecNum;
|
||||
|
||||
/** 同商品下规格值加和上限(goods_sku_rule.spec_num_limit) */
|
||||
private Integer specNumLimit;
|
||||
|
||||
/** 团购价最高差倍率 */
|
||||
private Double priceRangeRatio;
|
||||
|
||||
private List<PddPublishCatPropertyVO> properties;
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class PddPublishCatTemplateVO {
|
||||
|
||||
private Long id;
|
||||
private Long maxSkuNum;
|
||||
private Long inputMaxSpecNum;
|
||||
private Long singleSpecValueNum;
|
||||
private Boolean singleItem;
|
||||
private List<PddPublishCatPropertyVO> properties;
|
||||
}
|
||||
-15
@@ -70,18 +70,6 @@ public class PddGoodsPublishJobRunnerImpl implements PddGoodsPublishJobRunner {
|
||||
}
|
||||
List<PddGoodsPublishJobItemPO> items = jobItemMapper.selectList(qw);
|
||||
|
||||
int success = job.getSuccessCount() == null ? 0 : job.getSuccessCount();
|
||||
int fail = onlyFailed ? 0 : (job.getFailCount() == null ? 0 : job.getFailCount());
|
||||
if (onlyFailed) {
|
||||
// 重试失败项:先把失败数扣回,下面按结果重算
|
||||
fail = 0;
|
||||
success = (job.getTotalCount() == null ? 0 : job.getTotalCount())
|
||||
- items.size();
|
||||
if (success < 0) {
|
||||
success = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (PddGoodsPublishJobItemPO item : items) {
|
||||
item.setStatus(PddGoodsPublishJobItemPO.STATUS_RUNNING);
|
||||
item.setErrorMessage(null);
|
||||
@@ -90,7 +78,6 @@ public class PddGoodsPublishJobRunnerImpl implements PddGoodsPublishJobRunner {
|
||||
PddGoodsPublishDraftPO draft = draftMapper.selectById(item.getDraftId());
|
||||
if (draft == null || !companyId.equals(draft.getCompanyId())) {
|
||||
markItemFailed(item, "草稿不存在");
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
draft.setStatus(PddGoodsPublishDraftPO.STATUS_PUBLISHING);
|
||||
@@ -109,7 +96,6 @@ public class PddGoodsPublishJobRunnerImpl implements PddGoodsPublishJobRunner {
|
||||
item.setErrorMessage(null);
|
||||
jobItemMapper.updateById(item);
|
||||
// status / commitId / goodsId 由 publish(systemDraftId) 回写
|
||||
success++;
|
||||
} catch (Exception e) {
|
||||
String msg = e.getMessage() == null ? "发布失败" : e.getMessage();
|
||||
if (msg.length() > 900) {
|
||||
@@ -119,7 +105,6 @@ public class PddGoodsPublishJobRunnerImpl implements PddGoodsPublishJobRunner {
|
||||
draft.setStatus(PddGoodsPublishDraftPO.STATUS_FAILED);
|
||||
draft.setLastError(msg);
|
||||
draftMapper.updateById(draft);
|
||||
fail++;
|
||||
log.warn("publish desk job item failed jobId={} draftId={}", jobId, item.getDraftId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddGoodsPublishDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatTemplateQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatRuleQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatAuthQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCostTemplateDetailQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishLogisticsQueryDTO;
|
||||
@@ -11,7 +11,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.Pdd
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishTransferImageDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddGoodsPublishResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatAuthVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatRuleVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCostTemplateDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishLogisticsPageVO;
|
||||
@@ -34,7 +34,7 @@ public interface PddGoodsPublishService {
|
||||
|
||||
PddPublishCostTemplateDetailVO getCostTemplateDetail(PddPublishCostTemplateDetailQueryDTO query);
|
||||
|
||||
PddPublishCatTemplateVO getCatTemplate(PddPublishCatTemplateQueryDTO query);
|
||||
PddPublishCatRuleVO getCatRule(PddPublishCatRuleQueryDTO query);
|
||||
|
||||
List<PddPublishParentSpecVO> listParentSpecs(PddPublishSpecQueryDTO query);
|
||||
|
||||
|
||||
+38
-24
@@ -16,7 +16,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.Pdd
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddGoodsPublishSkuPropertyDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatAuthQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCostTemplateDetailQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatTemplateQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishCatRuleQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishLogisticsQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishShopCatQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.publish.PddPublishSpecIdCreateDTO;
|
||||
@@ -29,7 +29,8 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddP
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatPropertyVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatPropertyValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCostTemplateDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatPropertyShowConditionVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatRuleVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishCatVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishLogisticsPageVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.vo.publish.PddPublishLogisticsTemplateVO;
|
||||
@@ -206,15 +207,15 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public PddPublishCatTemplateVO getCatTemplate(PddPublishCatTemplateQueryDTO query) {
|
||||
public PddPublishCatRuleVO getCatRule(PddPublishCatRuleQueryDTO query) {
|
||||
ShopAuth ctx = requireShopAuth(query.getPddShopId());
|
||||
try {
|
||||
var tpl = publishPopApiClient.getCatTemplate(ctx.mallId(), ctx.accessToken(), query.getCatId());
|
||||
return mapCatTemplate(tpl);
|
||||
var rule = publishPopApiClient.getCatRule(ctx.mallId(), ctx.accessToken(), query.getCatId());
|
||||
return mapCatRule(rule);
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw wrapPop("查询类目属性模板失败", e);
|
||||
throw wrapPop("查询类目发布规则失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -695,31 +696,43 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
|
||||
return parts.isEmpty() ? null : String.join(";", parts);
|
||||
}
|
||||
|
||||
private PddPublishCatTemplateVO mapCatTemplate(PddGoodsPublishPopApiClient.CatTemplate tpl) {
|
||||
PddPublishCatTemplateVO vo = new PddPublishCatTemplateVO();
|
||||
vo.setId(tpl.id());
|
||||
vo.setMaxSkuNum(tpl.maxSkuNum());
|
||||
vo.setInputMaxSpecNum(tpl.inputMaxSpecNum());
|
||||
vo.setSingleSpecValueNum(tpl.singleSpecValueNum());
|
||||
vo.setSingleItem(tpl.singleItem());
|
||||
private PddPublishCatRuleVO mapCatRule(PddGoodsPublishPopApiClient.CatRule rule) {
|
||||
PddPublishCatRuleVO vo = new PddPublishCatRuleVO();
|
||||
vo.setChooseAllQualifySpec(rule.chooseAllQualifySpec());
|
||||
vo.setInputMaxSpecNum(rule.inputMaxSpecNum());
|
||||
vo.setSpecNumLimit(rule.specNumLimit());
|
||||
vo.setPriceRangeRatio(rule.priceRangeRatio());
|
||||
List<PddPublishCatPropertyVO> props = new ArrayList<>();
|
||||
if (tpl.properties() != null) {
|
||||
for (var p : tpl.properties()) {
|
||||
if (rule.properties() != null) {
|
||||
for (var p : rule.properties()) {
|
||||
PddPublishCatPropertyVO pv = new PddPublishCatPropertyVO();
|
||||
pv.setTemplatePid(p.templatePid());
|
||||
pv.setName(p.name());
|
||||
pv.setNameAlias(p.nameAlias());
|
||||
pv.setRefPid(p.refPid());
|
||||
pv.setSpecId(p.specId());
|
||||
pv.setParentId(p.parentId());
|
||||
pv.setParentSpecId(p.parentSpecId());
|
||||
pv.setRequired(p.required());
|
||||
pv.setSale(p.sale());
|
||||
pv.setControlType(p.controlType());
|
||||
pv.setFeature(p.feature());
|
||||
pv.setValueType(p.valueType());
|
||||
pv.setValueUnit(p.valueUnit());
|
||||
pv.setSku(p.sku());
|
||||
pv.setImportant(p.important());
|
||||
pv.setCanNote(p.canNote());
|
||||
pv.setPropertyValueType(p.propertyValueType());
|
||||
pv.setMaxValue(p.maxValue());
|
||||
pv.setMinValue(p.minValue());
|
||||
pv.setValuePrecision(p.valuePrecision());
|
||||
pv.setValueUnits(p.valueUnits());
|
||||
pv.setInputMaxNum(p.inputMaxNum());
|
||||
pv.setChooseMaxNum(p.chooseMaxNum());
|
||||
pv.setRequiredRuleType(p.requiredRuleType());
|
||||
pv.setRequiredRule(p.requiredRule());
|
||||
List<PddPublishCatPropertyShowConditionVO> showConds = new ArrayList<>();
|
||||
if (p.showCondition() != null) {
|
||||
for (var c : p.showCondition()) {
|
||||
PddPublishCatPropertyShowConditionVO cv = new PddPublishCatPropertyShowConditionVO();
|
||||
cv.setParentRefPid(c.parentRefPid());
|
||||
cv.setParentVids(c.parentVids());
|
||||
showConds.add(cv);
|
||||
}
|
||||
}
|
||||
pv.setShowCondition(showConds);
|
||||
List<PddPublishCatPropertyValueVO> values = new ArrayList<>();
|
||||
if (p.values() != null) {
|
||||
for (var v : p.values()) {
|
||||
@@ -728,8 +741,9 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
|
||||
vv.setValue(v.value());
|
||||
vv.setSpecId(v.specId());
|
||||
vv.setExtendInfo(v.extendInfo());
|
||||
vv.setParent(v.parent());
|
||||
vv.setParentVids(v.parentVids());
|
||||
vv.setGroupId(v.groupId());
|
||||
vv.setGroupName(v.groupName());
|
||||
values.add(vv);
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -27,7 +27,11 @@ public final class PddPopApiTypes {
|
||||
/** 平台全量类目树(无需 accessToken) */
|
||||
public static final String GOODS_CATS_GET = "pdd.goods.cats.get";
|
||||
public static final String GOODS_LOGISTICS_TEMPLATE_GET = "pdd.goods.logistics.template.get";
|
||||
/** @deprecated 已废弃,请用 {@link #GOODS_CAT_RULE_GET} */
|
||||
@Deprecated
|
||||
public static final String GOODS_CAT_TEMPLATE_GET = "pdd.goods.cat.template.get";
|
||||
/** 类目商品发布规则(含属性,替代 cat.template.get) */
|
||||
public static final String GOODS_CAT_RULE_GET = "pdd.goods.cat.rule.get";
|
||||
public static final String GOODS_SPEC_GET = "pdd.goods.spec.get";
|
||||
public static final String GOODS_SPEC_ID_GET = "pdd.goods.spec.id.get";
|
||||
public static final String ONE_EXPRESS_COST_TEMPLATE = "pdd.one.express.cost.template";
|
||||
|
||||
+63
-38
@@ -4,7 +4,7 @@ import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAddRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsEditGoodsCommitRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsSubmitGoodsCommitRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsAuthorizationCatsRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatTemplateGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsCatRuleGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsImageUploadRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsLogisticsTemplateGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddGoodsSpecGetRequest;
|
||||
@@ -14,7 +14,7 @@ import com.pdd.pop.sdk.http.api.pop.response.PddGoodsAddResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsEditGoodsCommitResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsSubmitGoodsCommitResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsAuthorizationCatsResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsCatTemplateGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsCatRuleGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsImageUploadResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsLogisticsTemplateGetResponse;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsSpecGetResponse;
|
||||
@@ -32,7 +32,7 @@ import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品发布域 POP:类目/运费模板/属性模板/规格/传图/新增/平台草稿。
|
||||
* 商品发布域 POP:类目/运费模板/发布规则(属性)/规格/传图/新增/平台草稿。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -90,17 +90,17 @@ public class PddGoodsPublishPopApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
/** 叶子类目属性模板。 */
|
||||
public CatTemplate getCatTemplate(Long mallId, String accessToken, Long catId) throws Exception {
|
||||
/** 叶子类目发布规则(属性 + SKU 限制等)。 */
|
||||
public CatRule getCatRule(Long mallId, String accessToken, Long catId) throws Exception {
|
||||
if (catId == null) {
|
||||
throw new BusinessException("类目ID不能为空");
|
||||
}
|
||||
return invokeSupport.invoke(PddPopApiTypes.GOODS_CAT_TEMPLATE_GET, mallId, client -> {
|
||||
PddGoodsCatTemplateGetRequest request = new PddGoodsCatTemplateGetRequest();
|
||||
return invokeSupport.invoke(PddPopApiTypes.GOODS_CAT_RULE_GET, mallId, client -> {
|
||||
PddGoodsCatRuleGetRequest request = new PddGoodsCatRuleGetRequest();
|
||||
request.setCatId(catId);
|
||||
PddGoodsCatTemplateGetResponse response = client.syncInvoke(request, accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.GOODS_CAT_TEMPLATE_GET);
|
||||
return mapCatTemplate(response);
|
||||
PddGoodsCatRuleGetResponse response = client.syncInvoke(request, accessToken);
|
||||
invokeSupport.assertNoError(response, PddPopApiTypes.GOODS_CAT_RULE_GET);
|
||||
return mapCatRule(response);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -555,14 +555,17 @@ public class PddGoodsPublishPopApiClient {
|
||||
Collections.unmodifiableList(houseAreas));
|
||||
}
|
||||
|
||||
private CatTemplate mapCatTemplate(PddGoodsCatTemplateGetResponse response) {
|
||||
if (response == null || response.getOpenApiResponse() == null) {
|
||||
return new CatTemplate(null, null, null, null, null, List.of());
|
||||
private CatRule mapCatRule(PddGoodsCatRuleGetResponse response) {
|
||||
if (response == null || response.getCatRuleGetResponse() == null) {
|
||||
return new CatRule(null, null, null, null, List.of());
|
||||
}
|
||||
var body = response.getOpenApiResponse();
|
||||
var root = response.getCatRuleGetResponse();
|
||||
var propRule = root.getGoodsPropertiesRule();
|
||||
var skuRule = root.getGoodsSkuRule();
|
||||
|
||||
List<CatProperty> props = new ArrayList<>();
|
||||
if (body.getProperties() != null) {
|
||||
for (var p : body.getProperties()) {
|
||||
if (propRule != null && propRule.getProperties() != null) {
|
||||
for (var p : propRule.getProperties()) {
|
||||
if (p == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -572,35 +575,52 @@ public class PddGoodsPublishPopApiClient {
|
||||
if (v == null) {
|
||||
continue;
|
||||
}
|
||||
Integer groupId = v.getGroup() != null ? v.getGroup().getId() : null;
|
||||
String groupName = v.getGroup() != null ? v.getGroup().getName() : null;
|
||||
values.add(new CatPropertyValue(
|
||||
v.getVid(), v.getValue(), v.getSpecId(), v.getExtendInfo(),
|
||||
v.getIsParent(), v.getParentVids()));
|
||||
v.getParentVids(), groupId, groupName));
|
||||
}
|
||||
}
|
||||
List<CatPropertyShowCondition> showConds = new ArrayList<>();
|
||||
if (p.getShowCondition() != null) {
|
||||
for (var c : p.getShowCondition()) {
|
||||
if (c == null) {
|
||||
continue;
|
||||
}
|
||||
showConds.add(new CatPropertyShowCondition(c.getParentRefPid(), c.getParentVids()));
|
||||
}
|
||||
}
|
||||
List<String> units = p.getValueUnit() != null
|
||||
? List.copyOf(p.getValueUnit())
|
||||
: List.of();
|
||||
props.add(new CatProperty(
|
||||
p.getId(),
|
||||
p.getName(),
|
||||
p.getNameAlias(),
|
||||
p.getRefPid(),
|
||||
p.getSpecId(),
|
||||
p.getParentId(),
|
||||
p.getParentSpecId(),
|
||||
Boolean.TRUE.equals(p.getRequired()),
|
||||
Boolean.TRUE.equals(p.getIsSale()),
|
||||
p.getControlType(),
|
||||
p.getFeature(),
|
||||
p.getValueType(),
|
||||
p.getValueUnit(),
|
||||
Boolean.TRUE.equals(p.getIsSku()),
|
||||
Boolean.TRUE.equals(p.getIsImportant()),
|
||||
Boolean.TRUE.equals(p.getCanNote()),
|
||||
p.getPropertyValueType(),
|
||||
p.getMaxValue(),
|
||||
p.getMinValue(),
|
||||
p.getValuePrecision(),
|
||||
units,
|
||||
p.getInputMaxNum(),
|
||||
p.getChooseMaxNum(),
|
||||
p.getRequiredRuleType(),
|
||||
p.getRequiredRule(),
|
||||
Collections.unmodifiableList(showConds),
|
||||
Collections.unmodifiableList(values)));
|
||||
}
|
||||
}
|
||||
return new CatTemplate(
|
||||
body.getId(),
|
||||
body.getMaxSkuNum(),
|
||||
body.getInputMaxSpecNum(),
|
||||
body.getSingleSpecValueNum(),
|
||||
body.getIsSingleItem(),
|
||||
return new CatRule(
|
||||
propRule != null ? propRule.getChooseAllQualifySpec() : null,
|
||||
propRule != null ? propRule.getInputMaxSpecNum() : null,
|
||||
skuRule != null ? skuRule.getSpecNumLimit() : null,
|
||||
skuRule != null ? skuRule.getPriceRangeRatio() : null,
|
||||
Collections.unmodifiableList(props));
|
||||
}
|
||||
|
||||
@@ -665,18 +685,23 @@ public class PddGoodsPublishPopApiClient {
|
||||
String province, String city, String town) {
|
||||
}
|
||||
|
||||
public record CatTemplate(Long id, Long maxSkuNum, Long inputMaxSpecNum, Long singleSpecValueNum,
|
||||
Boolean singleItem, List<CatProperty> properties) {
|
||||
public record CatRule(Boolean chooseAllQualifySpec, Long inputMaxSpecNum, Integer specNumLimit,
|
||||
Double priceRangeRatio, List<CatProperty> properties) {
|
||||
}
|
||||
|
||||
public record CatProperty(Long templatePid, String name, String nameAlias, Long refPid, Long specId,
|
||||
Long parentId, boolean required, boolean sale, Integer controlType,
|
||||
Integer feature, Integer valueType, String valueUnit,
|
||||
Integer inputMaxNum, Integer chooseMaxNum, List<CatPropertyValue> values) {
|
||||
public record CatProperty(String name, Long refPid, Long parentSpecId, boolean required, boolean sale,
|
||||
boolean sku, boolean important, boolean canNote, Integer propertyValueType,
|
||||
String maxValue, String minValue, Integer valuePrecision,
|
||||
List<String> valueUnits, Integer inputMaxNum, Integer chooseMaxNum,
|
||||
Integer requiredRuleType, String requiredRule,
|
||||
List<CatPropertyShowCondition> showCondition, List<CatPropertyValue> values) {
|
||||
}
|
||||
|
||||
public record CatPropertyShowCondition(Long parentRefPid, List<Long> parentVids) {
|
||||
}
|
||||
|
||||
public record CatPropertyValue(Long vid, String value, Long specId, String extendInfo,
|
||||
Boolean parent, List<Long> parentVids) {
|
||||
List<Long> parentVids, Integer groupId, String groupName) {
|
||||
}
|
||||
|
||||
public record ParentSpecItem(Long catId, Long parentSpecId, String parentSpecName) {
|
||||
|
||||
+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.selectByIds(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.modules.notify.access.AccessChangedEvent;
|
||||
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.mapper.CompanyMemberMapper;
|
||||
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 UserMapper userMapper;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final OpTeamMemberService opTeamMemberService;
|
||||
|
||||
public CompanyMemberServiceImpl(@Lazy CurrentUserContext currentUserContext,
|
||||
@Lazy CompanyService companyService,
|
||||
PositionService positionService,
|
||||
UserMapper userMapper,
|
||||
ApplicationEventPublisher eventPublisher) {
|
||||
ApplicationEventPublisher eventPublisher,
|
||||
@Lazy OpTeamMemberService opTeamMemberService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.companyService = companyService;
|
||||
this.positionService = positionService;
|
||||
this.userMapper = userMapper;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.opTeamMemberService = opTeamMemberService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -158,6 +162,8 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
||||
member.setStatus(0);
|
||||
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
this.updateById(member);
|
||||
// 软删不会触发 FK CASCADE,应用层同步摘除运营团队成员
|
||||
opTeamMemberService.deactivateByCompanyMemberId(memberId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -228,6 +234,7 @@ public class CompanyMemberServiceImpl extends ServiceImpl<CompanyMemberMapper, C
|
||||
member.setStatus(0);
|
||||
member.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
this.updateById(member);
|
||||
opTeamMemberService.deactivateByCompanyMemberId(member.getId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ pdd:
|
||||
shop-window-seconds: 60
|
||||
app-burst-limit: 800
|
||||
app-burst-window-seconds: 10
|
||||
pdd.goods.cat.template.get:
|
||||
pdd.goods.cat.rule.get:
|
||||
shop-limit: 6000
|
||||
shop-window-seconds: 60
|
||||
app-burst-limit: 800
|
||||
|
||||
@@ -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
|
||||
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`)
|
||||
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');
|
||||
@@ -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
|
||||
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. 菜单-权限关联
|
||||
-- ------------------------------------------------
|
||||
@@ -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`)
|
||||
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`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code LIKE 'ec:shop:ad-fee:%' WHERE m.name = '推广费';
|
||||
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class BiRegionNormalizerTest {
|
||||
|
||||
@Test
|
||||
void normalize_aliasesToFullName() {
|
||||
assertEquals("广东省", BiRegionNormalizer.normalize("广东"));
|
||||
assertEquals("广东省", BiRegionNormalizer.normalize("广东省"));
|
||||
assertEquals("内蒙古自治区", BiRegionNormalizer.normalize("内蒙古"));
|
||||
assertEquals("广西壮族自治区", BiRegionNormalizer.normalize("广西"));
|
||||
assertEquals("新疆维吾尔自治区", BiRegionNormalizer.normalize("新疆"));
|
||||
assertEquals("北京市", BiRegionNormalizer.normalize("北京"));
|
||||
assertEquals("香港特别行政区", BiRegionNormalizer.normalize("香港"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalize_blankOrUnknown() {
|
||||
assertEquals(BiRegionNormalizer.UNKNOWN, BiRegionNormalizer.normalize(null));
|
||||
assertEquals(BiRegionNormalizer.UNKNOWN, BiRegionNormalizer.normalize(" "));
|
||||
assertEquals(BiRegionNormalizer.UNKNOWN, BiRegionNormalizer.normalize("火星省"));
|
||||
assertTrue(BiRegionNormalizer.isUnknown(BiRegionNormalizer.UNKNOWN));
|
||||
}
|
||||
}
|
||||
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;
|
||||
baseUrl?: string | null;
|
||||
displayName?: string | null;
|
||||
/** auto | completions | responses */
|
||||
apiStyle?: string | null;
|
||||
apiKeyMasked?: string | null;
|
||||
models?: LlmModelItem[];
|
||||
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) {
|
||||
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||
`/agent/sessions/${threadId}/messages`,
|
||||
@@ -140,6 +147,7 @@ export async function createAgentLlmProviderApi(body: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
displayName?: string;
|
||||
apiStyle?: string;
|
||||
}) {
|
||||
return requestClient.post<AgentVO.LlmProvider>(
|
||||
'/company/agent-llm-providers',
|
||||
@@ -149,7 +157,12 @@ export async function createAgentLlmProviderApi(body: {
|
||||
|
||||
export async function updateAgentLlmProviderApi(
|
||||
providerId: number,
|
||||
body: { baseUrl?: string; apiKey?: string; displayName?: string },
|
||||
body: {
|
||||
baseUrl?: string;
|
||||
apiKey?: string;
|
||||
displayName?: string;
|
||||
apiStyle?: string;
|
||||
},
|
||||
) {
|
||||
return requestClient.put<AgentVO.LlmProvider>(
|
||||
`/company/agent-llm-providers/${providerId}`,
|
||||
|
||||
@@ -4,6 +4,7 @@ export {
|
||||
createAgentSessionApi,
|
||||
deleteAgentLlmProviderApi,
|
||||
deleteAgentMemoryApi,
|
||||
deleteAgentSessionApi,
|
||||
getAgentLlmProviderApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentLlmProvidersApi,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { RegionOverviewDTO, RegionOverviewVO } from './types';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/** 区域销量:省级净销售列表(地图 + 排行) */
|
||||
export async function getRegionOverviewApi(data: RegionOverviewDTO.Query) {
|
||||
return requestClient.post<RegionOverviewVO.Overview>(
|
||||
'/bi/region/overview',
|
||||
data,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './apis';
|
||||
export * from './types';
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './types.dto';
|
||||
export * from './types.vo';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user