Compare commits

...
3 Commits
14 changed files with 373 additions and 17 deletions
+4 -1
View File
@@ -15,7 +15,10 @@ from pydantic import BaseModel, Field
class PatchBasicArgs(BaseModel):
"""只填要改的字段;未出现的字段保持页面原值。"""
goodsName: str | None = Field(default=None, description="商品标题,60 字内")
goodsName: str | None = Field(
default=None,
description="商品标题:汉字算 2、英文数字算 1,合计最多 60(约 30 汉字)",
)
goodsDesc: str | None = Field(default=None, description="商品描述;空字符串表示清空")
marketPriceYuan: float | None = Field(default=None, description="参考价,元")
twoPiecesDiscount: float | None = Field(
+16 -2
View File
@@ -27,6 +27,8 @@ class PatchSessionBody(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
llmProviderId: int | None = None
llmModel: str | None = None
# 未落库会话(local-*)改绑到稳定业务键,如系统草稿 ID
sceneRef: str | None = Field(default=None, min_length=1, max_length=200)
def _session_vo(s) -> dict:
@@ -84,11 +86,23 @@ async def patch_session(
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
if body.title is None and body.llmModel is None and body.llmProviderId is None:
if (
body.title is None
and body.llmModel is None
and body.llmProviderId is None
and body.sceneRef is None
):
raise HTTPException(status_code=400, detail="无有效更新字段")
try:
s = None
if body.title is not None:
if body.sceneRef is not None:
s = await svc.rebind_scene_ref(
actor,
thread_id,
scene_ref=body.sceneRef,
title=body.title,
)
elif body.title is not None:
s = await svc.rename(actor, thread_id, body.title)
if body.llmModel is not None or body.llmProviderId is not None:
if body.llmModel is None or body.llmProviderId is None:
+37
View File
@@ -91,6 +91,43 @@ class SessionService:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def rebind_scene_ref(
self,
actor: Actor,
thread_id: str,
*,
scene_ref: str,
title: str | None = None,
) -> Session:
"""把未落库会话(scene_ref=local-*)改绑到稳定业务键(如系统草稿 ID)。"""
new_ref = (scene_ref or "").strip()
if not new_ref:
raise ValueError("scene_ref 不能为空")
if new_ref.startswith("local-"):
raise ValueError("不能改绑到临时 local 键")
session = await self.require_owned(actor, thread_id)
if session.scene_ref == new_ref:
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
return session
current = (session.scene_ref or "").strip()
if current and not current.startswith("local-"):
raise ValueError("仅未落库会话可改绑 scene_ref")
existing = await self.find_by_scene_ref(
actor, scene=session.scene or "general", scene_ref=new_ref
)
if existing is not None and existing.thread_id != thread_id:
raise ValueError("该业务对象已有关联会话")
session.scene_ref = new_ref
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def update_llm_selection(
self,
actor: Actor,
+1
View File
@@ -36,6 +36,7 @@ _PUBLISH_SYSTEM = (
"假一赔十/7天无理由/预售/二手、运费模板)、ui_set_spec_axes(规格轴)、"
"ui_patch_skus(按 outSkuSn 改单买价、拼单价、库存、重量)、ui_patch_props(类目属性)。"
"每次只传要改的字段,未传的保持原样。"
"商品标题字数:汉字算 2、英文数字算 1,合计最多 60(约 30 汉字);生成或改写标题时自行压缩到上限内,不要写超再指望页面截断。"
"运费模板 ID 必须来自快照 costTemplates;发货时限只能用快照里的秒数;"
"类目属性枚举用 goodsProperties 里的 vid 或文案,多选英文逗号分隔。"
"不能改店铺、叶子类目、轮播图、详情图、SKU 缩略图;用户要求这些时用一句话说明对话里改不了。"
+119
View File
@@ -0,0 +1,119 @@
"""未落库会话 scene_ref 改绑规则。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any
from application.session_service import SessionService
from domain.models import Actor, Session, SessionStatus
class _MemSessions:
def __init__(self) -> None:
self.rows: dict[str, Session] = {}
async def create(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
s = self.rows.get(thread_id)
if s is None:
return None
if s.company_id != company_id or s.user_id != user_id:
return None
return s
async def list_active(self, *args: Any, **kwargs: Any) -> list[Session]:
return []
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None:
for s in self.rows.values():
if (
s.company_id == company_id
and s.user_id == user_id
and s.status == SessionStatus.ACTIVE
and (s.scene or "general") == scene
and s.scene_ref == scene_ref
):
return s
return None
async def update(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
def _actor() -> Actor:
return Actor(company_id=1, user_id="u1")
def _session(*, thread_id: str, scene_ref: str | None) -> Session:
now = datetime.utcnow()
return Session(
thread_id=thread_id,
company_id=1,
user_id="u1",
title="发布草稿(未保存)",
status=SessionStatus.ACTIVE,
scene="ecom_goods_publish",
scene_ref=scene_ref,
created_at=now,
updated_at=now,
)
def test_rebind_local_to_draft_id():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
local = _session(thread_id="t1", scene_ref="local-abc")
await repo.create(local)
out = await svc.rebind_scene_ref(
_actor(), "t1", scene_ref="42", title="发布草稿 #42"
)
assert out.scene_ref == "42"
assert out.title == "发布草稿 #42"
asyncio.run(scenario())
def test_rebind_rejects_non_local():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t1", scene_ref="7"))
try:
await svc.rebind_scene_ref(_actor(), "t1", scene_ref="8")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "未落库" in str(e)
asyncio.run(scenario())
def test_rebind_rejects_occupied_draft():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t-old", scene_ref="9"))
await repo.create(_session(thread_id="t-local", scene_ref="local-x"))
try:
await svc.rebind_scene_ref(_actor(), "t-local", scene_ref="9")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "已有关联会话" in str(e)
asyncio.run(scenario())
@@ -24,6 +24,7 @@ public class PddGoodsPublishDTO {
*/
private Long systemDraftId;
/** 拼多多标题:汉字算 2、ASCII 算 1,合计不超过 60(约 30 汉字) */
@NotBlank(message = "商品标题不能为空")
private String goodsName;
@@ -436,6 +436,10 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
if (strict && !StringUtils.hasText(goodsName)) {
throw new BusinessException("商品标题不能为空");
}
// 拼多多:汉字算 2、ASCII 算 1,合计不超过 60(约 30 汉字)
if (strict && goodsName != null && pddTitleCharUnits(goodsName) > 60) {
throw new BusinessException("商品标题超长(汉字约30个/60字符)");
}
return new PddGoodsPublishPopApiClient.GoodsAddCommand(
goodsName,
@@ -517,6 +521,17 @@ public class PddGoodsPublishServiceImpl implements PddGoodsPublishService {
return imageTransfer.transfer(companyId, ctx.mallId(), ctx.accessToken(), fileId);
}
/** 拼多多标题字符单位:code point ≤ 0xFF 算 1,否则算 2。 */
private static int pddTitleCharUnits(String text) {
int n = 0;
for (int i = 0; i < text.length(); ) {
int cp = text.codePointAt(i);
n += cp <= 0xff ? 1 : 2;
i += Character.charCount(cp);
}
return n;
}
private static boolean looksLikeUrl(String s) {
String lower = s.toLowerCase();
return lower.startsWith("http://") || lower.startsWith("https://");
+7 -1
View File
@@ -115,7 +115,13 @@ export async function submitAgentClientToolResultApi(
export async function patchAgentSessionApi(
threadId: string,
body: { title?: string; llmProviderId?: number; llmModel?: string },
body: {
title?: string;
llmProviderId?: number;
llmModel?: string;
/** 未落库会话(local-*)改绑到系统草稿 ID */
sceneRef?: string;
},
) {
return requestClient.patch<AgentVO.Session>(
`/agent/sessions/${threadId}`,
@@ -15,6 +15,7 @@ import {
createAgentSessionApi,
listAgentEnabledLlmModelsApi,
listAgentMessagesApi,
listAgentSessionsApi,
patchAgentSessionApi,
streamAgentChat,
submitAgentClientToolResultApi,
@@ -50,6 +51,8 @@ const emit = defineEmits<{
}>();
const SCENE = 'ecom_goods_publish' as const;
/** 跨路由重挂:记住未落库会话 threadId,保存草稿后改绑用 */
const PENDING_LOCAL_THREAD_KEY = 'pdd-publish-agent-pending-thread';
/** 未落库时用本地 sceneRef,落库后切到草稿 ID */
const localSceneKey = `local-${
@@ -64,6 +67,30 @@ const sceneRef = computed(() =>
: localSceneKey,
);
function rememberPendingLocalThread(threadId: string) {
try {
sessionStorage.setItem(PENDING_LOCAL_THREAD_KEY, threadId);
} catch {
/* ignore quota / private mode */
}
}
function peekPendingLocalThread(): string | null {
try {
return sessionStorage.getItem(PENDING_LOCAL_THREAD_KEY);
} catch {
return null;
}
}
function clearPendingLocalThread() {
try {
sessionStorage.removeItem(PENDING_LOCAL_THREAD_KEY);
} catch {
/* ignore */
}
}
const sessionTitle = computed(() =>
props.draftId != null && props.draftId > 0
? `发布草稿 #${props.draftId}`
@@ -239,20 +266,45 @@ async function loadEnabledModels() {
}
}
/** 复用或创建本草稿的发布场景会话 */
/** 仅查找已有会话,不创建(打开草稿时恢复历史用) */
async function findExistingSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const ref = sceneRef.value;
// 临时键不会落库关联,不必查
if (!ref || ref.startsWith('local-')) return null;
try {
const res = await listAgentSessionsApi({ scene: SCENE });
const hit = (res.items || []).find((s) => s.sceneRef === ref);
if (!hit?.threadId) return null;
session.value = hit;
syncSelectedFromSession();
return hit.threadId;
} catch {
return null;
}
}
/** 首次发消息时创建或复用;打开页面不调用,避免空会话堆积 */
async function ensureSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const existing = await findExistingSession();
if (existing) return existing;
const parsed = parseModelKey(selectedModelKey.value);
const ref = sceneRef.value;
const s = await createAgentSessionApi({
title: sessionTitle.value,
llmProviderId: parsed?.providerId,
llmModel: parsed?.model,
scene: SCENE,
sceneRef: sceneRef.value,
sceneRef: ref,
reuseBySceneRef: true,
});
session.value = s;
syncSelectedFromSession();
// 未落库会话写入 pending,供 new→真实 ID 路由重挂后改绑
if (ref.startsWith('local-') && s.threadId) {
rememberPendingLocalThread(s.threadId);
}
return s.threadId;
}
@@ -278,6 +330,29 @@ async function loadMessages(threadId: string) {
}
}
/**
* 草稿首次落库:把已存在的 local-* 会话改绑到草稿 ID。
* 用户未发过消息则没有会话,直接返回 true(无需改绑)。
* 须在路由 replace 之前调用:new→id 常会整页重挂,内存会话会丢。
*/
async function rebindSessionToDraft(draftId: number): Promise<boolean> {
const threadId = session.value?.threadId || peekPendingLocalThread();
if (!threadId) return true;
try {
const s = await patchAgentSessionApi(threadId, {
sceneRef: String(draftId),
title: `发布草稿 #${draftId}`,
});
session.value = session.value ? { ...session.value, ...s } : s;
clearPendingLocalThread();
return true;
} catch (e: any) {
// 该草稿已有别的会话等冲突:不打断当前编辑
console.warn(e?.message || '发布助手会话改绑失败');
return false;
}
}
async function bootstrap() {
loadingSession.value = true;
messages.value = [];
@@ -286,7 +361,12 @@ async function bootstrap() {
citations.value = [];
try {
await loadEnabledModels();
const threadId = await ensureSession();
// 路由重挂后 draftId 已是真实 ID:先尝试把 pending 的 local 会话改绑过来
if (props.draftId != null && props.draftId > 0 && peekPendingLocalThread()) {
await rebindSessionToDraft(props.draftId);
}
// 只恢复已有会话,绝不在打开页时新建(避免空草稿刷会话)
const threadId = await findExistingSession();
if (threadId) await loadMessages(threadId);
} catch (e: any) {
message.error(e?.message || '初始化发布助手失败');
@@ -298,8 +378,9 @@ async function bootstrap() {
watch(
() => props.draftId,
(id, prev) => {
// 新建落库后仅 URL 从 new→id:沿用当前会话,避免打断
// 同页内 new→id 且会话仍在:改绑后不重建(父级也会在 replace 前主动改绑)
if (prev == null && id != null && id > 0 && session.value?.threadId) {
void rebindSessionToDraft(id);
return;
}
abort?.abort();
@@ -308,6 +389,10 @@ watch(
{ immediate: true },
);
defineExpose({
rebindSessionToDraft,
});
async function onModelChange(key: string) {
if (!key || !key.includes('::')) return;
selectedModelKey.value = key;
@@ -50,6 +50,11 @@ import { usePublishDraft } from './composables/use-publish-draft';
import { usePublishImages } from './composables/use-publish-images';
import { usePublishSku } from './composables/use-publish-sku';
import { usePublishSpecs } from './composables/use-publish-specs';
import {
PDD_GOODS_NAME_MAX_UNITS,
pddTitleCharUnits,
truncatePddTitle,
} from './utils/pdd-title-length';
defineOptions({ name: 'PddPublishEditor' });
@@ -363,6 +368,15 @@ function onSpecAxesListRef(el: HTMLElement | null) {
function onSkuTableWrapRef(el: HTMLElement | null) {
sku.skuTableWrapRef.value = el;
}
/** 标题:汉字算 2、ASCII 算 1,上限 60 */
function onGoodsNameChange(value: string) {
form.goodsName = truncatePddTitle(value);
}
function goodsNameCountFormatter(info: { value: string }) {
return `${pddTitleCharUnits(info.value)} / ${PDD_GOODS_NAME_MAX_UNITS}`;
}
</script>
<template>
@@ -461,7 +475,12 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
:class="{ 'agent-typing-field': agentTypingField === 'goodsName' }"
>
<Form.Item label="商品标题" required>
<Input v-model:value="form.goodsName" :maxlength="60" show-count />
<Input
:value="form.goodsName"
:show-count="{ formatter: goodsNameCountFormatter }"
placeholder="最多约 30 个汉字(60 字符)"
@update:value="onGoodsNameChange"
/>
</Form.Item>
</div>
<div
@@ -16,6 +16,7 @@ import {
effectiveValueUnits,
resolveCatPropControlKind,
} from '../utils/cat-property';
import { truncatePddTitle } from '../utils/pdd-title-length';
import { typewriterReplace } from '../utils/typewriter-text';
/** 智能体正在打字的表单焦点(用于高亮输入区) */
@@ -235,8 +236,8 @@ export function usePublishAgent(options: {
): Promise<ClientToolResult> {
const name = pickArgString(args, 'goodsName', 'goods_name');
if (!name) return { ok: false, message: '标题为空' };
// 与输入框 maxlength 对齐,避免受控 Input 截断后看似「没写上」
const next = name.slice(0, 60);
// 与拼多多标题计字对齐:汉字 2、ASCII 1,上限 60
const next = truncatePddTitle(name);
if (form.goodsName === next) {
return { ok: true, message: `标题未变:${next}` };
}
@@ -33,6 +33,11 @@ import {
seedDefaultPropUnits,
validateCatPropValue,
} from '../utils/cat-property';
import {
PDD_GOODS_NAME_MAX_UNITS,
pddTitleCharUnits,
truncatePddTitle,
} from '../utils/pdd-title-length';
type EmitDraft = {
(e: 'draft-saved', draftId: number): void;
@@ -163,6 +168,10 @@ export function usePublishDraft(options: {
message.warning('请填写商品标题');
return false;
}
if (pddTitleCharUnits(form.goodsName) > PDD_GOODS_NAME_MAX_UNITS) {
message.warning('商品标题超长(汉字约 30 个 / 60 字符)');
return false;
}
if (!form.catId) {
message.warning('请选择叶子类目');
return false;
@@ -401,10 +410,11 @@ export function usePublishDraft(options: {
loadSkuCandidates(),
]);
form.goodsName =
form.goodsName = truncatePddTitle(
(typeof es.goodsName === 'string' && es.goodsName) ||
draft.title ||
'';
draft.title ||
'',
);
if (typeof es.goodsDesc === 'string') form.goodsDesc = es.goodsDesc;
const catId =
@@ -37,6 +37,9 @@ const presetPddShopId = computed(() => {
});
const editorRef = ref<PublishEditorAgentApi | null>(null);
const agentPanelRef = ref<{
rebindSessionToDraft: (draftId: number) => Promise<boolean>;
} | null>(null);
/** 显式取 .value,避免把组件 ref 本体传给子组件导致偶发取不到命令面 */
const editorApi = computed(() => editorRef.value);
const { width: agentWidthPct, collapsed: agentCollapsed } =
@@ -59,10 +62,15 @@ function goBack() {
void router.push('/pdd/goods/publish');
}
/** 首次落库后把 URL 换成真实草稿 ID,便于刷新续编与 Agent 绑定 */
function onDraftSaved(id: number) {
/** 首次落库:先把发布助手 local 会话改绑到草稿 ID,再改 URL(避免路由重挂丢掉临时会话) */
async function onDraftSaved(id: number) {
if (!id || draftId.value === id) return;
void router.replace({
try {
await agentPanelRef.value?.rebindSessionToDraft(id);
} catch {
/* 改绑失败仍替换 URL,bootstrap 会再试 pending */
}
await router.replace({
path: `/pdd/goods/publish/editor/${id}`,
query: {},
});
@@ -103,6 +111,7 @@ function onDraftSaved(id: number) {
:style="agentPaneStyle"
>
<PddPublishAgentPanel
ref="agentPanelRef"
class="h-full min-h-0"
:draft-id="draftId"
:collapsed="agentCollapsed"
@@ -0,0 +1,36 @@
/**
* 拼多多商品标题字数:汉字/非 ASCII 算 2,ASCII 算 1,上限 60(约 30 汉字)。
*/
export const PDD_GOODS_NAME_MAX_UNITS = 60;
/** 单个码点占用的平台字符单位 */
function charUnit(ch: string): number {
const cp = ch.codePointAt(0) ?? 0;
return cp <= 0xff ? 1 : 2;
}
/** 标题已占用的字符单位 */
export function pddTitleCharUnits(text: string): number {
let n = 0;
for (const ch of text ?? '') {
n += charUnit(ch);
}
return n;
}
/** 按单位上限截断,保证不超过 maxUnits */
export function truncatePddTitle(
text: string,
maxUnits: number = PDD_GOODS_NAME_MAX_UNITS,
): string {
let n = 0;
let out = '';
for (const ch of text ?? '') {
const w = charUnit(ch);
if (n + w > maxUnits) break;
out += ch;
n += w;
}
return out;
}