mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
fix: 发布助手去掉读表单空转并修正工具状态卡住
This commit is contained in:
@@ -1,18 +1,13 @@
|
||||
"""发布场景前端工具:读快照用请求体注入;写工具由 streamer 推 client_tool 事件。"""
|
||||
"""发布场景前端写工具:读快照注入 system;写工具由 streamer 推 client_tool 事件。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.tools import StructuredTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class _EmptyArgs(BaseModel):
|
||||
pass
|
||||
|
||||
|
||||
class SetGoodsNameArgs(BaseModel):
|
||||
goodsName: str = Field(description="商品标题,建议 60 字内")
|
||||
|
||||
@@ -28,16 +23,19 @@ class SpecAxis(BaseModel):
|
||||
|
||||
class SetSpecAxesArgs(BaseModel):
|
||||
axes: list[SpecAxis] = Field(
|
||||
description="完整规格轴;将替换表单现有规格轴并重建 SKU 行"
|
||||
description=(
|
||||
"完整规格轴;同维改文案会保留已有 SKU 编码,"
|
||||
"新增取值才新建空编码行"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def build_publish_client_tools(
|
||||
*,
|
||||
form_snapshot: dict[str, Any] | None,
|
||||
form_snapshot: dict[str, Any] | None = None,
|
||||
) -> list[Any]:
|
||||
def get_snapshot() -> str:
|
||||
return json.dumps(form_snapshot or {}, ensure_ascii=False, default=str)
|
||||
"""仅注册写工具;读快照已注入 system,避免再占一轮「读取发布表单」。"""
|
||||
del form_snapshot # 快照由 system 注入,工具闭包不再依赖
|
||||
|
||||
def set_goods_name(goodsName: str) -> str:
|
||||
return f"已请求写入标题:{goodsName}"
|
||||
@@ -50,12 +48,6 @@ def build_publish_client_tools(
|
||||
return f"已请求写入 {n} 个规格维,页面将重建 SKU 行"
|
||||
|
||||
return [
|
||||
StructuredTool.from_function(
|
||||
func=get_snapshot,
|
||||
name="ui_get_publish_snapshot",
|
||||
description="读取当前发布表单快照:标题、描述、类目、规格轴、SKU 行(含商家编码)等。改表前应先调用。",
|
||||
args_schema=_EmptyArgs,
|
||||
),
|
||||
StructuredTool.from_function(
|
||||
func=set_goods_name,
|
||||
name="ui_set_goods_name",
|
||||
@@ -71,11 +63,12 @@ def build_publish_client_tools(
|
||||
StructuredTool.from_function(
|
||||
func=set_spec_axes,
|
||||
name="ui_set_spec_axes",
|
||||
description="设置规格轴(维名+值列表)。页面会按笛卡尔积重建 SKU 行。",
|
||||
description="设置规格轴(维名+值列表)。同维相同/改名的取值会保留已有 SKU 商家编码;新增取值才新建空编码行。",
|
||||
args_schema=SetSpecAxesArgs,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def is_client_tool_name(name: str) -> bool:
|
||||
return (name or "").startswith("ui_")
|
||||
"""需前端执行的写工具(ui_set_*);读类工具不走 client_tool。"""
|
||||
return (name or "").startswith("ui_set_")
|
||||
|
||||
@@ -18,7 +18,7 @@ router = APIRouter(prefix="/sessions", tags=["chat"])
|
||||
|
||||
class ChatBody(BaseModel):
|
||||
content: str = Field(min_length=1, max_length=20000)
|
||||
# 发布场景:当前表单快照,供 ui_get_publish_snapshot
|
||||
# 发布场景:当前表单快照,注入 system(不再走 ui_get_publish_snapshot)
|
||||
formSnapshot: dict | None = None
|
||||
|
||||
|
||||
|
||||
@@ -86,13 +86,14 @@ class ChatService:
|
||||
memory_count=memory_count,
|
||||
memory_just_saved=just_saved,
|
||||
scene=scene,
|
||||
form_snapshot=form_snapshot,
|
||||
)
|
||||
|
||||
client_tools = None
|
||||
if scene == "ecom_goods_publish":
|
||||
from agent.tools.publish_ui import build_publish_client_tools
|
||||
|
||||
client_tools = build_publish_client_tools(form_snapshot=form_snapshot)
|
||||
client_tools = build_publish_client_tools()
|
||||
|
||||
tools = await load_tools_for_turn(
|
||||
self._settings,
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from domain.models import SCENE_ECOM_GOODS_PUBLISH, SCENE_GENERAL
|
||||
|
||||
_BASE_SYSTEM = (
|
||||
@@ -28,12 +31,14 @@ _BASE_SYSTEM = (
|
||||
|
||||
_PUBLISH_SYSTEM = (
|
||||
"你是电商 DMB 的拼多多商品发布助手,帮助用户在系统草稿里完善标题、规格轴、属性与价格等。"
|
||||
"当前表单在浏览器里;改表单必须调用 ui_ 开头的前端工具,不要只口头说已修改。"
|
||||
"当前表单快照已在下方【当前发布表单】中给出,直接根据快照改表,不要再去「读取」表单。"
|
||||
"改表单必须调用 ui_set_goods_name / ui_set_goods_desc / ui_set_spec_axes,不要只口头说已修改。"
|
||||
"查内部商品/SKU:catalog_search、catalog_sku_detail(按 skuCode)。"
|
||||
"查已同步的拼多多渠道商品:pdd_goods_search、pdd_goods_detail(只查本地库)。"
|
||||
"常见流程:根据表单已有 SKU 编码 → catalog_sku_detail / pdd_goods_search → "
|
||||
"挑选或按用户指定模仿某条渠道商品 → 生成标题并用 ui_set_goods_name 写入;"
|
||||
"规格只通过 ui_set_spec_axes 写规格轴,页面会自动笛卡尔积重建 SKU 行。"
|
||||
"规格只通过 ui_set_spec_axes 写规格轴;改规格文案会保留已有 SKU 商家编码,"
|
||||
"新增规格值才会多出空编码行。"
|
||||
"用户未指定时,可自行选择最接近的渠道商品模仿,或结合内部商品信息自由发挥;"
|
||||
"用户指定风格或指定模仿哪条时以用户为准。"
|
||||
"一期不要处理图片上传或改图。"
|
||||
@@ -47,9 +52,17 @@ def build_system_prompt(
|
||||
memory_count: int = 0,
|
||||
memory_just_saved: str | None = None,
|
||||
scene: str = SCENE_GENERAL,
|
||||
form_snapshot: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
if (scene or SCENE_GENERAL).strip() == SCENE_ECOM_GOODS_PUBLISH:
|
||||
return _PUBLISH_SYSTEM
|
||||
snap = form_snapshot if isinstance(form_snapshot, dict) else {}
|
||||
snap_text = json.dumps(snap, ensure_ascii=False, default=str)
|
||||
# 控制体积,避免拖垮上下文
|
||||
if len(snap_text) > 12000:
|
||||
snap_text = snap_text[:12000] + "…(截断)"
|
||||
return (
|
||||
f"{_PUBLISH_SYSTEM}\n\n【当前发布表单】\n{snap_text}"
|
||||
)
|
||||
|
||||
system = _BASE_SYSTEM
|
||||
if memory_count > 0:
|
||||
|
||||
@@ -213,7 +213,7 @@ export async function probeAgentLlmModelsApi(body: {
|
||||
export function streamAgentChat(options: {
|
||||
threadId: string;
|
||||
content: string;
|
||||
/** 发布场景:当前表单快照,供 ui_get_publish_snapshot */
|
||||
/** 发布场景:当前表单快照,注入 Agent system */
|
||||
formSnapshot?: Record<string, unknown>;
|
||||
onToken: (text: string) => void;
|
||||
onTool?: (payload: {
|
||||
|
||||
@@ -364,7 +364,9 @@ function onStreamTool(payload: {
|
||||
toolStatusLabel.value = payload.label;
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
} else if (payload.phase === 'end') {
|
||||
toolStatusLabel.value = payload.label;
|
||||
// 结束后清状态,避免一直显示上一工具名直到出 token
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+208
-72
@@ -183,6 +183,65 @@ const submitting = ref(false);
|
||||
const hydratingDraft = ref(false);
|
||||
let skuRowSeq = 1;
|
||||
let uploadUidSeq = 1;
|
||||
/** 规格值槽位 id,跨改名保持不变 */
|
||||
let specValueSlotSeq = 1;
|
||||
|
||||
function createSpecValueSlot(token = ''): SpecValueSlot {
|
||||
return { id: specValueSlotSeq++, token };
|
||||
}
|
||||
|
||||
/** 草稿兼容:旧版 string[] 或新版 {id,token}[] */
|
||||
function normalizeSpecValueSlots(raw: unknown): SpecValueSlot[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
return [createSpecValueSlot('')];
|
||||
}
|
||||
return raw.map((item) => {
|
||||
if (item && typeof item === 'object' && 'token' in (item as object)) {
|
||||
const row = item as { id?: unknown; token?: unknown };
|
||||
const idNum = Number(row.id);
|
||||
if (Number.isFinite(idNum) && idNum > 0) {
|
||||
if (idNum >= specValueSlotSeq) specValueSlotSeq = idNum + 1;
|
||||
return { id: idNum, token: String(row.token ?? '') };
|
||||
}
|
||||
return createSpecValueSlot(String(row.token ?? ''));
|
||||
}
|
||||
return createSpecValueSlot(String(item ?? ''));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并规格值槽位:相同 token 优先复用 id;其余按剩余槽位顺序承接(改名);多出的新建。
|
||||
*/
|
||||
function mergeSpecValueSlots(
|
||||
prevSlots: SpecValueSlot[] | undefined,
|
||||
tokens: string[],
|
||||
): SpecValueSlot[] {
|
||||
if (tokens.length === 0) {
|
||||
return [createSpecValueSlot('')];
|
||||
}
|
||||
const available = [...(prevSlots ?? [])];
|
||||
const result: Array<{ id: number; token: string }> = [];
|
||||
|
||||
for (const token of tokens) {
|
||||
const idx = available.findIndex((s) => s.token === token);
|
||||
if (idx >= 0) {
|
||||
const [hit] = available.splice(idx, 1);
|
||||
result.push({ id: hit!.id, token });
|
||||
} else {
|
||||
result.push({ id: -1, token });
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < result.length; i++) {
|
||||
const row = result[i]!;
|
||||
if (row.id !== -1) continue;
|
||||
const leftover = available.shift();
|
||||
result[i] = leftover
|
||||
? { id: leftover.id, token: row.token }
|
||||
: createSpecValueSlot(row.token);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 草稿中持久化的已上传图片 */
|
||||
type PersistedUpload = {
|
||||
@@ -193,7 +252,7 @@ type PersistedUpload = {
|
||||
|
||||
type SkuRow = {
|
||||
key: number;
|
||||
/** 规格组合稳定键,用于重建时保留价格/编码等 */
|
||||
/** 各维规格值槽位 id 组合键;与展示文案无关,改名不丢编码 */
|
||||
comboKey: string;
|
||||
internalSkuId?: number;
|
||||
productName?: string;
|
||||
@@ -230,6 +289,15 @@ type SpecCatalogItem = {
|
||||
}[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 规格值槽位:id 稳定标识身份,token 为买家可见描述(可改名)。
|
||||
* SKU 行按各维 slot id 组合对齐,改文案不丢商家编码。
|
||||
*/
|
||||
type SpecValueSlot = {
|
||||
id: number;
|
||||
token: string;
|
||||
};
|
||||
|
||||
/** 已添加的规格轴:默认仅「款式」一条,其余手动添加 */
|
||||
type SpecAxis = {
|
||||
rowId: number;
|
||||
@@ -241,7 +309,7 @@ type SpecAxis = {
|
||||
templatePid?: number;
|
||||
valueUnit?: string;
|
||||
presetOptions: SpecCatalogItem['presetOptions'];
|
||||
selectedValues: string[];
|
||||
selectedValues: SpecValueSlot[];
|
||||
};
|
||||
|
||||
const form = reactive({
|
||||
@@ -988,7 +1056,7 @@ function createAxisFromCatalog(item: SpecCatalogItem): SpecAxis {
|
||||
valueUnit: item.valueUnit,
|
||||
presetOptions: item.presetOptions.map((o) => ({ ...o })),
|
||||
// 默认一条空输入,随时可编辑
|
||||
selectedValues: [''],
|
||||
selectedValues: [createSpecValueSlot('')],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1020,7 +1088,7 @@ function rebuildSpecCatalogPreservingUserData() {
|
||||
const prevAxes = specAxes.value.map((a) => ({
|
||||
...a,
|
||||
presetOptions: a.presetOptions.map((o) => ({ ...o })),
|
||||
selectedValues: [...a.selectedValues],
|
||||
selectedValues: a.selectedValues.map((s) => ({ ...s })),
|
||||
}));
|
||||
const prevSkus = skuRows.value;
|
||||
|
||||
@@ -1064,17 +1132,20 @@ function rebuildSpecCatalogPreservingUserData() {
|
||||
|
||||
usedCatalog.add(match.catalogKey);
|
||||
const tokenMap = new Map<string, string>();
|
||||
const selectedValues = prev.selectedValues.map((token) => {
|
||||
if (!String(token).trim()) return '';
|
||||
const selectedValues = prev.selectedValues.map((slot) => {
|
||||
const token = slot.token;
|
||||
if (!String(token).trim()) {
|
||||
return { id: slot.id, token: '' };
|
||||
}
|
||||
const label =
|
||||
prev.presetOptions.find((o) => o.value === token)?.label ?? token;
|
||||
const hit =
|
||||
match.presetOptions.find((o) => o.value === token) ||
|
||||
match.presetOptions.find((o) => o.label === label);
|
||||
// 预设对不上则保留文案,便于用户继续编辑
|
||||
// 预设对不上则保留文案,便于用户继续编辑;slot.id 不变
|
||||
const nextToken = hit?.value ?? label;
|
||||
tokenMap.set(token, nextToken);
|
||||
return nextToken;
|
||||
return { id: slot.id, token: nextToken };
|
||||
});
|
||||
valueMaps.set(prev.key, tokenMap);
|
||||
keyMap.set(prev.key, match.catalogKey);
|
||||
@@ -1089,7 +1160,10 @@ function rebuildSpecCatalogPreservingUserData() {
|
||||
templatePid: match.templatePid,
|
||||
valueUnit: match.valueUnit,
|
||||
presetOptions: match.presetOptions.map((o) => ({ ...o })),
|
||||
selectedValues: selectedValues.length > 0 ? selectedValues : [''],
|
||||
selectedValues:
|
||||
selectedValues.length > 0
|
||||
? selectedValues
|
||||
: [createSpecValueSlot('')],
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1102,14 +1176,22 @@ function rebuildSpecCatalogPreservingUserData() {
|
||||
const newVal = valueMaps.get(oldKey)?.get(oldVal) ?? oldVal;
|
||||
saleValues[newKey] = newVal;
|
||||
}
|
||||
const tokens = nextAxes.map((a) => saleValues[a.key] ?? '');
|
||||
const parts = nextAxes.map((a) => {
|
||||
const token = saleValues[a.key] ?? '';
|
||||
const slot =
|
||||
a.selectedValues.find((s) => s.token === token) ||
|
||||
a.selectedValues.find(
|
||||
(s) => labelOfAxisValue(a, s.token) === token,
|
||||
);
|
||||
return { axisKey: a.key, slotId: slot?.id ?? -1 };
|
||||
});
|
||||
const labels = nextAxes.map((a) =>
|
||||
labelOfAxisValue(a, saleValues[a.key] ?? ''),
|
||||
);
|
||||
return {
|
||||
...row,
|
||||
saleValues,
|
||||
comboKey: comboKeyOf(tokens),
|
||||
comboKey: comboKeyFromSlots(parts),
|
||||
skuName: labels.filter((l) => l && l !== '—').join(' / ') || row.skuName,
|
||||
};
|
||||
});
|
||||
@@ -1144,7 +1226,7 @@ function applyCatalogToAxis(axis: SpecAxis, catalogKey: string) {
|
||||
axis.templatePid = item.templatePid;
|
||||
axis.valueUnit = item.valueUnit;
|
||||
axis.presetOptions = item.presetOptions.map((o) => ({ ...o }));
|
||||
axis.selectedValues = [''];
|
||||
axis.selectedValues = [createSpecValueSlot('')];
|
||||
}
|
||||
|
||||
function onAxisCatalogChange(rowId: number, catalogKey: string) {
|
||||
@@ -1190,23 +1272,28 @@ function removeSpecAxis(rowId: number) {
|
||||
});
|
||||
}
|
||||
|
||||
/** 参与笛卡尔积的有效规格值(去掉空白) */
|
||||
/** 参与笛卡尔积的有效规格槽(去掉空白 token) */
|
||||
function effectiveSpecSlots(axis: SpecAxis) {
|
||||
return axis.selectedValues.filter((s) => s.token.trim());
|
||||
}
|
||||
|
||||
/** 有效规格值 token 列表(发布/校验用) */
|
||||
function effectiveSpecValues(axis: SpecAxis) {
|
||||
return axis.selectedValues.map((v) => v.trim()).filter(Boolean);
|
||||
return effectiveSpecSlots(axis).map((s) => s.token.trim());
|
||||
}
|
||||
|
||||
/** AutoComplete 展示文案:预设用 label,自定义原样 */
|
||||
function specValueDisplay(axis: SpecAxis, index: number) {
|
||||
const raw = axis.selectedValues[index] ?? '';
|
||||
const raw = axis.selectedValues[index]?.token ?? '';
|
||||
return labelOfAxisValue(axis, raw);
|
||||
}
|
||||
|
||||
/** 下拉选项:未占用的预设 + 当前项(用 label 作 value,避免输入框出现 vid) */
|
||||
function specValueAutoOptions(axis: SpecAxis, index: number) {
|
||||
const current = axis.selectedValues[index] ?? '';
|
||||
const current = axis.selectedValues[index]?.token ?? '';
|
||||
const used = new Set(
|
||||
axis.selectedValues
|
||||
.map((v, i) => (i === index ? '' : v.trim()))
|
||||
.map((s, i) => (i === index ? '' : s.token.trim()))
|
||||
.filter(Boolean),
|
||||
);
|
||||
return axis.presetOptions
|
||||
@@ -1226,24 +1313,30 @@ function resolveSpecValueToken(axis: SpecAxis, raw: string) {
|
||||
function onSpecValueInput(rowId: number, index: number, text: string) {
|
||||
const axis = specAxes.value.find((a) => a.rowId === rowId);
|
||||
if (!axis || index < 0 || index >= axis.selectedValues.length) return;
|
||||
// 输入过程保留原文,失焦再归一成预设 value
|
||||
axis.selectedValues[index] = text;
|
||||
const slot = axis.selectedValues[index];
|
||||
if (!slot) return;
|
||||
// 输入过程保留原文,失焦再归一成预设 value;slot.id 不变
|
||||
slot.token = text;
|
||||
}
|
||||
|
||||
function onSpecValueCommit(rowId: number, index: number) {
|
||||
const axis = specAxes.value.find((a) => a.rowId === rowId);
|
||||
if (!axis || index < 0 || index >= axis.selectedValues.length) return;
|
||||
const value = resolveSpecValueToken(axis, axis.selectedValues[index] ?? '');
|
||||
const slot = axis.selectedValues[index];
|
||||
if (!slot) return;
|
||||
const value = resolveSpecValueToken(axis, slot.token);
|
||||
if (
|
||||
value &&
|
||||
axis.selectedValues.some((v, i) => i !== index && v.trim() === value)
|
||||
axis.selectedValues.some(
|
||||
(s, i) => i !== index && s.token.trim() === value,
|
||||
)
|
||||
) {
|
||||
message.warning('该规格值已存在');
|
||||
axis.selectedValues[index] = '';
|
||||
slot.token = '';
|
||||
syncSkuRowsFromSpecs();
|
||||
return;
|
||||
}
|
||||
axis.selectedValues[index] = value;
|
||||
slot.token = value;
|
||||
syncSkuRowsFromSpecs();
|
||||
}
|
||||
|
||||
@@ -1252,14 +1345,14 @@ function onSpecValueEnter(rowId: number, index: number) {
|
||||
onSpecValueCommit(rowId, index);
|
||||
const axis = specAxes.value.find((a) => a.rowId === rowId);
|
||||
if (!axis) return;
|
||||
const current = (axis.selectedValues[index] ?? '').trim();
|
||||
const current = (axis.selectedValues[index]?.token ?? '').trim();
|
||||
if (!current) return;
|
||||
const next = axis.selectedValues[index + 1];
|
||||
if (next != null && !String(next).trim()) {
|
||||
if (next != null && !String(next.token).trim()) {
|
||||
focusSpecValueInput(rowId, index + 1);
|
||||
return;
|
||||
}
|
||||
axis.selectedValues.splice(index + 1, 0, '');
|
||||
axis.selectedValues.splice(index + 1, 0, createSpecValueSlot(''));
|
||||
focusSpecValueInput(rowId, index + 1);
|
||||
}
|
||||
|
||||
@@ -1276,7 +1369,7 @@ function focusSpecValueInput(rowId: number, index: number) {
|
||||
function addSpecValueSlot(rowId: number) {
|
||||
const axis = specAxes.value.find((a) => a.rowId === rowId);
|
||||
if (!axis) return;
|
||||
axis.selectedValues.push('');
|
||||
axis.selectedValues.push(createSpecValueSlot(''));
|
||||
}
|
||||
|
||||
function removeSpecValue(rowId: number, index: number) {
|
||||
@@ -1290,28 +1383,28 @@ function removeSpecValue(rowId: number, index: number) {
|
||||
if (!current) return;
|
||||
if (index < 0 || index >= current.selectedValues.length) return;
|
||||
if (current.selectedValues.length <= 1) {
|
||||
current.selectedValues[0] = '';
|
||||
current.selectedValues[0] = createSpecValueSlot('');
|
||||
} else {
|
||||
current.selectedValues.splice(index, 1);
|
||||
}
|
||||
syncSkuRowsFromSpecs();
|
||||
};
|
||||
|
||||
if (!String(raw).trim()) {
|
||||
if (!raw.token.trim()) {
|
||||
doRemove();
|
||||
return;
|
||||
}
|
||||
|
||||
const label = labelOfAxisValue(axis, raw);
|
||||
AntModal.confirm({
|
||||
title: '确认删除规格值?',
|
||||
content: `确定删除「${axis.name}」的取值「${label}」吗?相关 SKU 组合将重新生成。`,
|
||||
content: `删除「${labelOfAxisValue(axis, raw.token)}」后,相关 SKU 组合将移除。`,
|
||||
okText: '删除',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
centered: true,
|
||||
zIndex: 2100,
|
||||
onOk: doRemove,
|
||||
onOk() {
|
||||
doRemove();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1420,16 +1513,22 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
function cartesianProduct(lists: string[][]): string[][] {
|
||||
function cartesianProduct<T>(lists: T[][]): T[][] {
|
||||
if (lists.length === 0) return [];
|
||||
return lists.reduce<string[][]>(
|
||||
return lists.reduce<T[][]>(
|
||||
(acc, curr) => acc.flatMap((prefix) => curr.map((item) => [...prefix, item])),
|
||||
[[]],
|
||||
);
|
||||
}
|
||||
|
||||
function comboKeyOf(values: string[]) {
|
||||
return values.join('\u0001');
|
||||
/** SKU 身份:按轴 key + 槽位 id(与规格文案无关,轴顺序无关) */
|
||||
function comboKeyFromSlots(
|
||||
parts: Array<{ axisKey: string; slotId: number }>,
|
||||
) {
|
||||
return [...parts]
|
||||
.sort((a, b) => a.axisKey.localeCompare(b.axisKey))
|
||||
.map((p) => `${p.axisKey}:${p.slotId}`)
|
||||
.join('\u0001');
|
||||
}
|
||||
|
||||
function labelOfAxisValue(axis: SpecAxis, value: string) {
|
||||
@@ -1466,7 +1565,7 @@ function skuSpecCellAutoOptions(record: Record<string, any>, axisKey: string) {
|
||||
const axis = specAxes.value.find((a) => a.key === axisKey);
|
||||
if (!axis) return [];
|
||||
const current = (record.saleValues?.[axisKey] as string | undefined) ?? '';
|
||||
const index = axis.selectedValues.findIndex((v) => v === current);
|
||||
const index = axis.selectedValues.findIndex((s) => s.token === current);
|
||||
if (index < 0) {
|
||||
return axis.presetOptions.map((o) => ({
|
||||
label: o.label,
|
||||
@@ -1485,6 +1584,7 @@ function onSkuSpecCellInput(rowKey: number, axisKey: string, text: string) {
|
||||
|
||||
/**
|
||||
* 合并单元格内改规格值 = 重命名该轴上对应取值(整组同值),再同步笛卡尔积。
|
||||
* 只改槽位 token,slot.id 不变,商家编码保留。
|
||||
*/
|
||||
function onSkuSpecCellCommit(rowKey: number, axisKey: string) {
|
||||
const dk = skuSpecDraftKey(rowKey, axisKey);
|
||||
@@ -1502,20 +1602,25 @@ function onSkuSpecCellCommit(rowKey: number, axisKey: string) {
|
||||
const newToken = resolveSpecValueToken(axis, draft);
|
||||
if (!newToken || newToken === oldToken) return;
|
||||
|
||||
const vi = axis.selectedValues.findIndex((v) => v === oldToken);
|
||||
const vi = axis.selectedValues.findIndex((s) => s.token === oldToken);
|
||||
if (vi < 0) return;
|
||||
if (
|
||||
axis.selectedValues.some((v, i) => i !== vi && v.trim() === newToken)
|
||||
axis.selectedValues.some(
|
||||
(s, i) => i !== vi && s.token.trim() === newToken,
|
||||
)
|
||||
) {
|
||||
message.warning('该规格值已存在');
|
||||
return;
|
||||
}
|
||||
axis.selectedValues[vi] = newToken;
|
||||
const slot = axis.selectedValues[vi];
|
||||
if (!slot) return;
|
||||
slot.token = newToken;
|
||||
syncSkuRowsFromSpecs();
|
||||
}
|
||||
|
||||
/**
|
||||
* 规格取值变化后按笛卡尔积生成 SKU;同组合键保留已填价格/编码/图。
|
||||
* 规格槽位变化后按笛卡尔积生成 SKU;同槽位组合键保留已填价格/编码/图。
|
||||
* 改文案只改 token,槽位 id 不变,故不会丢商家编码。
|
||||
*/
|
||||
function syncSkuRowsFromSpecs() {
|
||||
const axes = specAxes.value;
|
||||
@@ -1523,13 +1628,13 @@ function syncSkuRowsFromSpecs() {
|
||||
clearSkuRows();
|
||||
return;
|
||||
}
|
||||
const valueLists = axes.map((a) => effectiveSpecValues(a));
|
||||
if (valueLists.some((list) => list.length === 0)) {
|
||||
const slotLists = axes.map((a) => effectiveSpecSlots(a));
|
||||
if (slotLists.some((list) => list.length === 0)) {
|
||||
clearSkuRows();
|
||||
return;
|
||||
}
|
||||
|
||||
const combos = cartesianProduct(valueLists);
|
||||
const combos = cartesianProduct(slotLists);
|
||||
const maxSku = Number(catTemplate.value?.maxSkuNum ?? 0);
|
||||
if (maxSku > 0 && combos.length > maxSku) {
|
||||
message.warning(
|
||||
@@ -1542,20 +1647,25 @@ function syncSkuRowsFromSpecs() {
|
||||
const usedKeys = new Set<string>();
|
||||
|
||||
for (const combo of combos) {
|
||||
const key = comboKeyOf(combo);
|
||||
const parts = axes.map((axis, i) => ({
|
||||
axisKey: axis.key,
|
||||
slotId: combo[i]!.id,
|
||||
}));
|
||||
const key = comboKeyFromSlots(parts);
|
||||
usedKeys.add(key);
|
||||
const saleValues: Record<string, string> = {};
|
||||
const labels: string[] = [];
|
||||
axes.forEach((axis, i) => {
|
||||
const v = combo[i]!;
|
||||
saleValues[axis.key] = v;
|
||||
labels.push(labelOfAxisValue(axis, v));
|
||||
const slot = combo[i]!;
|
||||
saleValues[axis.key] = slot.token;
|
||||
labels.push(labelOfAxisValue(axis, slot.token));
|
||||
});
|
||||
const skuName = labels.join(' / ');
|
||||
const prev = prevByKey.get(key);
|
||||
if (prev) {
|
||||
prev.skuName = skuName;
|
||||
prev.saleValues = saleValues;
|
||||
prev.comboKey = key;
|
||||
next.push(prev);
|
||||
prevByKey.delete(key);
|
||||
} else {
|
||||
@@ -2590,9 +2700,7 @@ async function hydrateFromDraft(id: number) {
|
||||
presetOptions: Array.isArray(a.presetOptions)
|
||||
? a.presetOptions.map((o) => ({ ...o }))
|
||||
: [],
|
||||
selectedValues: Array.isArray(a.selectedValues)
|
||||
? [...a.selectedValues]
|
||||
: [''],
|
||||
selectedValues: normalizeSpecValueSlots(a.selectedValues),
|
||||
}));
|
||||
specAxisRowSeq =
|
||||
Math.max(0, ...specAxes.value.map((a) => a.rowId)) + 1;
|
||||
@@ -2611,9 +2719,23 @@ async function hydrateFromDraft(id: number) {
|
||||
const r = raw as Record<string, unknown>;
|
||||
const thumb = r.thumb as PersistedUpload | null | undefined;
|
||||
const rowIndex = rows.length;
|
||||
const saleValues =
|
||||
r.saleValues && typeof r.saleValues === 'object'
|
||||
? { ...(r.saleValues as Record<string, string>) }
|
||||
: {};
|
||||
// 按 saleValues 反查槽位,重绑 comboKey(兼容旧草稿 token 键)
|
||||
const parts = specAxes.value.map((a) => {
|
||||
const token = saleValues[a.key] ?? '';
|
||||
const slot =
|
||||
a.selectedValues.find((s) => s.token === token) ||
|
||||
a.selectedValues.find(
|
||||
(s) => labelOfAxisValue(a, s.token) === token,
|
||||
);
|
||||
return { axisKey: a.key, slotId: slot?.id ?? -1 };
|
||||
});
|
||||
rows.push({
|
||||
key: Number(r.key) || skuRowSeq++,
|
||||
comboKey: String(r.comboKey || ''),
|
||||
comboKey: comboKeyFromSlots(parts),
|
||||
internalSkuId:
|
||||
typeof r.internalSkuId === 'number' ? r.internalSkuId : undefined,
|
||||
productName:
|
||||
@@ -2635,10 +2757,7 @@ async function hydrateFromDraft(id: number) {
|
||||
quantity: typeof r.quantity === 'number' ? r.quantity : 0,
|
||||
weight: typeof r.weight === 'number' ? r.weight : 0,
|
||||
thumbFileList: [],
|
||||
saleValues:
|
||||
r.saleValues && typeof r.saleValues === 'object'
|
||||
? { ...(r.saleValues as Record<string, string>) }
|
||||
: {},
|
||||
saleValues,
|
||||
});
|
||||
if (thumb?.fileId) {
|
||||
thumbPersisted.push({ rowIndex, thumb });
|
||||
@@ -2785,7 +2904,10 @@ async function saveDeskDraft(
|
||||
templatePid: a.templatePid,
|
||||
valueUnit: a.valueUnit,
|
||||
presetOptions: a.presetOptions.map((o) => ({ ...o })),
|
||||
selectedValues: [...a.selectedValues],
|
||||
selectedValues: a.selectedValues.map((s) => ({
|
||||
id: s.id,
|
||||
token: s.token,
|
||||
})),
|
||||
})),
|
||||
skuRows: skuRows.value.map((r) => ({
|
||||
key: r.key,
|
||||
@@ -3029,7 +3151,7 @@ function applySetGoodsDesc(args: Record<string, unknown>) {
|
||||
return { ok: true, message: '已写入商品描述' };
|
||||
}
|
||||
|
||||
/** 按名称匹配类目规格目录;无目录时建自由轴 */
|
||||
/** 按名称匹配类目规格目录;无目录时建自由轴。同轴按位置复用槽位 id,改文案保留 SKU。 */
|
||||
function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
const raw = args.axes;
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
@@ -3038,6 +3160,12 @@ function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
const maxAxes = Math.min(2, Math.max(1, specCatalog.value.length || 2));
|
||||
const limited = raw.slice(0, maxAxes);
|
||||
const usedCatalog = new Set<string>();
|
||||
const prevByCatalog = new Map(
|
||||
specAxes.value.map((a) => [a.catalogKey, a] as const),
|
||||
);
|
||||
const prevByName = new Map(
|
||||
specAxes.value.map((a) => [a.name, a] as const),
|
||||
);
|
||||
const next: SpecAxis[] = [];
|
||||
|
||||
for (const item of limited) {
|
||||
@@ -3054,27 +3182,40 @@ function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
specCatalog.value.find(
|
||||
(c) =>
|
||||
!usedCatalog.has(c.catalogKey) &&
|
||||
(c.name === axisName || c.name.includes(axisName) || axisName.includes(c.name)),
|
||||
(c.name === axisName ||
|
||||
c.name.includes(axisName) ||
|
||||
axisName.includes(c.name)),
|
||||
) ||
|
||||
specCatalog.value.find((c) => !usedCatalog.has(c.catalogKey));
|
||||
|
||||
if (match) {
|
||||
usedCatalog.add(match.catalogKey);
|
||||
const prev =
|
||||
prevByCatalog.get(match.catalogKey) ||
|
||||
prevByName.get(match.name) ||
|
||||
prevByName.get(axisName);
|
||||
const axis = createAxisFromCatalog(match);
|
||||
axis.selectedValues =
|
||||
// 复用旧轴 rowId,便于 UI 稳定;槽位按位置复用 id
|
||||
if (prev) {
|
||||
axis.rowId = prev.rowId;
|
||||
}
|
||||
const tokens =
|
||||
labels.length > 0
|
||||
? labels.map((t) => resolveSpecValueToken(axis, t))
|
||||
: [''];
|
||||
axis.selectedValues = mergeSpecValueSlots(prev?.selectedValues, tokens);
|
||||
next.push(axis);
|
||||
} else {
|
||||
const key = `agent_${axisName}_${specAxisRowSeq}`;
|
||||
const prev = prevByName.get(axisName);
|
||||
const key = prev?.key || `agent_${axisName}_${specAxisRowSeq}`;
|
||||
const tokens = labels.length > 0 ? labels : [''];
|
||||
next.push({
|
||||
rowId: specAxisRowSeq++,
|
||||
rowId: prev?.rowId ?? specAxisRowSeq++,
|
||||
catalogKey: key,
|
||||
key,
|
||||
name: axisName,
|
||||
presetOptions: [],
|
||||
selectedValues: labels.length > 0 ? labels : [''],
|
||||
selectedValues: mergeSpecValueSlots(prev?.selectedValues, tokens),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3092,11 +3233,6 @@ function applySetSpecAxes(args: Record<string, unknown>) {
|
||||
|
||||
function applyClientTool(name: string, args: Record<string, unknown>) {
|
||||
switch (name) {
|
||||
case 'ui_get_publish_snapshot':
|
||||
return {
|
||||
ok: true,
|
||||
message: '快照已由请求体注入,无需前端写入',
|
||||
};
|
||||
case 'ui_set_goods_name':
|
||||
return applySetGoodsName(args);
|
||||
case 'ui_set_goods_desc':
|
||||
@@ -3598,7 +3734,7 @@ onBeforeUnmount(() => {
|
||||
type="info"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
message="默认一条「款式」;最多两种规格。拖拽手柄可调规格轴与规格值顺序;失焦后更新下方 SKU 组合。"
|
||||
message="默认一条「款式」;最多两种规格。拖拽可调顺序。规格文案可改,已填商家编码会保留;增删规格值才会增删 SKU 行。"
|
||||
/>
|
||||
<Empty
|
||||
v-if="specCatalog.length === 0"
|
||||
@@ -3633,8 +3769,8 @@ onBeforeUnmount(() => {
|
||||
class="flex flex-wrap items-center gap-2"
|
||||
>
|
||||
<div
|
||||
v-for="(_val, vi) in axis.selectedValues"
|
||||
:key="`${axis.rowId}_val_${vi}`"
|
||||
v-for="(slot, vi) in axis.selectedValues"
|
||||
:key="slot.id"
|
||||
class="spec-value-chip flex items-center gap-1"
|
||||
:data-spec-value-input="`${axis.rowId}_${vi}`"
|
||||
>
|
||||
|
||||
+12
-5
@@ -293,14 +293,15 @@ function onStreamTool(payload: { phase: string; label: string }) {
|
||||
toolStatusLabel.value = payload.label;
|
||||
void nextTick().then(scrollChatToBottom);
|
||||
} else if (payload.phase === 'end') {
|
||||
toolStatusLabel.value = payload.label;
|
||||
// 结束后清状态,避免卡在「读取发布表单…」直到下一段 token
|
||||
toolStatusActive.value = false;
|
||||
toolStatusLabel.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
function onClientTool(call: AgentVO.ClientToolCall) {
|
||||
const api = props.editorApi;
|
||||
if (!api) return;
|
||||
if (call.name === 'ui_get_publish_snapshot') return;
|
||||
const result = api.applyClientTool(call.name, call.args || {});
|
||||
if (!result.ok) {
|
||||
message.warning(result.message || '表单写入失败');
|
||||
@@ -344,9 +345,15 @@ async function send(textOverride?: string) {
|
||||
await nextTick();
|
||||
scrollChatToBottom();
|
||||
|
||||
const formSnapshot = props.editorApi?.getFormSnapshot() as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
const formSnapshot = (() => {
|
||||
try {
|
||||
return props.editorApi?.getFormSnapshot?.() as
|
||||
| Record<string, unknown>
|
||||
| undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
abort?.abort();
|
||||
abort = streamAgentChat({
|
||||
|
||||
Reference in New Issue
Block a user