From 21cd9778ae630bdc13b51365e8462ca09b7dc5fe Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Tue, 22 Sep 2026 11:27:37 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=8E=BB=E6=8E=89=E5=BC=B9?= =?UTF-8?q?=E7=AA=97=E5=8F=91=E5=B8=83=E5=B9=B6=E5=B0=86=E5=8F=91=E5=B8=83?= =?UTF-8?q?=E7=BC=96=E8=BE=91=E5=99=A8=E6=8B=86=E4=B8=BA=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E5=A3=B3=E4=B8=8E=20composables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/PddGoodsPublishEditor.vue | 4259 ----------------- .../goods/components/PddGoodsPublishModal.vue | 75 - .../src/views/channel/pdd/goods/index.vue | 12 - .../views/channel/pdd/goods/publish/edit.vue | 7 +- .../goods/publish/editor/PddPublishEditor.vue | 811 ++++ .../pdd/goods/publish/editor/SkuTableCard.vue | 277 ++ .../pdd/goods/publish/editor/SpecAxesCard.vue | 158 + .../channel/pdd/goods/publish/editor/types.ts | 200 + .../goods/publish/editor/use-publish-agent.ts | 238 + .../publish/editor/use-publish-category.ts | 742 +++ .../goods/publish/editor/use-publish-draft.ts | 854 ++++ .../publish/editor/use-publish-images.ts | 361 ++ .../goods/publish/editor/use-publish-sku.ts | 699 +++ .../goods/publish/editor/use-publish-specs.ts | 629 +++ 14 files changed, 4972 insertions(+), 4350 deletions(-) delete mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishEditor.vue delete mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishModal.vue create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/PddPublishEditor.vue create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SkuTableCard.vue create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SpecAxesCard.vue create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/types.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-agent.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-category.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-draft.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-images.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-sku.ts create mode 100644 apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-specs.ts diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishEditor.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishEditor.vue deleted file mode 100644 index 3d990e2e..00000000 --- a/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishEditor.vue +++ /dev/null @@ -1,4259 +0,0 @@ - - - - - diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishModal.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishModal.vue deleted file mode 100644 index bbff2e35..00000000 --- a/apps/web/apps/web-antd/src/views/channel/pdd/goods/components/PddGoodsPublishModal.vue +++ /dev/null @@ -1,75 +0,0 @@ - - - diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/index.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/index.vue index 0f332d04..3c04b1c0 100644 --- a/apps/web/apps/web-antd/src/views/channel/pdd/goods/index.vue +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/index.vue @@ -16,15 +16,12 @@ import PddShopColPage from '#/views/channel/pdd/components/PddShopColPage.vue'; import PddShopDetailModal from '#/views/channel/pdd/shop/components/PddShopDetailModal.vue'; import PddGoodsDetailDrawer from './components/PddGoodsDetailDrawer.vue'; -import PddGoodsPublishModal from './components/PddGoodsPublishModal.vue'; defineOptions({ name: 'PddGoodsManagement' }); const loading = ref(false); const detailDrawerRef = ref>(); const shopDetailModalRef = ref>(); -const publishOpen = ref(false); -const publishHasDraft = ref(false); /** 左侧选中的拼多多渠道店铺 ID */ const selectedShopId = ref(undefined); const shopNameById = ref>({}); @@ -309,9 +306,6 @@ onMounted(async () => { - @@ -384,12 +378,6 @@ onMounted(async () => { - diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/edit.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/edit.vue index 7f12e001..70149a86 100644 --- a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/edit.vue +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/edit.vue @@ -6,8 +6,8 @@ import { Page } from '@vben/common-ui'; import { useColSidebarLayout } from '#/store/col-sidebar-layout'; -import PddGoodsPublishEditor from '../components/PddGoodsPublishEditor.vue'; import PddPublishAgentPanel from './PddPublishAgentPanel.vue'; +import PddPublishEditor from './editor/PddPublishEditor.vue'; import type { PublishEditorAgentApi } from './publish-agent-commands'; defineOptions({ name: 'PddGoodsPublishDeskEdit' }); @@ -63,7 +63,7 @@ function goBack() { #{{ draftId }} - +
@@ -73,10 +73,9 @@ function goBack() { class="flex min-h-0 flex-1 overflow-hidden" >
- +/** + * 拼多多发布编辑器壳:编排 form + composables + 卡片,不含业务算法细节。 + */ +import type { ProductVO } from '#/api/ec/product/types'; + +import { + onBeforeUnmount, + onMounted, + reactive, + ref, + watch, +} from 'vue'; + +import { + CheckCircleOutlined, + CloseCircleOutlined, + ExclamationCircleOutlined, + LoadingOutlined, + PlusOutlined, + WarningOutlined, +} from '@ant-design/icons-vue'; + +import { + Button, + Card, + Cascader, + Descriptions, + Empty, + Form, + Image, + Input, + InputNumber, + Select, + Space, + Spin, + Switch, + Table, + Tag, + Tooltip, + Upload, + message, +} from 'ant-design-vue'; + +import { getProductPageApi } from '#/api/ec/product'; + +import SpecAxesCard from './SpecAxesCard.vue'; +import SkuTableCard from './SkuTableCard.vue'; +import type { SpecAxis, SpecCatalogItem, SkuRow } from './types'; +import { createEmptyPublishForm } from './types'; +import { usePublishAgent } from './use-publish-agent'; +import { usePublishCategory } from './use-publish-category'; +import { usePublishDraft } from './use-publish-draft'; +import { usePublishImages } from './use-publish-images'; +import { usePublishSku } from './use-publish-sku'; +import { usePublishSpecs } from './use-publish-specs'; + +defineOptions({ name: 'PddPublishEditor' }); + +const props = withDefaults( + defineProps<{ + /** 是否激活(页面挂载) */ + open?: boolean; + presetPddShopId?: number | null; + /** 服务端草稿 ID(工作台编辑) */ + draftId?: number | null; + }>(), + { + open: true, + draftId: null, + }, +); + +const emit = defineEmits<{ + success: []; + close: []; + 'draft-saved': [draftId: number]; +}>(); + +const form = reactive(createEmptyPublishForm()); +const hydratingDraft = ref(false); +const skuRows = ref([]); +const specAxes = ref([]); +const specCatalog = ref([]); +const productOptions = ref<{ label: string; value: number; name: string }[]>( + [], +); + +/** 环依赖:specs ↔ sku,用可变实现在装配后回填 */ +let syncSkuRowsFromSpecsImpl: (opts?: { + orphanByIndex?: boolean; +}) => SkuRow[] = () => []; +let comboKeyFromSlotsImpl: ( + parts: Array<{ axisKey: string; slotId: number }>, +) => string = () => ''; +let rebuildPreservingImpl = () => {}; +let buildSpecCatalogImpl = (): SpecCatalogItem[] => []; +let clearSkuRowsImpl = () => {}; + +const images = usePublishImages(skuRows); + +const category = usePublishCategory({ + form, + hydratingDraft, + clearSkuRows: () => clearSkuRowsImpl(), + specAxes, + specCatalog, + rebuildSpecCatalogPreservingUserData: () => rebuildPreservingImpl(), + buildSpecCatalog: () => buildSpecCatalogImpl(), +}); + +const specs = usePublishSpecs({ + saleProps: category.saleProps, + parentSpecs: category.parentSpecs, + specAxes, + specCatalog, + skuRows, + syncSkuRowsFromSpecs: (opts) => syncSkuRowsFromSpecsImpl(opts), + comboKeyFromSlots: (parts) => comboKeyFromSlotsImpl(parts), +}); + +const sku = usePublishSku({ + skuRows, + specAxes, + catTemplate: category.catTemplate, + revokeUploadFiles: images.revokeUploadFiles, + specHelpers: { + effectiveSpecSlots: specs.effectiveSpecSlots, + labelOfAxisValue: specs.labelOfAxisValue, + resolveSpecValueToken: specs.resolveSpecValueToken, + specValueAutoOptions: specs.specValueAutoOptions, + }, +}); + +syncSkuRowsFromSpecsImpl = sku.syncSkuRowsFromSpecs; +comboKeyFromSlotsImpl = sku.comboKeyFromSlots; +rebuildPreservingImpl = specs.rebuildSpecCatalogPreservingUserData; +buildSpecCatalogImpl = specs.buildSpecCatalog; +clearSkuRowsImpl = sku.clearSkuRows; + +async function loadProducts(keyword = '') { + try { + const data = await getProductPageApi({ + page: 1, + pageSize: 50, + filters: keyword ? { keywords: keyword } : {}, + }); + productOptions.value = (data.records ?? []).map((p: ProductVO.Info) => ({ + label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`, + value: p.id, + name: p.name, + })); + } catch { + message.error('加载内部商品失败'); + } +} + +function handleClose() { + resetAll(); + emit('close'); +} + +const draft = usePublishDraft({ + form, + hydratingDraft, + emit, + closeEditor: handleClose, + loadShops: category.loadShops, + loadRootCats: category.loadRootCats, + loadLogistics: category.loadLogistics, + loadCostTemplateDetail: category.loadCostTemplateDetail, + loadCatContextForHydrate: category.loadCatContextForHydrate, + resolveFullCatPath: category.resolveFullCatPath, + catAuthAuthorized: category.catAuthAuthorized, + catAuthMessage: category.catAuthMessage, + catAuthChecking: category.catAuthChecking, + selectedCatPathLabel: category.selectedCatPathLabel, + nonSaleProps: category.nonSaleProps, + productOptions, + loadProducts, + specAxes, + specCatalog, + normalizeSpecValueSlots: specs.normalizeSpecValueSlots, + rebuildSpecCatalogAndSeed: specs.rebuildSpecCatalogAndSeed, + labelOfAxisValue: specs.labelOfAxisValue, + effectiveSpecValues: specs.effectiveSpecValues, + refreshSpecSortables: specs.refreshSpecSortables, + bumpSpecAxisRowSeqFromIds: specs.bumpSpecAxisRowSeqFromIds, + skuRows, + loadSkuCandidates: sku.loadSkuCandidates, + comboKeyFromSlots: sku.comboKeyFromSlots, + bumpSkuRowSeqFromKeys: sku.bumpSkuRowSeqFromKeys, + nextSkuRowKey: sku.nextSkuRowKey, + carouselFileList: images.carouselFileList, + detailFileList: images.detailFileList, + ensurePersistedUploads: images.ensurePersistedUploads, + toUploadFilesFromPersisted: images.toUploadFilesFromPersisted, +}); + +const agent = usePublishAgent({ + form, + specAxes, + specCatalog, + skuRows, + effectiveSpecValues: specs.effectiveSpecValues, + labelOfAxisValue: specs.labelOfAxisValue, + skuRowValueLabels: sku.skuRowValueLabels, + createAxisFromCatalog: specs.createAxisFromCatalog, + mergeSpecValueSlots: specs.mergeSpecValueSlots, + resolveSpecValueToken: specs.resolveSpecValueToken, + nextSpecAxisRowId: specs.nextSpecAxisRowId, + syncSkuRowsFromSpecs: sku.syncSkuRowsFromSpecs, + applySkuAssignmentsByOutSkuSn: sku.applySkuAssignmentsByOutSkuSn, + revokeUploadFiles: images.revokeUploadFiles, +}); + +watch( + () => form.primaryProductId, + (id) => { + if (!id) return; + const p = productOptions.value.find((x) => x.value === id); + if (p && !form.goodsName) { + form.goodsName = p.name; + } + }, +); + +watch( + () => props.open ?? true, + (v) => { + if (v) { + if (!props.draftId) { + form.pddShopId = props.presetPddShopId ?? undefined; + } + void category.loadShops(); + void loadProducts(); + void sku.loadSkuCandidates(); + if (props.draftId) { + void draft.hydrateFromDraft(props.draftId); + } + } + }, +); + +onMounted(() => { + if (!(props.open ?? true)) return; + if (!props.draftId) { + form.pddShopId = props.presetPddShopId ?? undefined; + } + void category.loadShops(); + void loadProducts(); + void sku.loadSkuCandidates(); + if (props.draftId) { + void draft.hydrateFromDraft(props.draftId); + } +}); + +function resetAll() { + draft.submitting.value = false; + Object.assign(form, createEmptyPublishForm()); + category.resetCategoryState(); + images.clearLocalImages(); + sku.clearSkuRows(); + specAxes.value = []; + specCatalog.value = []; + sku.skuSpecDraft.value = {}; + sku.bindPickSkuIds.value = []; + sku.clearAllOutSkuSnTimers(); + specs.destroySpecSortables(); + specs.resetSpecValueSlotSeq(); + specs.resetSpecAxisRowSeq(); + sku.resetSkuRowSeq(); + images.resetUploadUidSeq(); + draft.clearSpecIdCache(); + draft.resetBoundDraftId(); +} + +defineExpose({ + getFormSnapshot: agent.getFormSnapshot, + applyClientTool: agent.applyClientTool, +}); + +onBeforeUnmount(() => { + images.clearLocalImages(); + sku.clearAllOutSkuSnTimers(); + specs.destroySpecSortables(); + category.clearCatSearchTimer(); +}); + +// 解构供模板使用 +const { + shopOptions, + logisticsOptions, + costTemplateDetail, + costTemplateDetailLoading, + catSourceDegraded, + catDegradeHint, + catAuthHint, + catAuthAuthorized, + catAuthChecking, + localCatReady, + catsLoading, + catSearchLoading, + catCascaderSearch, + displayCatOptions, + catLoadData, + catCascaderFilter, + catDisplayRender, + onCatCascaderSearch, + onCatChange, + loadShops, + loadCostTemplateDetail, + nonSaleProps, +} = category; + +const { + carouselFileList, + detailFileList, + previewVisible, + previewImage, + beforeUploadCarousel, + beforeUploadDetail, + beforeUploadSku, + onRemoveCarousel, + onRemoveDetail, + onSkuThumbFileListChange, + onPreviewUploadFile, + setPreviewVisible, +} = images; + +const { + canAddSpecAxis, + catalogOptionsForAxis, + onAxisCatalogChange, + addSpecAxis, + removeSpecAxis, + specValueDisplay, + specValueAutoOptions, + onSpecValueInput, + onSpecValueCommit, + onSpecValueEnter, + addSpecValueSlot, + removeSpecValue, +} = specs; + +const { + bindPickSkuIds, + skuSelectOptions, + skuTableColumns, + skuTableScrollX, + debouncedLoadSkuCandidates, + onSkuSelectDropdownOpen, + skuSpecCellDisplay, + skuSpecCellAutoOptions, + onSkuSpecCellInput, + onSkuSpecCellCommit, + onOutSkuSnChange, + onOutSkuSnBlur, + bindInternalSku, + applyInternalSkusInOrder, + clearInternalSkuBindings, +} = sku; + +const { + draftSaving, + platformPushing, + submitting, + saveDeskDraft, + pushToPlatformDraft, + handleSubmit, +} = draft; + +function onSpecAxesListRef(el: HTMLElement | null) { + specs.specAxesListRef.value = el; +} + +function onSkuTableWrapRef(el: HTMLElement | null) { + sku.skuTableWrapRef.value = el; +} + + + diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SkuTableCard.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SkuTableCard.vue new file mode 100644 index 00000000..15cf52ac --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SkuTableCard.vue @@ -0,0 +1,277 @@ + + + + + diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SpecAxesCard.vue b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SpecAxesCard.vue new file mode 100644 index 00000000..415a7a54 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/SpecAxesCard.vue @@ -0,0 +1,158 @@ + + + diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/types.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/types.ts new file mode 100644 index 00000000..8aa3b94e --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/types.ts @@ -0,0 +1,200 @@ +import type { UploadFile } from 'ant-design-vue'; + +/** 草稿中持久化的已上传图片 */ +export type PersistedUpload = { + fileId: number; + name?: string; + url?: string; +}; + +export type SkuRow = { + key: number; + /** 各维规格值槽位 id 组合键;与展示文案无关,改名不丢编码 */ + comboKey: string; + internalSkuId?: number; + productName?: string; + /** 关联的内部 SKU 名称(展示用) */ + internalSkuName?: string; + /** + * 商家编码是否命中内部 SKU: + * idle=未校验/空;checking=请求中;matched=是;unmatched=非内部SKU + */ + codeMatchStatus?: 'idle' | 'checking' | 'matched' | 'unmatched'; + skuName: string; + outSkuSn: string; + priceYuan?: number; + multiPriceYuan?: number; + quantity: number; + weight: number; + thumbFileList: UploadFile[]; + saleValues: Record; +}; + +/** 类目可选父规格(下拉候选);用户手动添加进编辑区 */ +export type SpecCatalogItem = { + catalogKey: string; + name: string; + parentSpecId: number; + refPid?: number; + templatePid?: number; + valueUnit?: string; + presetOptions: { + label: string; + value: string; + vid?: number; + specId?: number; + }[]; +}; + +/** + * 规格值槽位:id 稳定标识身份,token 为买家可见描述(可改名)。 + * SKU 行按各维 slot id 组合对齐,改文案不丢商家编码。 + */ +export type SpecValueSlot = { + id: number; + token: string; +}; + +/** 已添加的规格轴:默认仅「款式」一条,其余手动添加 */ +export type SpecAxis = { + rowId: number; + catalogKey: string; + key: string; + name: string; + parentSpecId?: number; + refPid?: number; + templatePid?: number; + valueUnit?: string; + presetOptions: SpecCatalogItem['presetOptions']; + selectedValues: SpecValueSlot[]; +}; + +/** Cascader 节点(本地树 / 搜索命中) */ +export type CatCascaderNode = { + label?: string; + value: number; + isLeaf?: boolean; + loading?: boolean; + children?: CatCascaderNode[]; + /** 搜索命中时带回完整 path,便于回填 */ + pathIds?: string; +}; + +export type DefaultOptionType = { + label?: any; + value?: any; + children?: any[]; +}; + +/** 发布表单字段(店铺/类目/标题等) */ +export type PublishFormFields = { + pddShopId: number | undefined; + primaryProductId: number | undefined; + goodsName: string; + goodsDesc: string; + catPath: number[]; + catId: number | undefined; + costTemplateId: number | undefined; + marketPriceYuan: number | undefined; + shipmentLimitSecond: number; + isFolt: boolean; + isPreSale: boolean; + isRefundable: boolean; + secondHand: boolean; + twoPiecesDiscount: number; + goodsPropValues: Record; +}; + +/** 创建空白发布表单字段 */ +export function createEmptyPublishForm(): PublishFormFields { + return { + pddShopId: undefined, + primaryProductId: undefined, + goodsName: '', + goodsDesc: '', + catPath: [], + catId: undefined, + costTemplateId: undefined, + marketPriceYuan: undefined, + shipmentLimitSecond: 172800, + isFolt: true, + isPreSale: false, + isRefundable: true, + secondHand: false, + twoPiecesDiscount: 95, + goodsPropValues: {}, + }; +} + +/** 规格值槽位序号工厂:跨改名保持 id,草稿回填可抬升序号 */ +export function createSpecValueSlotFactory() { + 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; + } + + function resetSpecValueSlotSeq() { + specValueSlotSeq = 1; + } + + return { + createSpecValueSlot, + normalizeSpecValueSlots, + mergeSpecValueSlots, + resetSpecValueSlotSeq, + }; +} diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-agent.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-agent.ts new file mode 100644 index 00000000..72ffdf71 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-agent.ts @@ -0,0 +1,238 @@ +import type { Ref } from 'vue'; + +import type { + ClientToolResult, + PublishFormSnapshot, +} from '../publish-agent-commands'; +import type { + PublishFormFields, + SpecAxis, + SpecCatalogItem, + SkuRow, +} from './types'; + +/** + * 智能体命令面:读表单快照 + 执行 ui_*(含 skuAssignments / 槽位 id 复用)。 + */ +export function usePublishAgent(options: { + form: PublishFormFields; + specAxes: Ref; + specCatalog: Ref; + skuRows: Ref; + effectiveSpecValues: (axis: SpecAxis) => string[]; + labelOfAxisValue: (axis: SpecAxis, value: string) => string; + skuRowValueLabels: (row: SkuRow) => string[]; + createAxisFromCatalog: (item: SpecCatalogItem) => SpecAxis; + mergeSpecValueSlots: ( + prevSlots: SpecAxis['selectedValues'] | undefined, + tokens: string[], + ) => SpecAxis['selectedValues']; + resolveSpecValueToken: (axis: SpecAxis, raw: string) => string; + nextSpecAxisRowId: () => number; + syncSkuRowsFromSpecs: (opts?: { orphanByIndex?: boolean }) => SkuRow[]; + applySkuAssignmentsByOutSkuSn: ( + assignments: Array<{ outSkuSn: string; values: string[] }>, + prevRows: SkuRow[], + ) => number; + revokeUploadFiles: (files?: SkuRow['thumbFileList']) => void; +}) { + const { + form, + specAxes, + specCatalog, + skuRows, + effectiveSpecValues, + labelOfAxisValue, + skuRowValueLabels, + createAxisFromCatalog, + mergeSpecValueSlots, + resolveSpecValueToken, + nextSpecAxisRowId, + syncSkuRowsFromSpecs, + applySkuAssignmentsByOutSkuSn, + revokeUploadFiles, + } = options; + + function getFormSnapshot(): PublishFormSnapshot { + return { + goodsName: form.goodsName, + goodsDesc: form.goodsDesc, + pddShopId: form.pddShopId, + catId: form.catId, + marketPriceYuan: form.marketPriceYuan, + costTemplateId: form.costTemplateId, + shipmentLimitSecond: form.shipmentLimitSecond, + twoPiecesDiscount: form.twoPiecesDiscount, + specAxes: specAxes.value.map((a) => ({ + name: a.name, + catalogKey: a.catalogKey, + values: effectiveSpecValues(a).map((v) => labelOfAxisValue(a, v)), + })), + /** outSkuSn 为 SKU 唯一身份;values 与 specAxes 同序,便于 agent 重排 */ + skuRows: skuRows.value.map((r) => ({ + outSkuSn: r.outSkuSn, + values: skuRowValueLabels(r), + skuName: r.skuName, + quantity: r.quantity, + weight: r.weight, + productName: r.productName, + internalSkuName: r.internalSkuName, + })), + specCatalog: specCatalog.value.map((c) => ({ + name: c.name, + catalogKey: c.catalogKey, + })), + }; + } + + function applySetGoodsName(args: Record): ClientToolResult { + const name = String(args.goodsName ?? '').trim(); + if (!name) return { ok: false, message: '标题为空' }; + form.goodsName = name.slice(0, 120); + return { ok: true, message: `已写入标题:${form.goodsName}` }; + } + + function applySetGoodsDesc(args: Record): ClientToolResult { + form.goodsDesc = String(args.goodsDesc ?? ''); + return { ok: true, message: '已写入商品描述' }; + } + + function parseSkuAssignments(raw: unknown) { + if (!Array.isArray(raw)) return []; + const list: Array<{ outSkuSn: string; values: string[] }> = []; + for (const item of raw) { + if (!item || typeof item !== 'object') continue; + const row = item as { outSkuSn?: unknown; values?: unknown }; + const outSkuSn = String(row.outSkuSn ?? '').trim(); + const values = Array.isArray(row.values) + ? row.values.map((v) => String(v ?? '').trim()) + : []; + if (!outSkuSn || values.length === 0) continue; + list.push({ outSkuSn, values }); + } + return list; + } + + /** 按名称匹配类目规格目录;无目录时建自由轴。同轴按位置复用槽位 id,改文案保留 SKU。 */ + function applySetSpecAxes(args: Record): ClientToolResult { + const raw = args.axes; + if (!Array.isArray(raw) || raw.length === 0) { + return { ok: false, message: '规格轴为空' }; + } + const assignments = parseSkuAssignments(args.skuAssignments); + const maxAxes = Math.min(2, Math.max(1, specCatalog.value.length || 2)); + const limited = raw.slice(0, maxAxes); + const usedCatalog = new Set(); + 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 prevSkuRows = skuRows.value.map((r) => r); + const next: SpecAxis[] = []; + + for (const item of limited) { + if (!item || typeof item !== 'object') continue; + const row = item as { name?: unknown; values?: unknown }; + const axisName = String(row.name ?? '').trim(); + const valuesRaw = Array.isArray(row.values) ? row.values : []; + const labels = valuesRaw + .map((v) => String(v ?? '').trim()) + .filter(Boolean); + if (!axisName) continue; + + const match = + specCatalog.value.find( + (c) => + !usedCatalog.has(c.catalogKey) && + (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); + // 复用旧轴 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 prev = prevByName.get(axisName); + const rowId = prev?.rowId ?? nextSpecAxisRowId(); + const key = prev?.key || `agent_${axisName}_${rowId}`; + const tokens = labels.length > 0 ? labels : ['']; + next.push({ + rowId, + catalogKey: key, + key, + name: axisName, + presetOptions: [], + selectedValues: mergeSpecValueSlots(prev?.selectedValues, tokens), + }); + } + } + + if (next.length === 0) { + return { ok: false, message: '未能解析任何规格维' }; + } + specAxes.value = next; + // 有编码绑定时关闭行序兜底,完全按 agent 的 outSkuSn 对齐 + const deferredOrphans = syncSkuRowsFromSpecs({ + orphanByIndex: assignments.length === 0, + }); + const bound = + assignments.length > 0 + ? applySkuAssignmentsByOutSkuSn(assignments, prevSkuRows) + : 0; + for (const orphan of deferredOrphans) { + const adopted = skuRows.value.some((r) => r.key === orphan.key); + if (!adopted) { + revokeUploadFiles(orphan.thumbFileList); + } + } + return { + ok: true, + message: + assignments.length > 0 + ? `已设置 ${next.length} 个规格维,SKU ${skuRows.value.length} 条,按编码绑定 ${bound}/${assignments.length}` + : `已设置 ${next.length} 个规格维,SKU 行 ${skuRows.value.length} 条`, + }; + } + + function applyClientTool( + name: string, + args: Record, + ): ClientToolResult { + switch (name) { + case 'ui_set_goods_name': + return applySetGoodsName(args); + case 'ui_set_goods_desc': + return applySetGoodsDesc(args); + case 'ui_set_spec_axes': + return applySetSpecAxes(args); + default: + return { ok: false, message: `未支持的前端工具:${name}` }; + } + } + + return { + getFormSnapshot, + applyClientTool, + applySetSpecAxes, + }; +} + +export type PublishAgentApi = ReturnType; diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-category.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-category.ts new file mode 100644 index 00000000..21797f75 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-category.ts @@ -0,0 +1,742 @@ +import type { CascaderProps } from 'ant-design-vue'; +import type { Ref } from 'vue'; + +import { computed, ref, watch } from 'vue'; + +import { message } from 'ant-design-vue'; + +import type { PddGoodsPublishVO } from '#/api/channel/pdd/goods'; +import { + checkPddPublishCatAuthApi, + getPddPublishCatTemplateApi, + getPddPublishLogisticsTemplateDetailApi, + listPddPublishCatsApi, + listPddPublishLogisticsApi, + listPddPublishParentSpecsApi, +} from '#/api/channel/pdd/goods'; +import { + getPddCatSyncStatusApi, + listPddCatChildrenApi, + searchPddCatsApi, +} from '#/api/channel/pdd/cat'; +import { getPddShopPageApi } from '#/api/channel/pdd/shop'; + +import type { + CatCascaderNode, + DefaultOptionType, + PublishFormFields, + SpecAxis, + SpecCatalogItem, +} from './types'; + +/** + * 类目树 / Cascader / 发布权 / 模板与运费加载。 + * 规格重建与 SKU 清空由壳层注入,避免与 specs/sku 环依赖。 + */ +export function usePublishCategory(options: { + form: PublishFormFields; + hydratingDraft: Ref; + /** 切换店铺/清空类目时清空 SKU */ + clearSkuRows: () => void; + specAxes: Ref; + specCatalog: Ref; + rebuildSpecCatalogPreservingUserData: () => void; + buildSpecCatalog: () => SpecCatalogItem[]; +}) { + const { + form, + hydratingDraft, + clearSkuRows, + specAxes, + specCatalog, + rebuildSpecCatalogPreservingUserData, + buildSpecCatalog, + } = options; + + const shopOptions = ref<{ label: string; value: number }[]>([]); + const logisticsOptions = ref<{ label: string; value: number }[]>([]); + const costTemplateDetail = ref( + null, + ); + const costTemplateDetailLoading = ref(false); + const catTemplate = ref(null); + const parentSpecs = ref([]); + + const nonSaleProps = computed(() => + (catTemplate.value?.properties ?? []).filter((p) => !p.sale), + ); + const saleProps = computed(() => + (catTemplate.value?.properties ?? []).filter((p) => p.sale), + ); + + const rootCatOptions = ref([]); + const catsLoading = ref(false); + /** 已按 parent 拉过的类目,避免重复请求 */ + const loadedCatParents = ref>(new Set()); + + /** 本地库同步状态:仅 SUCCESS 走本地树 + 跨层搜索,其余降级拼多多授权类目接口 */ + const catSyncStatus = ref(null); + const localCatReady = computed(() => catSyncStatus.value === 'SUCCESS'); + const catSourceDegraded = computed(() => !localCatReady.value); + + /** Cascader 搜索框文案;本地就绪时用于跨层检索 */ + const catCascaderSearch = ref(''); + /** 本地跨层搜索命中(扁平叶子),非空时临时替换树选项 */ + const catSearchHitOptions = ref([]); + const catSearchLoading = ref(false); + let catSearchTimer: undefined | ReturnType; + /** 选中后展示的完整路径文案 */ + const selectedCatPathLabel = ref(''); + /** + * 搜索选中的叶子:清空搜索结果后仍挂到 options 上,避免 Cascader 只显示裸 catId。 + */ + const pinnedSelectedCat = ref(null); + + const displayCatOptions = computed(() => { + if (localCatReady.value && catCascaderSearch.value.trim()) { + return catSearchHitOptions.value; + } + const roots = rootCatOptions.value; + const pinned = pinnedSelectedCat.value; + if ( + pinned && + form.catPath.length === 1 && + form.catPath[0] === pinned.value && + !roots.some((r) => r.value === pinned.value) + ) { + return [pinned, ...roots]; + } + return roots; + }); + + /** Cascader 输入框展示:优先完整路径文案,避免只剩数字 ID */ + function catDisplayRender(info: { + labels: string[]; + selectedOptions?: DefaultOptionType[]; + }) { + if (selectedCatPathLabel.value) { + return selectedCatPathLabel.value; + } + const labels = (info.labels ?? []).filter( + (l) => l != null && String(l).trim() !== '', + ); + if (labels.length) { + return labels.join(' / '); + } + return ''; + } + + const catDegradeHint = computed(() => { + if (catSyncStatus.value === 'RUNNING') { + return '平台类目同步进行中:暂不可用本地跨层搜索,已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点'; + } + return '本地类目未就绪:已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点。同步成功后可跨层搜索'; + }); + + /** 当前选中叶子是否有发布权;null=未校验/不适用 */ + const catAuthAuthorized = ref(null); + const catAuthMessage = ref(''); + const catAuthChecking = ref(false); + + /** 类目发布权:图标 + Tooltip 文案 */ + const catAuthHint = computed(() => { + if (catAuthChecking.value) { + return { + title: '正在校验该类目是否有发布权…', + tone: 'info' as const, + }; + } + if (!form.catId) return null; + if (catAuthAuthorized.value === true) { + return { + title: '当前店铺有权发布该类目', + tone: 'success' as const, + }; + } + if (catAuthAuthorized.value === false) { + return { + title: catAuthMessage.value || '当前店铺无权发布该类目', + tone: 'error' as const, + }; + } + if (catAuthMessage.value) { + return { + title: catAuthMessage.value, + tone: 'warning' as const, + }; + } + return null; + }); + + async function refreshCatSyncStatus() { + try { + const s = await getPddCatSyncStatusApi(); + catSyncStatus.value = s?.status ?? null; + } catch { + // 无权限或失败时降级拼多多接口 + catSyncStatus.value = null; + } + } + + function mapLocalCatNode(c: { + catId: number; + catName?: string; + leaf?: boolean; + }): CatCascaderNode { + return { + label: c.catName || `类目${c.catId}`, + value: c.catId, + isLeaf: !!c.leaf, + }; + } + + function mapPopCatNode(c: PddGoodsPublishVO.Cat): CatCascaderNode { + return { + label: c.catName, + value: c.catId, + isLeaf: !!c.leaf, + }; + } + + async function fetchCatChildren( + parentCatId: number, + ): Promise { + if (localCatReady.value) { + const list = await listPddCatChildrenApi({ parentCatId }); + return list.map(mapLocalCatNode); + } + if (!form.pddShopId) { + return []; + } + const list = await listPddPublishCatsApi({ + pddShopId: form.pddShopId, + parentCatId, + }); + return list.map(mapPopCatNode); + } + + /** Cascader 搜索选中后 form.catPath 可能只有叶子;完整路径在 pinned.pathIds */ + function parseCatPathIds(pathIds?: string | null): number[] { + if (!pathIds) return []; + return pathIds + .split('/') + .map((x) => Number(x)) + .filter((n) => Number.isFinite(n) && n > 0); + } + + /** 权限校验 / 草稿持久化用的完整类目路径 */ + function resolveFullCatPath(): number[] { + const fromPinned = parseCatPathIds(pinnedSelectedCat.value?.pathIds); + if (fromPinned.length > 0) { + return fromPinned; + } + if (form.catPath.length > 0) { + return [...form.catPath]; + } + return form.catId ? [form.catId] : []; + } + + /** + * 仅有叶子 id 时,用本地类目库补全 pathIds(搜索命中)。 + * 解决历史草稿只存了叶子导致鉴权失败的问题。 + */ + async function enrichCatPathIfNeeded( + catId: number, + path: number[], + pathLabel: string, + ): Promise<{ path: number[]; pathLabel: string }> { + if (path.length > 1) { + return { path, pathLabel }; + } + await refreshCatSyncStatus(); + if (!localCatReady.value) { + return { path: path.length ? path : [catId], pathLabel }; + } + const kw = + pathLabel + .split('/') + .map((s) => s.trim()) + .filter(Boolean) + .pop() || String(catId); + try { + const list = await searchPddCatsApi({ + keyword: kw, + leafOnly: true, + limit: 50, + }); + const hit = list.find((c) => c.catId === catId); + const enriched = parseCatPathIds(hit?.pathIds); + if (enriched.length > 0) { + return { + path: enriched, + pathLabel: hit?.pathNames || pathLabel || '', + }; + } + } catch { + // 补全失败则沿用原路径 + } + return { path: path.length ? path : [catId], pathLabel }; + } + + /** 选中叶子后再校验发布权(不在选择器展开时实时标权) */ + async function refreshCatAuth(fullPath: number[]) { + catAuthAuthorized.value = null; + catAuthMessage.value = ''; + if (!form.pddShopId || !fullPath.length) { + return; + } + // 降级已是授权树,展开选中默认有权 + if (!localCatReady.value) { + catAuthAuthorized.value = true; + return; + } + catAuthChecking.value = true; + try { + const res = await checkPddPublishCatAuthApi({ + pddShopId: form.pddShopId, + catPath: fullPath, + }); + catAuthAuthorized.value = !!res?.authorized; + catAuthMessage.value = + res?.message || + (res?.authorized + ? '当前店铺有权发布该类目' + : '当前店铺无权发布该类目'); + } catch (e: any) { + catAuthAuthorized.value = null; + catAuthMessage.value = e?.message || '类目权限校验失败'; + } finally { + catAuthChecking.value = false; + } + } + + /** 展开时按需加载子类目(本地库或拼多多接口) */ + const catLoadData: CascaderProps['loadData'] = async (selectedOptions) => { + // 跨层搜索结果为扁平叶子,不走懒加载 + if (localCatReady.value && catCascaderSearch.value.trim()) { + return; + } + const target = selectedOptions[selectedOptions.length - 1]; + if (!target) return; + const parentId = Number(target.value); + if (loadedCatParents.value.has(parentId) || target.isLeaf) { + return; + } + target.loading = true; + try { + const children = await fetchCatChildren(parentId); + target.children = children; + // 降级场景:接口未标 leaf 且无子时标叶子,避免空白展开 + if (children.length === 0) { + target.isLeaf = true; + } + loadedCatParents.value.add(parentId); + } catch (e: any) { + message.error(e?.message || '加载类目失败'); + } finally { + target.loading = false; + } + }; + + /** Cascader 内置搜索:本地跨层时选项已是命中集;降级时仅过滤已加载节点 */ + function catCascaderFilter(inputValue: string, path: DefaultOptionType[]) { + if (localCatReady.value && inputValue.trim()) { + return true; + } + const kw = inputValue.trim().toLowerCase(); + if (!kw) return true; + return path.some((o) => String(o.label ?? '').toLowerCase().includes(kw)); + } + + function onCatCascaderSearch(keyword: string) { + catCascaderSearch.value = keyword ?? ''; + if (catSearchTimer) clearTimeout(catSearchTimer); + if (!localCatReady.value) { + catSearchHitOptions.value = []; + return; + } + const kw = String(keyword ?? '').trim(); + if (!kw) { + catSearchHitOptions.value = []; + catSearchLoading.value = false; + return; + } + catSearchTimer = setTimeout(async () => { + catSearchLoading.value = true; + try { + const list = await searchPddCatsApi({ + keyword: kw, + leafOnly: true, + limit: 50, + }); + catSearchHitOptions.value = list.map((c) => ({ + label: c.pathNames || c.catName || `类目${c.catId}`, + value: c.catId, + isLeaf: true, + pathIds: c.pathIds, + })); + } catch (e: any) { + message.error(e?.message || '搜索类目失败'); + catSearchHitOptions.value = []; + } finally { + catSearchLoading.value = false; + } + }, 280); + } + + async function loadShops(keyword = '') { + try { + const data = await getPddShopPageApi({ + page: 1, + pageSize: 200, + filters: keyword ? { mallName: keyword } : {}, + }); + shopOptions.value = (data.records ?? []).map((s) => ({ + label: s.mallName + ? `${s.mallName}${s.mallId != null ? ` (${s.mallId})` : ''}` + : `店铺#${s.id}`, + value: s.id, + })); + } catch { + message.error('加载渠道店铺失败'); + } + } + + async function loadRootCats() { + if (!form.pddShopId) { + rootCatOptions.value = []; + return; + } + catsLoading.value = true; + loadedCatParents.value = new Set(); + rootCatOptions.value = []; + catSearchHitOptions.value = []; + catCascaderSearch.value = ''; + pinnedSelectedCat.value = null; + try { + await refreshCatSyncStatus(); + const list = await fetchCatChildren(0); + rootCatOptions.value = list; + loadedCatParents.value.add(0); + } catch (e: any) { + message.error( + e?.message || + (localCatReady.value + ? '加载本地类目失败' + : '加载拼多多授权类目失败'), + ); + } finally { + catsLoading.value = false; + } + } + + async function applyCatSelection( + catId: number, + pathIds?: string, + pathLabel?: string, + ) { + const path = pathIds + ? pathIds + .split('/') + .map((x) => Number(x)) + .filter((n) => Number.isFinite(n) && n > 0) + : [catId]; + form.catPath = path; + form.catId = catId; + selectedCatPathLabel.value = pathLabel || ''; + catTemplate.value = null; + parentSpecs.value = []; + // 类目属性随模板变,需清空;规格/SKU 尽量沿用 + form.goodsPropValues = {}; + await refreshCatAuth(path); + if (!form.pddShopId || !form.catId) return; + if (catAuthAuthorized.value === false) { + return; + } + try { + const [tpl, specs] = await Promise.all([ + getPddPublishCatTemplateApi({ + pddShopId: form.pddShopId, + catId: form.catId, + }), + listPddPublishParentSpecsApi({ + pddShopId: form.pddShopId, + catId: form.catId, + }), + ]); + catTemplate.value = tpl; + parentSpecs.value = specs ?? []; + rebuildSpecCatalogPreservingUserData(); + } catch (e: any) { + message.error(e?.message || '加载类目模板失败'); + } + } + + async function loadLogistics() { + if (!form.pddShopId) return; + try { + const page = await listPddPublishLogisticsApi({ + pddShopId: form.pddShopId, + page: 1, + pageSize: 100, + goodsStatus: 0, + }); + logisticsOptions.value = (page.templates ?? []).map((t) => ({ + label: t.templateName || `模板#${t.templateId}`, + value: t.templateId, + })); + } catch (e: any) { + message.error(e?.message || '加载运费模板失败'); + } + } + + async function loadCostTemplateDetail(templateId?: number) { + costTemplateDetail.value = null; + if (!form.pddShopId || templateId == null) return; + costTemplateDetailLoading.value = true; + try { + costTemplateDetail.value = await getPddPublishLogisticsTemplateDetailApi({ + pddShopId: form.pddShopId, + costTemplateId: templateId, + }); + } catch (e: any) { + message.error(e?.message || '加载运费模板详情失败'); + } finally { + costTemplateDetailLoading.value = false; + } + } + + function buildCascaderPathLabel( + optionsList: CatCascaderNode[], + path: number[], + ): string { + const parts: string[] = []; + let nodes = optionsList; + for (const id of path) { + const found = nodes.find((n) => n.value === id); + if (!found) break; + if (found.label) parts.push(String(found.label)); + nodes = found.children ?? []; + } + return parts.join(' / '); + } + + function findCascaderNode( + optionsList: CatCascaderNode[], + path: number[], + ): CatCascaderNode | null { + let nodes = optionsList; + let found: CatCascaderNode | null = null; + for (const id of path) { + found = nodes.find((n) => n.value === id) ?? null; + if (!found) return null; + nodes = found.children ?? []; + } + return found; + } + + async function onCatChange(path: number[]) { + if (!path?.length) { + form.catPath = []; + form.catId = undefined; + selectedCatPathLabel.value = ''; + pinnedSelectedCat.value = null; + catAuthAuthorized.value = null; + catAuthMessage.value = ''; + catTemplate.value = null; + parentSpecs.value = []; + form.goodsPropValues = {}; + clearSkuRows(); + specAxes.value = []; + specCatalog.value = []; + return; + } + const searching = + localCatReady.value && !!catCascaderSearch.value.trim(); + const optionsList = searching + ? catSearchHitOptions.value + : rootCatOptions.value; + const leafOpt = findCascaderNode(optionsList, path); + // 级联展开到非叶子时只更新路径,不清空已填规格/SKU + if (leafOpt && leafOpt.isLeaf === false) { + form.catPath = path; + form.catId = undefined; + selectedCatPathLabel.value = ''; + pinnedSelectedCat.value = null; + catAuthAuthorized.value = null; + catAuthMessage.value = ''; + return; + } + const catId = path[path.length - 1]!; + const hit = + catSearchHitOptions.value.find((o) => o.value === catId) || + (pinnedSelectedCat.value?.value === catId + ? pinnedSelectedCat.value + : undefined); + const pathLabel = + hit?.label != null + ? String(hit.label) + : buildCascaderPathLabel(optionsList, path) || + (leafOpt?.label != null ? String(leafOpt.label) : undefined); + await applyCatSelection( + catId, + hit?.pathIds || path.join('/'), + pathLabel, + ); + // 搜索命中为扁平选项:钉住展示节点,Cascader 值用单级 id + if (hit?.pathIds || searching) { + const label = pathLabel || `类目${catId}`; + pinnedSelectedCat.value = { + label, + value: catId, + isLeaf: true, + // 完整路径必须留下,供鉴权与草稿持久化(Cascader 值仍用单级叶子) + pathIds: hit?.pathIds || path.join('/'), + }; + form.catPath = [catId]; + } else { + pinnedSelectedCat.value = null; + } + catCascaderSearch.value = ''; + catSearchHitOptions.value = []; + } + + /** 回填时加载类目模板/可选规格,不种子默认规格轴(由草稿数据恢复) */ + async function loadCatContextForHydrate( + catId: number, + path: number[], + pathLabel: string, + ) { + const enriched = await enrichCatPathIfNeeded(catId, path, pathLabel); + const safePath = enriched.path.length > 0 ? enriched.path : [catId]; + form.catId = catId; + selectedCatPathLabel.value = enriched.pathLabel || pathLabel || ''; + // Cascader 用钉住叶子 + 单级值展示;完整路径放 pathIds 供鉴权/再保存 + pinnedSelectedCat.value = { + label: selectedCatPathLabel.value || `类目${catId}`, + value: catId, + isLeaf: true, + pathIds: safePath.join('/'), + }; + form.catPath = [catId]; + await refreshCatAuth(safePath); + if (!form.pddShopId || catAuthAuthorized.value === false) { + return; + } + try { + const [tpl, specs] = await Promise.all([ + getPddPublishCatTemplateApi({ + pddShopId: form.pddShopId, + catId, + }), + listPddPublishParentSpecsApi({ + pddShopId: form.pddShopId, + catId, + }), + ]); + catTemplate.value = tpl; + parentSpecs.value = specs ?? []; + specCatalog.value = buildSpecCatalog(); + } catch (e: any) { + message.error(e?.message || '加载类目模板失败'); + } + } + + watch( + () => form.pddShopId, + (id) => { + // 草稿回填时只拉类目/运费,不清空已恢复的字段 + if (hydratingDraft.value) { + if (id) { + void loadRootCats(); + void loadLogistics(); + } + return; + } + form.catPath = []; + form.catId = undefined; + selectedCatPathLabel.value = ''; + catAuthAuthorized.value = null; + catAuthMessage.value = ''; + form.costTemplateId = undefined; + costTemplateDetail.value = null; + catTemplate.value = null; + parentSpecs.value = []; + clearSkuRows(); + specAxes.value = []; + specCatalog.value = []; + logisticsOptions.value = []; + form.goodsPropValues = {}; + catSearchHitOptions.value = []; + catCascaderSearch.value = ''; + rootCatOptions.value = []; + loadedCatParents.value = new Set(); + pinnedSelectedCat.value = null; + if (!id) return; + void loadRootCats(); + void loadLogistics(); + }, + ); + + function clearCatSearchTimer() { + if (catSearchTimer) clearTimeout(catSearchTimer); + } + + function resetCategoryState() { + selectedCatPathLabel.value = ''; + catAuthAuthorized.value = null; + catAuthMessage.value = ''; + costTemplateDetail.value = null; + catTemplate.value = null; + parentSpecs.value = []; + rootCatOptions.value = []; + catSearchHitOptions.value = []; + catCascaderSearch.value = ''; + logisticsOptions.value = []; + loadedCatParents.value = new Set(); + pinnedSelectedCat.value = null; + catSyncStatus.value = null; + } + + return { + shopOptions, + logisticsOptions, + costTemplateDetail, + costTemplateDetailLoading, + catTemplate, + parentSpecs, + nonSaleProps, + saleProps, + rootCatOptions, + catsLoading, + catSyncStatus, + localCatReady, + catSourceDegraded, + catCascaderSearch, + catSearchHitOptions, + catSearchLoading, + selectedCatPathLabel, + pinnedSelectedCat, + displayCatOptions, + catDisplayRender, + catDegradeHint, + catAuthAuthorized, + catAuthMessage, + catAuthChecking, + catAuthHint, + catLoadData, + catCascaderFilter, + onCatCascaderSearch, + loadShops, + loadRootCats, + loadLogistics, + loadCostTemplateDetail, + onCatChange, + resolveFullCatPath, + loadCatContextForHydrate, + clearCatSearchTimer, + resetCategoryState, + }; +} + +export type PublishCategoryApi = ReturnType; diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-draft.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-draft.ts new file mode 100644 index 00000000..0a0dd7d3 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-draft.ts @@ -0,0 +1,854 @@ +import type { UploadFile } from 'ant-design-vue'; +import type { ComputedRef, Ref } from 'vue'; + +import { nextTick, ref } from 'vue'; + +import { message } from 'ant-design-vue'; + +import type { + PddGoodsPublishDTO, + PddGoodsPublishVO, +} from '#/api/channel/pdd/goods'; +import { + createPddPublishDeskDraftApi, + createPddPublishSpecIdApi, + getPddPublishDeskDraftApi, + publishPddGoodsApi, + pushPddPublishDeskDraftApi, + updatePddPublishDeskDraftApi, +} from '#/api/channel/pdd/goods'; + +import type { + PersistedUpload, + PublishFormFields, + SpecAxis, + SpecCatalogItem, + SkuRow, +} from './types'; + +type EmitDraft = { + (e: 'draft-saved', draftId: number): void; + (e: 'success'): void; +}; + +/** + * 草稿回填 / 保存 / 推送 / 发布校验与 payload 构建。 + * 依赖类目、规格、SKU、图片各块已由壳层组装好的 refs 与方法。 + */ +export function usePublishDraft(options: { + form: PublishFormFields; + hydratingDraft: Ref; + emit: EmitDraft; + closeEditor: () => void; + // category + loadShops: (keyword?: string) => Promise; + loadRootCats: () => Promise; + loadLogistics: () => Promise; + loadCostTemplateDetail: (templateId?: number) => Promise; + loadCatContextForHydrate: ( + catId: number, + path: number[], + pathLabel: string, + ) => Promise; + resolveFullCatPath: () => number[]; + catAuthAuthorized: Ref; + catAuthMessage: Ref; + catAuthChecking: Ref; + selectedCatPathLabel: Ref; + nonSaleProps: ComputedRef; + // products + productOptions: Ref<{ label: string; value: number; name: string }[]>; + loadProducts: (keyword?: string) => Promise; + // specs + specAxes: Ref; + specCatalog: Ref; + normalizeSpecValueSlots: (raw: unknown) => SpecAxis['selectedValues']; + rebuildSpecCatalogAndSeed: () => void; + labelOfAxisValue: (axis: SpecAxis, value: string) => string; + effectiveSpecValues: (axis: SpecAxis) => string[]; + refreshSpecSortables: () => Promise; + bumpSpecAxisRowSeqFromIds: (ids: number[]) => void; + // sku + skuRows: Ref; + loadSkuCandidates: (keyword?: string) => Promise; + comboKeyFromSlots: ( + parts: Array<{ axisKey: string; slotId: number }>, + ) => string; + bumpSkuRowSeqFromKeys: (keys: number[]) => void; + nextSkuRowKey: () => number; + // images + carouselFileList: Ref; + detailFileList: Ref; + ensurePersistedUploads: (files: UploadFile[]) => Promise; + toUploadFilesFromPersisted: ( + items: PersistedUpload[], + ) => Promise; +}) { + const { + form, + hydratingDraft, + emit, + closeEditor, + loadShops, + loadRootCats, + loadLogistics, + loadCostTemplateDetail, + loadCatContextForHydrate, + resolveFullCatPath, + catAuthAuthorized, + catAuthMessage, + catAuthChecking, + selectedCatPathLabel, + nonSaleProps, + productOptions, + loadProducts, + specAxes, + specCatalog, + normalizeSpecValueSlots, + rebuildSpecCatalogAndSeed, + labelOfAxisValue, + effectiveSpecValues, + refreshSpecSortables, + bumpSpecAxisRowSeqFromIds, + skuRows, + loadSkuCandidates, + comboKeyFromSlots, + bumpSkuRowSeqFromKeys, + nextSkuRowKey, + carouselFileList, + detailFileList, + ensurePersistedUploads, + toUploadFilesFromPersisted, + } = options; + + const draftSaving = ref(false); + const platformPushing = ref(false); + const boundDraftId = ref(null); + const submitting = ref(false); + const specIdCache = new Map(); + + function yuanToFen(yuan?: number) { + if (yuan == null || Number.isNaN(yuan)) return undefined; + return Math.round(yuan * 100); + } + + async function resolveSpecId( + parentSpecId: number, + specName: string, + ): Promise { + const key = `${parentSpecId}::${specName}`; + const cached = specIdCache.get(key); + if (cached) return cached; + if (!form.pddShopId) throw new Error('未选择店铺'); + const res = await createPddPublishSpecIdApi({ + pddShopId: form.pddShopId, + parentSpecId, + specName, + }); + specIdCache.set(key, res.specId); + return res.specId; + } + + function validateForm(): boolean { + if (!form.pddShopId) { + message.warning('请选择渠道店铺'); + return false; + } + if (!form.primaryProductId) { + message.warning('请选择主内部商品'); + return false; + } + if (!form.goodsName.trim()) { + message.warning('请填写商品标题'); + return false; + } + if (!form.catId) { + message.warning('请选择叶子类目'); + return false; + } + if (catAuthAuthorized.value === false) { + message.warning(catAuthMessage.value || '当前店铺无权发布该类目'); + return false; + } + if (catAuthChecking.value) { + message.warning('正在校验类目发布权限,请稍候'); + return false; + } + if (!form.costTemplateId) { + message.warning('请选择运费模板'); + return false; + } + if (form.marketPriceYuan == null) { + message.warning('请填写参考价'); + return false; + } + if ( + form.twoPiecesDiscount == null || + form.twoPiecesDiscount < 0 || + form.twoPiecesDiscount > 100 + ) { + message.warning('请填写满两件折扣(0-100,95表示95折)'); + return false; + } + for (const p of nonSaleProps.value) { + if (!p.required) continue; + const key = String(p.templatePid ?? p.refPid); + if (!form.goodsPropValues[key]) { + message.warning(`请填写必填属性:${p.name || key}`); + return false; + } + } + if (carouselFileList.value.length === 0) { + message.warning('请选择轮播图'); + return false; + } + if (detailFileList.value.length === 0) { + message.warning('请选择详情图'); + return false; + } + if (specAxes.value.length === 0) { + message.warning('当前类目无可用规格,请更换类目或联系运营'); + return false; + } + for (const axis of specAxes.value) { + if (effectiveSpecValues(axis).length === 0) { + message.warning(`请为规格「${axis.name}」填写至少一个取值`); + return false; + } + } + if (skuRows.value.length === 0) { + message.warning('请先完成规格取值以生成 SKU'); + return false; + } + for (const row of skuRows.value) { + if (!row.outSkuSn.trim()) { + message.warning( + `请为规格组合「${row.skuName || '未命名'}」填写商家编码,或关联内部 SKU`, + ); + return false; + } + if (row.priceYuan == null || row.multiPriceYuan == null) { + message.warning(`请填写 SKU「${row.skuName || row.outSkuSn}」价格`); + return false; + } + if (row.thumbFileList.length === 0) { + message.warning(`请为 SKU「${row.skuName || row.outSkuSn}」选择缩略图`); + return false; + } + } + return true; + } + + async function buildPublishPayload( + carouselFileIds: number[], + detailFileIds: number[], + thumbFileIdBySkuKey: Map, + ): Promise { + // 非销售属性 → goods_properties(不传 parent_spec_id / spec_id) + const goodsProperties: PddGoodsPublishDTO.GoodsProperty[] = []; + for (const p of nonSaleProps.value) { + const key = String(p.templatePid ?? p.refPid); + const raw = form.goodsPropValues[key]; + if (!raw) continue; + const matched = p.values?.find( + (v) => String(v.vid) === raw || v.value === raw, + ); + goodsProperties.push({ + refPid: p.refPid, + templatePid: p.templatePid, + valueUnit: p.valueUnit, + vid: matched?.vid, + value: matched?.value ?? raw, + }); + } + + /** + * 销售规格:goods.add 要求 + * 1) goods_properties 带 parent_spec_id + spec_id(规格值去重) + * 2) sku.spec_id_list 为该 SKU 的规格组合 + * 3) sku.sku_properties 为销售属性 ref_pid/vid/value(有 refPid 时) + */ + const saleSpecSeen = new Set(); + + const skus: PddGoodsPublishDTO.PublishSku[] = []; + for (const row of skuRows.value) { + const thumbFileId = thumbFileIdBySkuKey.get(row.key); + if (thumbFileId == null) { + throw new Error(`SKU「${row.skuName || row.outSkuSn}」缩略图上传失败`); + } + const specIds: number[] = []; + const skuProperties: PddGoodsPublishDTO.SkuProperty[] = []; + + for (const axis of specAxes.value) { + const raw = row.saleValues[axis.key]; + if (!raw) { + throw new Error( + `SKU「${row.skuName || row.outSkuSn}」缺少规格「${axis.name}」`, + ); + } + const matched = axis.presetOptions.find((o) => o.value === raw); + let specId = matched?.specId; + const valueText = matched?.label ?? raw; + const parentSpecId = axis.parentSpecId; + if (parentSpecId == null) { + throw new Error( + `规格「${axis.name}」缺少 parent_spec_id,请重新选择类目`, + ); + } + if (!specId && valueText) { + specId = await resolveSpecId(parentSpecId, valueText); + } + if (specId == null) { + throw new Error( + `SKU「${row.skuName || row.outSkuSn}」规格「${axis.name}」无法生成 spec_id`, + ); + } + specIds.push(specId); + + const dedupeKey = `${parentSpecId}:${specId}`; + if (!saleSpecSeen.has(dedupeKey)) { + saleSpecSeen.add(dedupeKey); + goodsProperties.push({ + refPid: axis.refPid, + templatePid: axis.templatePid, + valueUnit: axis.valueUnit, + vid: matched?.vid, + value: valueText, + parentSpecId, + specId, + }); + } + + if (axis.refPid != null) { + skuProperties.push({ + refPid: axis.refPid, + vid: matched?.vid ?? 0, + value: valueText, + punit: axis.valueUnit || '', + }); + } + } + + if (specIds.length === 0) { + throw new Error( + `SKU「${row.skuName || row.outSkuSn}」未生成规格列表`, + ); + } + + skus.push({ + internalSkuId: row.internalSkuId, + outSkuSn: row.outSkuSn.trim(), + priceFen: yuanToFen(row.priceYuan)!, + multiPriceFen: yuanToFen(row.multiPriceYuan)!, + quantity: row.quantity, + weight: row.weight, + thumbImage: String(thumbFileId), + specIdList: JSON.stringify(specIds), + isOnsale: 1, + skuProperties, + }); + } + + return { + pddShopId: form.pddShopId!, + primaryProductId: form.primaryProductId!, + goodsName: form.goodsName.trim(), + goodsDesc: form.goodsDesc || undefined, + catId: form.catId!, + costTemplateId: form.costTemplateId!, + marketPriceFen: yuanToFen(form.marketPriceYuan)!, + shipmentLimitSecond: form.shipmentLimitSecond, + isFolt: form.isFolt, + isPreSale: form.isPreSale, + isRefundable: form.isRefundable, + secondHand: form.secondHand, + twoPiecesDiscount: form.twoPiecesDiscount, + carouselImages: carouselFileIds.map(String), + detailImages: detailFileIds.map(String), + goodsProperties, + skus, + }; + } + + /** 从服务端草稿完整恢复编辑态(含类目/规格/SKU/已上传图片) */ + async function hydrateFromDraft(id: number) { + hydratingDraft.value = true; + try { + const draft = await getPddPublishDeskDraftApi(id); + boundDraftId.value = draft.id; + + let editorState: Record | undefined; + if (draft.payloadJson) { + try { + const root = JSON.parse(draft.payloadJson) as { + editorState?: Record; + }; + editorState = root.editorState; + } catch { + message.warning('草稿内容解析失败,仅恢复标题与店铺'); + } + } + + const es = editorState ?? {}; + const shopId = + draft.pddShopId ?? + (typeof es.pddShopId === 'number' ? es.pddShopId : undefined); + form.pddShopId = shopId; + await Promise.all([ + loadShops(), + shopId ? loadRootCats() : Promise.resolve(), + shopId ? loadLogistics() : Promise.resolve(), + loadProducts(), + loadSkuCandidates(), + ]); + + form.goodsName = + (typeof es.goodsName === 'string' && es.goodsName) || + draft.title || + ''; + if (typeof es.goodsDesc === 'string') form.goodsDesc = es.goodsDesc; + if (typeof es.primaryProductId === 'number') { + form.primaryProductId = es.primaryProductId; + if ( + form.primaryProductId && + !productOptions.value.some((p) => p.value === form.primaryProductId) + ) { + productOptions.value = [ + { + label: `商品#${form.primaryProductId}`, + value: form.primaryProductId, + name: form.goodsName || `商品#${form.primaryProductId}`, + }, + ...productOptions.value, + ]; + } + } + + const catId = + draft.catId ?? + (typeof es.catId === 'number' ? es.catId : undefined); + const catPath = Array.isArray(es.catPath) + ? (es.catPath as unknown[]) + .map((x) => Number(x)) + .filter((n) => Number.isFinite(n) && n > 0) + : catId + ? [catId] + : []; + const pathLabel = + typeof es.selectedCatPathLabel === 'string' + ? es.selectedCatPathLabel + : ''; + if (catId) { + await loadCatContextForHydrate(catId, catPath, pathLabel); + } + + if (typeof es.costTemplateId === 'number') { + form.costTemplateId = es.costTemplateId; + void loadCostTemplateDetail(es.costTemplateId); + } + if (typeof es.marketPriceYuan === 'number') { + form.marketPriceYuan = es.marketPriceYuan; + } + if (typeof es.shipmentLimitSecond === 'number') { + form.shipmentLimitSecond = es.shipmentLimitSecond; + } + if (typeof es.isFolt === 'boolean') form.isFolt = es.isFolt; + if (typeof es.isPreSale === 'boolean') form.isPreSale = es.isPreSale; + if (typeof es.isRefundable === 'boolean') { + form.isRefundable = es.isRefundable; + } + if (typeof es.secondHand === 'boolean') form.secondHand = es.secondHand; + if (typeof es.twoPiecesDiscount === 'number') { + form.twoPiecesDiscount = es.twoPiecesDiscount; + } + if ( + es.goodsPropValues && + typeof es.goodsPropValues === 'object' && + !Array.isArray(es.goodsPropValues) + ) { + form.goodsPropValues = { + ...(es.goodsPropValues as Record), + }; + } + + const savedAxes = Array.isArray(es.specAxes) + ? (es.specAxes as SpecAxis[]) + : []; + if (savedAxes.length > 0) { + specAxes.value = savedAxes.map((a) => ({ + ...a, + presetOptions: Array.isArray(a.presetOptions) + ? a.presetOptions.map((o) => ({ ...o })) + : [], + selectedValues: normalizeSpecValueSlots(a.selectedValues), + })); + bumpSpecAxisRowSeqFromIds(specAxes.value.map((a) => a.rowId)); + } else if (specCatalog.value.length > 0) { + rebuildSpecCatalogAndSeed(); + } + + const savedSkus = Array.isArray(es.skuRows) ? es.skuRows : []; + const thumbPersisted: { + rowIndex: number; + thumb: PersistedUpload; + }[] = []; + if (savedSkus.length > 0) { + const rows: SkuRow[] = []; + for (const raw of savedSkus) { + const r = raw as Record; + const thumb = r.thumb as PersistedUpload | null | undefined; + const rowIndex = rows.length; + const saleValues = + r.saleValues && typeof r.saleValues === 'object' + ? { ...(r.saleValues as Record) } + : {}; + // 按 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) || nextSkuRowKey(), + comboKey: comboKeyFromSlots(parts), + internalSkuId: + typeof r.internalSkuId === 'number' ? r.internalSkuId : undefined, + productName: + typeof r.productName === 'string' ? r.productName : undefined, + internalSkuName: + typeof r.internalSkuName === 'string' + ? r.internalSkuName + : undefined, + codeMatchStatus: + (r.codeMatchStatus as SkuRow['codeMatchStatus']) || 'idle', + skuName: String(r.skuName || ''), + outSkuSn: String(r.outSkuSn || ''), + priceYuan: + typeof r.priceYuan === 'number' ? r.priceYuan : undefined, + multiPriceYuan: + typeof r.multiPriceYuan === 'number' + ? r.multiPriceYuan + : undefined, + quantity: typeof r.quantity === 'number' ? r.quantity : 0, + weight: typeof r.weight === 'number' ? r.weight : 0, + thumbFileList: [], + saleValues, + }); + if (thumb?.fileId) { + thumbPersisted.push({ rowIndex, thumb }); + } + } + skuRows.value = rows; + bumpSkuRowSeqFromKeys(rows.map((r) => r.key)); + } + + const carousel = Array.isArray(es.carouselFiles) + ? (es.carouselFiles as PersistedUpload[]) + : []; + const detail = Array.isArray(es.detailFiles) + ? (es.detailFiles as PersistedUpload[]) + : []; + const carouselSaved = carousel.filter((f) => f?.fileId); + const detailSaved = detail.filter((f) => f?.fileId); + const allPersisted = [ + ...carouselSaved, + ...detailSaved, + ...thumbPersisted.map((t) => t.thumb), + ]; + const restoredFiles = await toUploadFilesFromPersisted(allPersisted); + let cursor = 0; + carouselFileList.value = restoredFiles.slice( + cursor, + (cursor += carouselSaved.length), + ); + detailFileList.value = restoredFiles.slice( + cursor, + (cursor += detailSaved.length), + ); + for (const { rowIndex } of thumbPersisted) { + const file = restoredFiles[cursor++]; + if (file && skuRows.value[rowIndex]) { + skuRows.value[rowIndex]!.thumbFileList = [file]; + } + } + + await nextTick(); + void refreshSpecSortables(); + message.success('已加载草稿'); + } catch (e: any) { + message.error(e?.message || '加载草稿失败'); + } finally { + hydratingDraft.value = false; + } + } + + /** 保存系统草稿;markReady=true 时写入 publishPayload 供批量发布 */ + async function saveDeskDraft( + markReady: boolean, + extras?: { includePublishPayload?: boolean; silentSuccess?: boolean }, + ): Promise<{ id: number; hasPayload: boolean } | null> { + if (!form.pddShopId) { + message.warning('请先选择渠道店铺'); + return null; + } + const title = form.goodsName.trim() || '未命名草稿'; + const includePayload = markReady || extras?.includePublishPayload === true; + draftSaving.value = true; + const hide = message.loading( + markReady + ? '生成可发布数据…' + : includePayload + ? '保存系统草稿…' + : '保存系统草稿…', + 0, + ); + try { + // 普通保存也上传图片,否则下次打开无法回填(未上传的合并一次签名) + const pendingThumbs = skuRows.value + .map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] })) + .filter((x): x is { rowKey: number; file: UploadFile } => !!x.file); + const persistedAll = await ensurePersistedUploads([ + ...carouselFileList.value, + ...detailFileList.value, + ...pendingThumbs.map((x) => x.file), + ]); + let p = 0; + const carouselFiles = persistedAll.slice( + p, + (p += carouselFileList.value.length), + ); + const detailFiles = persistedAll.slice( + p, + (p += detailFileList.value.length), + ); + const thumbPersisted = persistedAll.slice(p); + const thumbBySkuKey = new Map(); + pendingThumbs.forEach((item, i) => { + const saved = thumbPersisted[i]; + if (saved) thumbBySkuKey.set(item.rowKey, saved); + }); + + let publishPayload: PddGoodsPublishDTO.Publish | undefined; + if (includePayload) { + if (markReady && !validateForm()) { + return null; + } + const thumbFileIdBySkuKey = new Map(); + for (const [k, v] of thumbBySkuKey) { + thumbFileIdBySkuKey.set(k, v.fileId); + } + try { + publishPayload = await buildPublishPayload( + carouselFiles.map((f) => f.fileId), + detailFiles.map((f) => f.fileId), + thumbFileIdBySkuKey, + ); + } catch (e: any) { + if (markReady) { + throw e; + } + // 推送场景:先落系统草稿,调用方再提示无法推送 + } + } + + const payloadJson = JSON.stringify({ + editorState: { + pddShopId: form.pddShopId, + primaryProductId: form.primaryProductId, + goodsName: form.goodsName, + goodsDesc: form.goodsDesc, + catId: form.catId, + catPath: resolveFullCatPath(), + selectedCatPathLabel: selectedCatPathLabel.value, + costTemplateId: form.costTemplateId, + marketPriceYuan: form.marketPriceYuan, + shipmentLimitSecond: form.shipmentLimitSecond, + isFolt: form.isFolt, + isPreSale: form.isPreSale, + isRefundable: form.isRefundable, + secondHand: form.secondHand, + twoPiecesDiscount: form.twoPiecesDiscount, + goodsPropValues: { ...form.goodsPropValues }, + specAxes: specAxes.value.map((a) => ({ + rowId: a.rowId, + catalogKey: a.catalogKey, + key: a.key, + name: a.name, + parentSpecId: a.parentSpecId, + refPid: a.refPid, + templatePid: a.templatePid, + valueUnit: a.valueUnit, + presetOptions: a.presetOptions.map((o) => ({ ...o })), + selectedValues: a.selectedValues.map((s) => ({ + id: s.id, + token: s.token, + })), + })), + skuRows: skuRows.value.map((r) => ({ + key: r.key, + comboKey: r.comboKey, + internalSkuId: r.internalSkuId, + productName: r.productName, + internalSkuName: r.internalSkuName, + codeMatchStatus: r.codeMatchStatus, + skuName: r.skuName, + outSkuSn: r.outSkuSn, + priceYuan: r.priceYuan, + multiPriceYuan: r.multiPriceYuan, + quantity: r.quantity, + weight: r.weight, + saleValues: { ...r.saleValues }, + thumb: thumbBySkuKey.get(r.key) ?? null, + })), + carouselFiles, + detailFiles, + }, + publishPayload: publishPayload ?? undefined, + }); + const body = { + pddShopId: form.pddShopId, + title, + catId: form.catId, + skuCount: skuRows.value.length, + status: markReady ? 'READY' : 'EDITING', + payloadJson, + }; + const saved = boundDraftId.value + ? await updatePddPublishDeskDraftApi(boundDraftId.value, body) + : await createPddPublishDeskDraftApi(body); + boundDraftId.value = saved.id; + emit('draft-saved', saved.id); + if (!extras?.silentSuccess) { + message.success(markReady ? '已保存为可发布草稿' : '系统草稿已保存'); + } + return { id: saved.id, hasPayload: !!publishPayload }; + } catch (e: any) { + message.error(e?.message || '保存系统草稿失败'); + return null; + } finally { + hide(); + draftSaving.value = false; + } + } + + /** 先落系统草稿(尽量带 publishPayload),再推送到拼多多草稿箱 */ + async function pushToPlatformDraft() { + if (!form.pddShopId) { + message.warning('请先选择渠道店铺'); + return; + } + if (!form.catId) { + message.warning('请先选择叶子类目'); + return; + } + platformPushing.value = true; + try { + const saved = await saveDeskDraft(false, { + includePublishPayload: true, + silentSuccess: true, + }); + if (!saved) return; + if (!saved.hasPayload) { + message.error('未能生成可推送数据,请补全规格、价格与图片后再试'); + return; + } + const hide = message.loading('推送到拼多多草稿箱…', 0); + try { + const vo = await pushPddPublishDeskDraftApi(saved.id); + message.success( + vo.pddGoodsCommitId + ? `已推送到拼多多草稿箱(ID ${vo.pddGoodsCommitId})` + : '已推送到拼多多草稿箱', + ); + } finally { + hide(); + } + } catch (e: any) { + message.error(e?.message || '推送到拼多多草稿箱失败'); + } finally { + platformPushing.value = false; + } + } + + async function handleSubmit() { + if (!validateForm()) return; + submitting.value = true; + const hide = message.loading('正在上传图片并发布…', 0); + try { + const pendingThumbs = skuRows.value + .map((row) => ({ rowKey: row.key, file: row.thumbFileList[0] })) + .filter((x): x is { rowKey: number; file: UploadFile } => !!x.file); + const persistedAll = await ensurePersistedUploads([ + ...carouselFileList.value, + ...detailFileList.value, + ...pendingThumbs.map((x) => x.file), + ]); + let p = 0; + const carouselFileIds = persistedAll + .slice(p, (p += carouselFileList.value.length)) + .map((f) => f.fileId); + const detailFileIds = persistedAll + .slice(p, (p += detailFileList.value.length)) + .map((f) => f.fileId); + const thumbPersisted = persistedAll.slice(p); + const thumbFileIdBySkuKey = new Map(); + pendingThumbs.forEach((item, i) => { + const saved = thumbPersisted[i]; + if (saved) thumbFileIdBySkuKey.set(item.rowKey, saved.fileId); + }); + + const payload = await buildPublishPayload( + carouselFileIds, + detailFileIds, + thumbFileIdBySkuKey, + ); + // 确保有系统草稿并回传 ID,发布结果才能写入 goods_commit_id + if (boundDraftId.value) { + payload.systemDraftId = boundDraftId.value; + } else if (form.pddShopId) { + const saved = await saveDeskDraft(true, { silentSuccess: true }); + if (saved?.id) { + payload.systemDraftId = saved.id; + } + } + const res = await publishPddGoodsApi(payload); + message.success(`发布成功,goodsId=${res.goodsId}`); + emit('success'); + closeEditor(); + } catch (e: any) { + message.error(e?.message || '发布失败'); + } finally { + hide(); + submitting.value = false; + } + } + + function clearSpecIdCache() { + specIdCache.clear(); + } + + function resetBoundDraftId() { + boundDraftId.value = null; + } + + return { + draftSaving, + platformPushing, + boundDraftId, + submitting, + hydrateFromDraft, + saveDeskDraft, + pushToPlatformDraft, + handleSubmit, + validateForm, + buildPublishPayload, + clearSpecIdCache, + resetBoundDraftId, + }; +} + +export type PublishDraftApi = ReturnType; diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-images.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-images.ts new file mode 100644 index 00000000..a542c25e --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-images.ts @@ -0,0 +1,361 @@ +import type { UploadFile, UploadProps } from 'ant-design-vue'; +import type { Ref } from 'vue'; + +import { ref } from 'vue'; + +import { Upload, message } from 'ant-design-vue'; + +import { FileCategory } from '#/constants/file-category'; +import { getFileAccessUrlApi } from '#/api/sys/file'; +import { uploadFile, uploadFiles } from '#/utils/upload-file'; + +import type { PersistedUpload, SkuRow } from './types'; + +/** + * 轮播/详情/SKU 缩略图本地预览与持久化上传。 + * 发布与草稿保存时再真正入库;卸载时需 revoke blob。 + */ +export function usePublishImages(skuRows: Ref) { + let uploadUidSeq = 1; + + const carouselFileList = ref([]); + const detailFileList = ref([]); + const previewVisible = ref(false); + const previewImage = ref(''); + + /** 本地选图 → UploadFile(blob 预览),发布时再真正上传 */ + function toLocalUploadFile(file: File): UploadFile { + const url = URL.createObjectURL(file); + return { + uid: `local-${uploadUidSeq++}`, + name: file.name, + status: 'done', + url, + thumbUrl: url, + originFileObj: file as UploadFile['originFileObj'], + }; + } + + function isImageFile(file: File) { + return file.type.startsWith('image/'); + } + + function revokeUploadFile(file?: UploadFile) { + const url = file?.url || file?.thumbUrl; + if (url?.startsWith('blob:')) { + URL.revokeObjectURL(url); + } + } + + function revokeUploadFiles(files?: UploadFile[]) { + for (const f of files ?? []) { + revokeUploadFile(f); + } + } + + function clearLocalImages() { + revokeUploadFiles(carouselFileList.value); + revokeUploadFiles(detailFileList.value); + for (const row of skuRows.value) { + revokeUploadFiles(row.thumbFileList); + row.thumbFileList = []; + } + carouselFileList.value = []; + detailFileList.value = []; + } + + /** 拦截自动上传:手动入列表,悬停由 picture-card 展示预览/删除 */ + function makeBeforeUpload( + append: (file: UploadFile) => void, + ): UploadProps['beforeUpload'] { + return (file) => { + const raw = file as File; + if (!isImageFile(raw)) { + message.warning(`跳过非图片文件:${raw.name}`); + return Upload.LIST_IGNORE; + } + append(toLocalUploadFile(raw)); + return Upload.LIST_IGNORE; + }; + } + + const beforeUploadCarousel = makeBeforeUpload((f) => { + carouselFileList.value = [...carouselFileList.value, f]; + }); + + const beforeUploadDetail = makeBeforeUpload((f) => { + detailFileList.value = [...detailFileList.value, f]; + }); + + function beforeUploadSku(rowKey: number): UploadProps['beforeUpload'] { + return makeBeforeUpload((f) => { + const row = skuRows.value.find((r) => r.key === rowKey); + if (!row) return; + revokeUploadFiles(row.thumbFileList); + row.thumbFileList = [f]; + }); + } + + function onRemoveCarousel(file: UploadFile) { + revokeUploadFile(file); + return true; + } + + function onRemoveDetail(file: UploadFile) { + revokeUploadFile(file); + return true; + } + + function onSkuThumbFileListChange(rowKey: number, list: UploadFile[]) { + const row = skuRows.value.find((r) => r.key === rowKey); + if (!row) return; + const nextUids = new Set(list.map((f) => f.uid)); + for (const old of row.thumbFileList) { + if (!nextUids.has(old.uid)) { + revokeUploadFile(old); + } + } + row.thumbFileList = list; + } + + /** picture-card 悬停「眼睛」:组件内预览 */ + function onPreviewUploadFile(file: UploadFile) { + previewImage.value = file.url || file.thumbUrl || ''; + previewVisible.value = true; + } + + function setPreviewVisible(visible: boolean) { + previewVisible.value = visible; + } + + async function uploadUploadFile(file: UploadFile): Promise { + const existingId = Number((file as UploadFile & { fileId?: number }).fileId); + if (Number.isFinite(existingId) && existingId > 0) { + return existingId; + } + const raw = file.originFileObj as File | undefined; + if (!raw) { + throw new Error(`图片文件丢失:${file.name || file.uid}`); + } + const info = await uploadFile(raw, { + category: FileCategory.IMAGE, + errorMessage: `图片上传失败:${raw.name}`, + }); + if (!info?.id) { + throw new Error(`图片上传失败:${raw.name}`); + } + (file as UploadFile & { fileId?: number }).fileId = info.id; + if (info.accessUrl) { + file.url = info.accessUrl; + file.thumbUrl = info.accessUrl; + } + return info.id; + } + + /** + * 批量确保图片已入库:未上传的合并一次签名/上传;已有 fileId 的补访问 URL。 + */ + async function ensurePersistedUploads( + files: UploadFile[], + ): Promise { + if (files.length === 0) return []; + + type Slot = + | { kind: 'done'; value: PersistedUpload } + | { kind: 'upload'; file: UploadFile; raw: File }; + + const slots: Slot[] = []; + const needAccessIds: number[] = []; + + for (const file of files) { + const existingId = Number( + (file as UploadFile & { fileId?: number }).fileId, + ); + if (Number.isFinite(existingId) && existingId > 0) { + let url = file.url; + if (!url || url.startsWith('blob:')) { + needAccessIds.push(existingId); + slots.push({ + kind: 'done', + value: { fileId: existingId, name: file.name }, + }); + } else { + slots.push({ + kind: 'done', + value: { fileId: existingId, name: file.name, url }, + }); + } + continue; + } + const raw = file.originFileObj as File | undefined; + if (!raw) { + throw new Error(`图片文件丢失:${file.name || file.uid}`); + } + slots.push({ kind: 'upload', file, raw }); + } + + const accessUrlById = new Map(); + if (needAccessIds.length > 0) { + const uniqueIds = [...new Set(needAccessIds)]; + const urls = await Promise.all( + uniqueIds.map(async (id) => { + try { + return [id, await getFileAccessUrlApi(id)] as const; + } catch { + return [id, ''] as const; + } + }), + ); + for (const [id, url] of urls) { + if (url) accessUrlById.set(id, url); + } + } + + const uploadIndexes: number[] = []; + const uploadRaws: File[] = []; + slots.forEach((slot, index) => { + if (slot.kind === 'upload') { + uploadIndexes.push(index); + uploadRaws.push(slot.raw); + } + }); + + let uploaded: Awaited> = []; + if (uploadRaws.length > 0) { + uploaded = await uploadFiles(uploadRaws, { + category: FileCategory.IMAGE, + errorMessage: '图片上传失败', + }); + } + + let uploadCursor = 0; + const results: PersistedUpload[] = []; + for (let i = 0; i < slots.length; i++) { + const slot = slots[i]!; + if (slot.kind === 'done') { + const url = slot.value.url || accessUrlById.get(slot.value.fileId); + const file = files[i]!; + if (url) { + file.url = url; + file.thumbUrl = url; + } + results.push({ + fileId: slot.value.fileId, + name: slot.value.name, + url: url || undefined, + }); + continue; + } + const info = uploaded[uploadCursor++]!; + if (!info?.id) { + throw new Error(`图片上传失败:${slot.raw.name}`); + } + (slot.file as UploadFile & { fileId?: number }).fileId = info.id; + if (info.accessUrl) { + slot.file.url = info.accessUrl; + slot.file.thumbUrl = info.accessUrl; + } + results.push({ + fileId: info.id, + name: slot.file.name, + url: info.accessUrl, + }); + } + return results; + } + + async function ensurePersistedUpload( + file: UploadFile, + ): Promise { + const [one] = await ensurePersistedUploads([file]); + if (!one) { + throw new Error(`图片上传失败:${file.name || file.uid}`); + } + return one; + } + + async function toUploadFilesFromPersisted( + items: PersistedUpload[], + ): Promise { + if (items.length === 0) return []; + const needIds = items + .filter((p) => p.fileId && (!p.url || p.url.startsWith('blob:'))) + .map((p) => p.fileId); + const urlById = new Map(); + for (const p of items) { + if (p.url && !p.url.startsWith('blob:')) { + urlById.set(p.fileId, p.url); + } + } + if (needIds.length > 0) { + const uniqueIds = [...new Set(needIds)]; + const pairs = await Promise.all( + uniqueIds.map(async (id) => { + try { + return [id, await getFileAccessUrlApi(id)] as const; + } catch { + return [id, ''] as const; + } + }), + ); + for (const [id, url] of pairs) { + if (url) urlById.set(id, url); + } + } + return items + .map((p) => { + const url = urlById.get(p.fileId); + if (!url) return null; + return { + uid: `file-${p.fileId}-${uploadUidSeq++}`, + name: p.name || `image-${p.fileId}`, + status: 'done' as const, + url, + thumbUrl: url, + fileId: p.fileId, + } as UploadFile; + }) + .filter(Boolean) as UploadFile[]; + } + + async function toUploadFileFromPersisted( + p: PersistedUpload, + ): Promise { + const [one] = await toUploadFilesFromPersisted([p]); + if (!one) { + throw new Error(`无法加载图片:${p.fileId}`); + } + return one; + } + + function resetUploadUidSeq() { + uploadUidSeq = 1; + } + + return { + carouselFileList, + detailFileList, + previewVisible, + previewImage, + toLocalUploadFile, + revokeUploadFile, + revokeUploadFiles, + clearLocalImages, + beforeUploadCarousel, + beforeUploadDetail, + beforeUploadSku, + onRemoveCarousel, + onRemoveDetail, + onSkuThumbFileListChange, + onPreviewUploadFile, + setPreviewVisible, + uploadUploadFile, + ensurePersistedUploads, + ensurePersistedUpload, + toUploadFilesFromPersisted, + toUploadFileFromPersisted, + resetUploadUidSeq, + }; +} + +export type PublishImagesApi = ReturnType; diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-sku.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-sku.ts new file mode 100644 index 00000000..67c8cf9a --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-sku.ts @@ -0,0 +1,699 @@ +import type { ProductSkuVO } from '#/api/ec/product/sku'; +import type { UploadFile } from 'ant-design-vue'; +import type { Ref } from 'vue'; + +import { computed, nextTick, ref } from 'vue'; + +import { useDebounceFn } from '@vueuse/core'; + +import { message } from 'ant-design-vue'; + +import type { PddGoodsPublishVO } from '#/api/channel/pdd/goods'; +import { + getProductSkuBySkuCodeApi, + getProductSkuPageApi, +} from '#/api/ec/product/sku'; + +import type { SpecAxis, SkuRow } from './types'; + +type SpecHelpers = { + effectiveSpecSlots: (axis: SpecAxis) => SpecAxis['selectedValues']; + labelOfAxisValue: (axis: SpecAxis, value: string) => string; + resolveSpecValueToken: (axis: SpecAxis, raw: string) => string; + specValueAutoOptions: ( + axis: SpecAxis, + index: number, + ) => Array<{ label: string; value: string }>; +}; + +/** + * SKU 笛卡尔积同步、内部 SKU 绑定、商家编码校验与表工具。 + * 依赖规格轴 refs;改文案靠槽位 id 保编码,Agent 走 applySkuAssignmentsByOutSkuSn。 + */ +export function usePublishSku(options: { + /** 与 images 等共享同一 ref,由壳层创建 */ + skuRows: Ref; + specAxes: Ref; + catTemplate: Ref; + revokeUploadFiles: (files?: UploadFile[]) => void; + specHelpers: SpecHelpers; +}) { + const { skuRows, specAxes, catTemplate, revokeUploadFiles, specHelpers } = + options; + const { + effectiveSpecSlots, + labelOfAxisValue, + resolveSpecValueToken, + specValueAutoOptions, + } = specHelpers; + + let skuRowSeq = 1; + + const skuOptions = ref([]); + /** SKU 规格列内联编辑草稿:`${rowKey}_${axisKey}` → 输入中文案 */ + const skuSpecDraft = ref>({}); + /** 上方「内部 SKU 拉入」多选 */ + const bindPickSkuIds = ref([]); + /** 商家编码校验防抖定时器(按行) */ + const outSkuSnTimers = new Map>(); + /** 商家编码校验序号,防止乱序回写 */ + const outSkuSnValidateSeq = new Map(); + /** 规格表容器:新增后滚到表体底部 */ + const skuTableWrapRef = ref(null); + + /** 规格列行合并:前缀规格值相同则合并(笛卡尔积顺序下连续) */ + const skuSpecRowSpans = computed(() => { + const rows = skuRows.value; + const axes = specAxes.value; + const spansByAxisKey = new Map(); + for (const axis of axes) { + spansByAxisKey.set(axis.key, Array.from({ length: rows.length }, () => 1)); + } + if (rows.length === 0 || axes.length === 0) return spansByAxisKey; + + for (let axisIdx = 0; axisIdx < axes.length; axisIdx++) { + const prefixKeys = axes.slice(0, axisIdx + 1).map((a) => a.key); + const spans = spansByAxisKey.get(axes[axisIdx]!.key)!; + let i = 0; + while (i < rows.length) { + let j = i + 1; + while ( + j < rows.length && + prefixKeys.every( + (k) => rows[j]!.saleValues[k] === rows[i]!.saleValues[k], + ) + ) { + j++; + } + spans[i] = j - i; + for (let k = i + 1; k < j; k++) { + spans[k] = 0; + } + i = j; + } + } + return spansByAxisKey; + }); + + /** SKU 表列:每种规格单独一列,相同规格值合并单元格 */ + const skuTableColumns = computed(() => [ + ...specAxes.value.map((axis) => ({ + title: axis.name, + key: `spec_${axis.key}`, + width: 140, + customCell: (_record: SkuRow, rowIndex?: number) => ({ + rowSpan: skuSpecRowSpans.value.get(axis.key)?.[rowIndex ?? 0] ?? 1, + }), + })), + { title: '编码', key: 'code', width: 140 }, + { title: '内部SKU', key: 'internalSku', width: 160 }, + { title: '单买价', key: 'price', width: 120 }, + { title: '拼单价', key: 'multi', width: 120 }, + { title: '库存', key: 'qty', width: 100 }, + { title: '重量g', key: 'weight', width: 100 }, + { title: '缩略图', key: 'thumb', width: 100 }, + ]); + + const skuTableScrollX = computed(() => 740 + specAxes.value.length * 140); + + const skuSelectOptions = computed(() => + skuOptions.value.map((s) => ({ + label: `${s.productName} / ${s.name}${s.skuCode ? ` (${s.skuCode})` : ''}`, + value: s.id, + })), + ); + + /** 最近一次已请求/在途的关键字,避免 focus+search 或重复 search 打两次 */ + let skuSearchKeywordKey = '\0'; + let skuSearchSeq = 0; + + async function loadSkuCandidates(keyword = '') { + const kw = keyword.trim(); + if (kw === skuSearchKeywordKey) return; + skuSearchKeywordKey = kw; + const seq = ++skuSearchSeq; + try { + const data = await getProductSkuPageApi({ + page: 1, + pageSize: 100, + filters: kw ? { keywords: kw } : {}, + }); + if (seq !== skuSearchSeq) return; + skuOptions.value = data.records ?? []; + } catch { + if (seq === skuSearchSeq) { + skuSearchKeywordKey = '\0'; + message.error('加载 SKU 失败'); + } + } + } + + /** 远程搜索防抖:连打只打最后一次 */ + const debouncedLoadSkuCandidates = useDebounceFn((keyword: string) => { + void loadSkuCandidates(keyword); + }, 300); + + /** 下拉打开时若尚无选项再拉首屏(替代 focus,避免与 search 叠一次空请求) */ + function onSkuSelectDropdownOpen(open: boolean) { + if (open && skuOptions.value.length === 0) { + void loadSkuCandidates(); + } + } + + function clearSkuRows() { + for (const row of skuRows.value) { + revokeUploadFiles(row.thumbFileList); + } + skuRows.value = []; + } + + function cartesianProduct(lists: T[][]): T[][] { + if (lists.length === 0) return []; + return lists.reduce( + (acc, curr) => + acc.flatMap((prefix) => curr.map((item) => [...prefix, item])), + [[]], + ); + } + + /** 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'); + } + + /** SKU 行某规格列展示文案(Table bodyCell 的 record 类型较宽) */ + function skuSpecColumnLabel( + record: { saleValues?: Record }, + columnKey: string, + ) { + const axisKey = columnKey.replace(/^spec_/, ''); + const axis = specAxes.value.find((a) => a.key === axisKey); + const raw = record.saleValues?.[axisKey]; + if (!axis || raw == null || raw === '') return '—'; + return labelOfAxisValue(axis, raw); + } + + function skuSpecDraftKey(rowKey: number, axisKey: string) { + return `${rowKey}_${axisKey}`; + } + + /** 规格列展示:优先草稿(输入中),否则轴上取值的 label */ + function skuSpecCellDisplay(record: Record, axisKey: string) { + const rowKey = Number(record.key); + const dk = skuSpecDraftKey(rowKey, axisKey); + if (Object.prototype.hasOwnProperty.call(skuSpecDraft.value, dk)) { + return skuSpecDraft.value[dk] ?? ''; + } + return skuSpecColumnLabel(record, `spec_${axisKey}`); + } + + function skuSpecCellAutoOptions(record: Record, 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((s) => s.token === current); + if (index < 0) { + return axis.presetOptions.map((o) => ({ + label: o.label, + value: o.label, + })); + } + return specValueAutoOptions(axis, index); + } + + function onSkuSpecCellInput(rowKey: number, axisKey: string, text: string) { + skuSpecDraft.value = { + ...skuSpecDraft.value, + [skuSpecDraftKey(rowKey, axisKey)]: text, + }; + } + + /** + * 合并单元格内改规格值 = 重命名该轴上对应取值(整组同值),再同步笛卡尔积。 + * 只改槽位 token,slot.id 不变,商家编码保留。 + */ + function onSkuSpecCellCommit(rowKey: number, axisKey: string) { + const dk = skuSpecDraftKey(rowKey, axisKey); + if (!Object.prototype.hasOwnProperty.call(skuSpecDraft.value, dk)) return; + const draft = skuSpecDraft.value[dk] ?? ''; + const nextDraft = { ...skuSpecDraft.value }; + delete nextDraft[dk]; + skuSpecDraft.value = nextDraft; + + const row = skuRows.value.find((r) => r.key === rowKey); + const axis = specAxes.value.find((a) => a.key === axisKey); + if (!row || !axis) return; + + const oldToken = row.saleValues[axisKey] ?? ''; + const newToken = resolveSpecValueToken(axis, draft); + if (!newToken || newToken === oldToken) return; + + const vi = axis.selectedValues.findIndex((s) => s.token === oldToken); + if (vi < 0) return; + if ( + axis.selectedValues.some( + (s, i) => i !== vi && s.token.trim() === newToken, + ) + ) { + message.warning('该规格值已存在'); + return; + } + const slot = axis.selectedValues[vi]; + if (!slot) return; + slot.token = newToken; + syncSkuRowsFromSpecs(); + } + + /** + * 规格槽位变化后按笛卡尔积生成 SKU;同槽位组合键保留已填价格/编码/图。 + * 改文案只改 token,槽位 id 不变,故不会丢商家编码。 + * orphanByIndex:槽位对不上时是否按原行序迁编码(人手改轴用);Agent 有 skuAssignments 时关闭。 + * 返回未纳入新表的旧行,供调用方按编码绑定或释放缩略图。 + */ + function syncSkuRowsFromSpecs(opts?: { orphanByIndex?: boolean }): SkuRow[] { + const orphanByIndex = opts?.orphanByIndex !== false; + const axes = specAxes.value; + if (axes.length === 0) { + clearSkuRows(); + return []; + } + const slotLists = axes.map((a) => effectiveSpecSlots(a)); + if (slotLists.some((list) => list.length === 0)) { + clearSkuRows(); + return []; + } + + const combos = cartesianProduct(slotLists); + const maxSku = Number(catTemplate.value?.maxSkuNum ?? 0); + if (maxSku > 0 && combos.length > maxSku) { + message.warning( + `规格组合共 ${combos.length} 个,超过类目上限 ${maxSku},请减少规格值`, + ); + } + + const prevRows = skuRows.value; + const prevByKey = new Map(prevRows.map((r) => [r.comboKey, r])); + const next: SkuRow[] = []; + const isFresh: boolean[] = []; + + for (const combo of combos) { + const parts = axes.map((axis, i) => ({ + axisKey: axis.key, + slotId: combo[i]!.id, + })); + const key = comboKeyFromSlots(parts); + const saleValues: Record = {}; + const labels: string[] = []; + axes.forEach((axis, i) => { + 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); + isFresh.push(false); + prevByKey.delete(key); + } else { + next.push({ + key: skuRowSeq++, + comboKey: key, + skuName, + outSkuSn: '', + quantity: 100, + weight: 1, + thumbFileList: [], + saleValues, + }); + isFresh.push(true); + } + } + + if (orphanByIndex) { + const orphans = prevRows.filter((r) => prevByKey.has(r.comboKey)); + let orphanIdx = 0; + for (let ni = 0; ni < next.length; ni++) { + if (!isFresh[ni]) continue; + const orphan = orphans[orphanIdx++]; + if (!orphan) break; + adoptSkuRowBusinessFields(next[ni]!, orphan); + prevByKey.delete(orphan.comboKey); + } + for (const orphan of prevByKey.values()) { + revokeUploadFiles(orphan.thumbFileList); + } + skuRows.value = next; + void scrollSkuTableToBottom(); + return []; + } + + const deferredOrphans = prevRows.filter((r) => prevByKey.has(r.comboKey)); + skuRows.value = next; + void scrollSkuTableToBottom(); + return deferredOrphans; + } + + /** 规格重组时继承编码/价/图/内部绑定;保留目标行的 comboKey 与规格描述 */ + function adoptSkuRowBusinessFields(target: SkuRow, source: SkuRow) { + target.key = source.key; + target.outSkuSn = source.outSkuSn; + target.priceYuan = source.priceYuan; + target.multiPriceYuan = source.multiPriceYuan; + target.quantity = source.quantity; + target.weight = source.weight; + target.thumbFileList = source.thumbFileList; + target.internalSkuId = source.internalSkuId; + target.productName = source.productName; + target.internalSkuName = source.internalSkuName; + target.codeMatchStatus = source.codeMatchStatus; + } + + /** 行规格展示值列表(与轴顺序一致,供 Agent 对齐) */ + function skuRowValueLabels(row: SkuRow) { + return specAxes.value.map((a) => + labelOfAxisValue(a, row.saleValues[a.key] ?? ''), + ); + } + + /** 判断 SKU 行是否匹配 Agent 给出的 values(与当前轴同序,按 label/token) */ + function skuRowMatchesValueLabels(row: SkuRow, valueLabels: string[]) { + const axes = specAxes.value; + if (valueLabels.length !== axes.length) return false; + return axes.every((axis, i) => { + const want = String(valueLabels[i] ?? '').trim(); + const token = row.saleValues[axis.key] ?? ''; + const label = labelOfAxisValue(axis, token); + const resolved = resolveSpecValueToken(axis, want); + return ( + want === token || + want === label || + resolved === token || + resolved === label + ); + }); + } + + /** + * 按商家编码把旧行业务字段挂到 Agent 指定的新规格组合上。 + * outSkuSn 为唯一身份;values 与当前 axes 同序。 + */ + function applySkuAssignmentsByOutSkuSn( + assignments: Array<{ outSkuSn: string; values: string[] }>, + prevRows: SkuRow[], + ) { + const prevByCode = new Map(); + for (const r of prevRows) { + const code = r.outSkuSn.trim(); + if (code && !prevByCode.has(code)) prevByCode.set(code, r); + } + const usedCodes = new Set(); + let bound = 0; + for (const item of assignments) { + const code = item.outSkuSn.trim(); + if (!code || usedCodes.has(code)) continue; + const source = prevByCode.get(code); + if (!source) continue; + const target = skuRows.value.find( + (r) => + !r.outSkuSn.trim() && skuRowMatchesValueLabels(r, item.values), + ); + if (!target) continue; + adoptSkuRowBusinessFields(target, source); + usedCodes.add(code); + bound += 1; + } + return bound; + } + + /** 将内部 SKU 绑定到某一组合行(只填编码,不新增行) */ + function bindInternalSku(rowKey: number, skuId?: number) { + const row = skuRows.value.find((r) => r.key === rowKey); + if (!row) return; + if (skuId == null) { + row.internalSkuId = undefined; + row.productName = undefined; + row.internalSkuName = undefined; + row.codeMatchStatus = 'idle'; + return; + } + if ( + skuRows.value.some( + (r) => r.key !== row.key && r.internalSkuId === skuId, + ) + ) { + message.warning('该内部 SKU 已绑定到其他规格组合'); + return; + } + const sku = skuOptions.value.find((s) => s.id === skuId); + if (!sku) { + message.warning('未找到该 SKU,请先搜索'); + return; + } + row.internalSkuId = sku.id; + row.productName = sku.productName; + row.internalSkuName = sku.name; + row.codeMatchStatus = 'matched'; + if (sku.skuCode) { + row.outSkuSn = sku.skuCode; + } + } + + /** 商家编码写入后清除该行待校验定时器 */ + function clearOutSkuSnTimer(rowKey: number) { + const t = outSkuSnTimers.get(rowKey); + if (t) { + clearTimeout(t); + outSkuSnTimers.delete(rowKey); + } + } + + function clearAllOutSkuSnTimers() { + for (const t of outSkuSnTimers.values()) { + clearTimeout(t); + } + outSkuSnTimers.clear(); + outSkuSnValidateSeq.clear(); + } + + /** 商家编码变更:400ms 防抖后校验是否内部 SKU */ + function onOutSkuSnChange(rowKey: number, value: string) { + const row = skuRows.value.find((r) => r.key === rowKey); + if (!row) return; + row.outSkuSn = value; + // 编码改动后暂视为未校验,避免仍显示旧关联 + if (row.codeMatchStatus === 'matched' || row.codeMatchStatus === 'unmatched') { + row.codeMatchStatus = 'idle'; + } + clearOutSkuSnTimer(rowKey); + outSkuSnTimers.set( + rowKey, + setTimeout(() => { + outSkuSnTimers.delete(rowKey); + void validateOutSkuSnByCode(rowKey); + }, 400), + ); + } + + /** 失焦立即校验(取消防抖) */ + function onOutSkuSnBlur(rowKey: number) { + clearOutSkuSnTimer(rowKey); + void validateOutSkuSnByCode(rowKey); + } + + /** + * 按商家编码反查内部 SKU;命中则关联,否则标「非内部SKU」。 + */ + async function validateOutSkuSnByCode(rowKey: number) { + const row = skuRows.value.find((r) => r.key === rowKey); + if (!row) return; + + const code = row.outSkuSn.trim(); + if (!code) { + row.internalSkuId = undefined; + row.productName = undefined; + row.internalSkuName = undefined; + row.codeMatchStatus = 'idle'; + return; + } + + // 已关联且编码未变:跳过请求 + if ( + row.codeMatchStatus === 'matched' && + row.internalSkuId != null && + row.outSkuSn.trim() === code + ) { + const bound = skuOptions.value.find((s) => s.id === row.internalSkuId); + if (bound?.skuCode && bound.skuCode === code) return; + } + + const seq = (outSkuSnValidateSeq.get(rowKey) ?? 0) + 1; + outSkuSnValidateSeq.set(rowKey, seq); + row.codeMatchStatus = 'checking'; + + try { + const sku = await getProductSkuBySkuCodeApi(code); + if (outSkuSnValidateSeq.get(rowKey) !== seq) return; + if (!sku?.id) { + row.internalSkuId = undefined; + row.productName = undefined; + row.internalSkuName = undefined; + row.codeMatchStatus = 'unmatched'; + return; + } + if ( + skuRows.value.some( + (r) => r.key !== row.key && r.internalSkuId === sku.id, + ) + ) { + message.warning('该内部 SKU 已绑定到其他规格组合'); + row.internalSkuId = undefined; + row.productName = sku.productName; + row.internalSkuName = sku.name; + row.codeMatchStatus = 'matched'; + return; + } + row.internalSkuId = sku.id; + row.productName = sku.productName; + row.internalSkuName = sku.name; + row.codeMatchStatus = 'matched'; + // 缓存到下拉候选,便于同弹窗内复用 + if (!skuOptions.value.some((s) => s.id === sku.id)) { + skuOptions.value = [sku, ...skuOptions.value]; + } + } catch { + if (outSkuSnValidateSeq.get(rowKey) !== seq) return; + row.internalSkuId = undefined; + row.productName = undefined; + row.internalSkuName = undefined; + row.codeMatchStatus = 'unmatched'; + } + } + + /** 按当前 SKU 表行序依次关联上方多选的内部 SKU */ + function applyInternalSkusInOrder() { + const ids = bindPickSkuIds.value; + if (ids.length === 0) { + message.warning('请先选择内部 SKU'); + return; + } + const rows = skuRows.value; + if (rows.length === 0) { + message.warning('请先生成 SKU 组合'); + return; + } + const n = Math.min(ids.length, rows.length); + const idSet = new Set(ids.slice(0, n)); + for (const r of rows) { + if (r.internalSkuId != null && idSet.has(r.internalSkuId)) { + r.internalSkuId = undefined; + r.productName = undefined; + r.internalSkuName = undefined; + r.codeMatchStatus = 'idle'; + } + } + for (let i = 0; i < n; i++) { + const row = rows[i]!; + const skuId = ids[i]!; + const sku = skuOptions.value.find((s) => s.id === skuId); + if (!sku) continue; + clearOutSkuSnTimer(row.key); + row.internalSkuId = sku.id; + row.productName = sku.productName; + row.internalSkuName = sku.name; + row.codeMatchStatus = 'matched'; + if (sku.skuCode) { + row.outSkuSn = sku.skuCode; + } + } + if (ids.length > rows.length) { + message.info(`已按顺序填入 ${rows.length} 行,多余选择已忽略`); + } else if (ids.length < rows.length) { + message.info(`已填入前 ${ids.length} 行,其余行未改动`); + } else { + message.success('已按顺序关联内部 SKU'); + } + } + + /** 清空全部行的内部 SKU 关联(不改商家编码) */ + function clearInternalSkuBindings() { + if (skuRows.value.length === 0) return; + for (const row of skuRows.value) { + clearOutSkuSnTimer(row.key); + row.internalSkuId = undefined; + row.productName = undefined; + row.internalSkuName = undefined; + row.codeMatchStatus = 'idle'; + } + message.success('已清空内部 SKU 关联'); + } + + /** 新增规格后滚到表体底部,方便继续编辑新行 */ + async function scrollSkuTableToBottom() { + await nextTick(); + await nextTick(); + const body = skuTableWrapRef.value?.querySelector( + '.ant-table-body', + ) as HTMLElement | null; + if (!body) return; + body.scrollTo({ top: body.scrollHeight, behavior: 'smooth' }); + } + + function resetSkuRowSeq(next = 1) { + skuRowSeq = next; + } + + function bumpSkuRowSeqFromKeys(keys: number[]) { + skuRowSeq = Math.max(0, ...keys, skuRowSeq - 1) + 1; + } + + function nextSkuRowKey() { + return skuRowSeq++; + } + + return { + skuOptions, + skuRows, + skuSpecDraft, + bindPickSkuIds, + skuTableWrapRef, + skuSpecRowSpans, + skuTableColumns, + skuTableScrollX, + skuSelectOptions, + loadSkuCandidates, + debouncedLoadSkuCandidates, + onSkuSelectDropdownOpen, + clearSkuRows, + comboKeyFromSlots, + skuSpecColumnLabel, + skuSpecCellDisplay, + skuSpecCellAutoOptions, + onSkuSpecCellInput, + onSkuSpecCellCommit, + syncSkuRowsFromSpecs, + adoptSkuRowBusinessFields, + skuRowValueLabels, + applySkuAssignmentsByOutSkuSn, + bindInternalSku, + clearAllOutSkuSnTimers, + onOutSkuSnChange, + onOutSkuSnBlur, + applyInternalSkusInOrder, + clearInternalSkuBindings, + scrollSkuTableToBottom, + resetSkuRowSeq, + bumpSkuRowSeqFromKeys, + nextSkuRowKey, + }; +} + +export type PublishSkuApi = ReturnType; diff --git a/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-specs.ts b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-specs.ts new file mode 100644 index 00000000..06789bd3 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/channel/pdd/goods/publish/editor/use-publish-specs.ts @@ -0,0 +1,629 @@ +import type { Sortable } from '@vben/hooks'; +import type { ComputedRef, Ref } from 'vue'; + +import { computed, nextTick, ref, watch } from 'vue'; + +import { useSortable } from '@vben/hooks'; +import { Modal as AntModal, message } from 'ant-design-vue'; + +import type { PddGoodsPublishVO } from '#/api/channel/pdd/goods'; + +import type { SpecAxis, SpecCatalogItem, SkuRow } from './types'; +import { createSpecValueSlotFactory } from './types'; + +/** + * 销售规格目录/轴 CRUD、槽位合并与 Sortable。 + * syncSkuRowsFromSpecs 由壳层注入,保证与 SKU 表同一套笛卡尔积逻辑。 + */ +export function usePublishSpecs(options: { + saleProps: Ref | ComputedRef; + parentSpecs: Ref; + /** 与 category / draft 共享,由壳层创建 */ + specAxes: Ref; + specCatalog: Ref; + skuRows: Ref; + syncSkuRowsFromSpecs: (opts?: { orphanByIndex?: boolean }) => SkuRow[]; + comboKeyFromSlots: ( + parts: Array<{ axisKey: string; slotId: number }>, + ) => string; +}) { + const { + saleProps, + parentSpecs, + specAxes, + specCatalog, + skuRows, + syncSkuRowsFromSpecs, + comboKeyFromSlots, + } = options; + + const { + createSpecValueSlot, + normalizeSpecValueSlots, + mergeSpecValueSlots, + resetSpecValueSlotSeq, + } = createSpecValueSlotFactory(); + + let specAxisRowSeq = 1; + + /** 规格轴列表容器(拖拽排序) */ + const specAxesListRef = ref(null); + let axesSortable: null | Sortable = null; + /** 各轴规格值容器的 Sortable 实例 */ + const valueSortables = new Map(); + + const canAddSpecAxis = computed(() => { + const maxAxes = Math.min(2, specCatalog.value.length); + return ( + specCatalog.value.length > 0 && specAxes.value.length < maxAxes + ); + }); + + /** 从类目销售属性 / 父规格构建可选规格目录 */ + function buildSpecCatalog(): SpecCatalogItem[] { + const sales = saleProps.value; + const parents = parentSpecs.value; + if (parents.length > 0) { + return parents.map((ps) => { + const matchedSale = sales.find((s) => s.name === ps.parentSpecName); + return { + catalogKey: `ps_${ps.parentSpecId}`, + name: ps.parentSpecName || `规格${ps.parentSpecId}`, + parentSpecId: ps.parentSpecId, + refPid: matchedSale?.refPid, + templatePid: matchedSale?.templatePid, + valueUnit: matchedSale?.valueUnit, + presetOptions: (matchedSale?.values || []).map((v) => ({ + label: v.value || String(v.vid), + value: String(v.vid ?? v.value), + vid: v.vid, + specId: v.specId, + })), + }; + }); + } + const items: SpecCatalogItem[] = []; + for (const sp of sales) { + const parentSpecId = sp.specId; + if (parentSpecId == null) continue; + items.push({ + catalogKey: String(sp.refPid ?? sp.templatePid ?? parentSpecId), + name: sp.name || String(parentSpecId), + parentSpecId, + refPid: sp.refPid, + templatePid: sp.templatePid, + valueUnit: sp.valueUnit, + presetOptions: (sp.values || []).map((v) => ({ + label: v.value || String(v.vid), + value: String(v.vid ?? v.value), + vid: v.vid, + specId: v.specId, + })), + }); + } + return items; + } + + function createAxisFromCatalog(item: SpecCatalogItem): SpecAxis { + return { + rowId: specAxisRowSeq++, + catalogKey: item.catalogKey, + key: item.catalogKey, + name: item.name, + parentSpecId: item.parentSpecId, + refPid: item.refPid, + templatePid: item.templatePid, + valueUnit: item.valueUnit, + presetOptions: item.presetOptions.map((o) => ({ ...o })), + // 默认一条空输入,随时可编辑 + selectedValues: [createSpecValueSlot('')], + }; + } + + function findDefaultCatalogItem(catalog: SpecCatalogItem[]) { + return ( + catalog.find((c) => c.name === '款式') || + catalog.find((c) => c.name.includes('款式')) || + catalog[0] + ); + } + + function labelOfAxisValue(axis: SpecAxis, value: string) { + return axis.presetOptions.find((o) => o.value === value)?.label ?? value; + } + + /** 重建可选规格,并默认种子一条「款式」 */ + function rebuildSpecCatalogAndSeed() { + const catalog = buildSpecCatalog(); + specCatalog.value = catalog; + const def = findDefaultCatalogItem(catalog); + specAxes.value = def ? [createAxisFromCatalog(def)] : []; + syncSkuRowsFromSpecs(); + } + + /** + * 切换类目后重建规格目录,尽量沿用已有规格轴取值与 SKU。 + * 名称能匹配的更新为新类目 parentSpecId;不能匹配的保留原值并提示用户改选规格。 + */ + function rebuildSpecCatalogPreservingUserData() { + const catalog = buildSpecCatalog(); + specCatalog.value = catalog; + + const prevAxes = specAxes.value.map((a) => ({ + ...a, + presetOptions: a.presetOptions.map((o) => ({ ...o })), + selectedValues: a.selectedValues.map((s) => ({ ...s })), + })); + const prevSkus = skuRows.value; + + if (prevAxes.length === 0) { + const def = findDefaultCatalogItem(catalog); + specAxes.value = def ? [createAxisFromCatalog(def)] : []; + syncSkuRowsFromSpecs(); + return; + } + + if (catalog.length === 0) { + message.warning( + '新类目暂无销售规格,已保留原规格与 SKU;发布前请更换类目或确认规格', + ); + return; + } + + const warnings: string[] = []; + const usedCatalog = new Set(); + /** 旧轴 key → 新轴 key */ + const keyMap = new Map(); + /** 旧轴 key → (旧 token → 新 token) */ + const valueMaps = new Map>(); + + const nextAxes: SpecAxis[] = prevAxes.map((prev) => { + const match = + catalog.find( + (c) => !usedCatalog.has(c.catalogKey) && c.name === prev.name, + ) || + catalog.find( + (c) => + !usedCatalog.has(c.catalogKey) && + (c.name.includes(prev.name) || prev.name.includes(c.name)), + ); + + if (!match) { + warnings.push(`「${prev.name}」`); + keyMap.set(prev.key, prev.key); + return prev; + } + + usedCatalog.add(match.catalogKey); + const tokenMap = new Map(); + 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 { id: slot.id, token: nextToken }; + }); + valueMaps.set(prev.key, tokenMap); + keyMap.set(prev.key, match.catalogKey); + + return { + rowId: prev.rowId, + catalogKey: match.catalogKey, + key: match.catalogKey, + name: match.name, + parentSpecId: match.parentSpecId, + refPid: match.refPid, + templatePid: match.templatePid, + valueUnit: match.valueUnit, + presetOptions: match.presetOptions.map((o) => ({ ...o })), + selectedValues: + selectedValues.length > 0 + ? selectedValues + : [createSpecValueSlot('')], + }; + }); + + specAxes.value = nextAxes; + + skuRows.value = prevSkus.map((row) => { + const saleValues: Record = {}; + for (const [oldKey, oldVal] of Object.entries(row.saleValues)) { + const newKey = keyMap.get(oldKey) ?? oldKey; + const newVal = valueMaps.get(oldKey)?.get(oldVal) ?? oldVal; + saleValues[newKey] = newVal; + } + 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: comboKeyFromSlots(parts), + skuName: labels.filter((l) => l && l !== '—').join(' / ') || row.skuName, + }; + }); + + if (warnings.length > 0) { + message.warning( + `新类目不支持规格 ${warnings.join('、')},已保留原值,请在规格区切换为该类目支持的规格`, + ); + } + } + + /** 某行可选的父规格(排除已被其他行占用) */ + function catalogOptionsForAxis(rowId: number) { + const used = new Set( + specAxes.value + .filter((a) => a.rowId !== rowId) + .map((a) => a.catalogKey), + ); + return specCatalog.value + .filter((c) => !used.has(c.catalogKey)) + .map((c) => ({ label: c.name, value: c.catalogKey })); + } + + function applyCatalogToAxis(axis: SpecAxis, catalogKey: string) { + const item = specCatalog.value.find((c) => c.catalogKey === catalogKey); + if (!item) return; + axis.catalogKey = item.catalogKey; + axis.key = item.catalogKey; + axis.name = item.name; + axis.parentSpecId = item.parentSpecId; + axis.refPid = item.refPid; + axis.templatePid = item.templatePid; + axis.valueUnit = item.valueUnit; + axis.presetOptions = item.presetOptions.map((o) => ({ ...o })); + axis.selectedValues = [createSpecValueSlot('')]; + } + + function onAxisCatalogChange(rowId: number, catalogKey: string) { + const axis = specAxes.value.find((a) => a.rowId === rowId); + if (!axis || !catalogKey) return; + applyCatalogToAxis(axis, catalogKey); + syncSkuRowsFromSpecs(); + } + + function addSpecAxis() { + if (specAxes.value.length >= 2) { + message.warning('最多添加两种规格'); + return; + } + const used = new Set(specAxes.value.map((a) => a.catalogKey)); + const next = specCatalog.value.find((c) => !used.has(c.catalogKey)); + if (!next) { + message.warning('没有可添加的规格了'); + return; + } + specAxes.value.push(createAxisFromCatalog(next)); + syncSkuRowsFromSpecs(); + } + + function removeSpecAxis(rowId: number) { + if (specAxes.value.length <= 1) { + message.warning('至少保留一个规格'); + return; + } + const axis = specAxes.value.find((a) => a.rowId === rowId); + AntModal.confirm({ + title: '确认删除规格?', + content: `确定删除规格「${axis?.name || ''}」及其全部取值吗?相关 SKU 组合将重新生成。`, + okText: '删除', + okType: 'danger', + cancelText: '取消', + centered: true, + zIndex: 2100, + onOk() { + specAxes.value = specAxes.value.filter((a) => a.rowId !== rowId); + syncSkuRowsFromSpecs(); + }, + }); + } + + /** 参与笛卡尔积的有效规格槽(去掉空白 token) */ + function effectiveSpecSlots(axis: SpecAxis) { + return axis.selectedValues.filter((s) => s.token.trim()); + } + + /** 有效规格值 token 列表(发布/校验用) */ + function effectiveSpecValues(axis: SpecAxis) { + return effectiveSpecSlots(axis).map((s) => s.token.trim()); + } + + /** AutoComplete 展示文案:预设用 label,自定义原样 */ + function specValueDisplay(axis: SpecAxis, index: number) { + const raw = axis.selectedValues[index]?.token ?? ''; + return labelOfAxisValue(axis, raw); + } + + /** 下拉选项:未占用的预设 + 当前项(用 label 作 value,避免输入框出现 vid) */ + function specValueAutoOptions(axis: SpecAxis, index: number) { + const current = axis.selectedValues[index]?.token ?? ''; + const used = new Set( + axis.selectedValues + .map((s, i) => (i === index ? '' : s.token.trim())) + .filter(Boolean), + ); + return axis.presetOptions + .filter((o) => !used.has(o.value) || o.value === current) + .map((o) => ({ label: o.label, value: o.label })); + } + + function resolveSpecValueToken(axis: SpecAxis, raw: string) { + const text = raw.trim(); + if (!text) return ''; + const matched = axis.presetOptions.find( + (o) => o.value === text || o.label === text, + ); + return matched?.value ?? text; + } + + 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; + 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 slot = axis.selectedValues[index]; + if (!slot) return; + const value = resolveSpecValueToken(axis, slot.token); + if ( + value && + axis.selectedValues.some( + (s, i) => i !== index && s.token.trim() === value, + ) + ) { + message.warning('该规格值已存在'); + slot.token = ''; + syncSkuRowsFromSpecs(); + return; + } + slot.token = value; + syncSkuRowsFromSpecs(); + } + + /** 回车:提交当前值并追加一个新的空输入,并聚焦到新框 */ + 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]?.token ?? '').trim(); + if (!current) return; + const next = axis.selectedValues[index + 1]; + if (next != null && !String(next.token).trim()) { + focusSpecValueInput(rowId, index + 1); + return; + } + axis.selectedValues.splice(index + 1, 0, createSpecValueSlot('')); + focusSpecValueInput(rowId, index + 1); + } + + function focusSpecValueInput(rowId: number, index: number) { + void nextTick(() => { + const root = document.querySelector( + `[data-spec-value-input="${rowId}_${index}"]`, + ); + const input = root?.querySelector('input') as HTMLInputElement | null; + input?.focus(); + }); + } + + function addSpecValueSlot(rowId: number) { + const axis = specAxes.value.find((a) => a.rowId === rowId); + if (!axis) return; + axis.selectedValues.push(createSpecValueSlot('')); + } + + function removeSpecValue(rowId: number, index: number) { + const axis = specAxes.value.find((a) => a.rowId === rowId); + if (!axis) return; + const raw = axis.selectedValues[index]; + if (raw == null) return; + + const doRemove = () => { + const current = specAxes.value.find((a) => a.rowId === rowId); + if (!current) return; + if (index < 0 || index >= current.selectedValues.length) return; + if (current.selectedValues.length <= 1) { + current.selectedValues[0] = createSpecValueSlot(''); + } else { + current.selectedValues.splice(index, 1); + } + syncSkuRowsFromSpecs(); + }; + + if (!raw.token.trim()) { + doRemove(); + return; + } + AntModal.confirm({ + title: '确认删除规格值?', + content: `删除「${labelOfAxisValue(axis, raw.token)}」后,相关 SKU 组合将移除。`, + okText: '删除', + okType: 'danger', + cancelText: '取消', + centered: true, + zIndex: 2100, + onOk() { + doRemove(); + }, + }); + } + + /** 销毁规格轴/规格值 Sortable,避免泄漏 */ + function destroySpecSortables() { + axesSortable?.destroy(); + axesSortable = null; + for (const s of valueSortables.values()) { + s.destroy(); + } + valueSortables.clear(); + } + + /** 规格轴卡片拖拽:交换维度顺序后重建 SKU 行序 */ + async function initAxesSortable() { + axesSortable?.destroy(); + axesSortable = null; + await nextTick(); + const el = specAxesListRef.value; + if (!el || specAxes.value.length < 2) return; + const { initializeSortable } = useSortable(el, { + animation: 200, + delay: 0, + handle: '.spec-axis-drag-handle', + draggable: '.spec-axis-card', + onEnd(evt) { + const { oldIndex, newIndex } = evt; + if ( + oldIndex == null || + newIndex == null || + oldIndex === newIndex || + Number.isNaN(oldIndex) || + Number.isNaN(newIndex) + ) { + return; + } + const list = [...specAxes.value]; + const [moved] = list.splice(oldIndex, 1); + if (!moved) return; + list.splice(newIndex, 0, moved); + specAxes.value = list; + syncSkuRowsFromSpecs(); + void refreshSpecSortables(); + }, + }); + axesSortable = await initializeSortable(); + } + + /** 轴内规格值 Chip 拖拽:只调同轴取值顺序 */ + async function initValueSortables() { + for (const s of valueSortables.values()) { + s.destroy(); + } + valueSortables.clear(); + await nextTick(); + for (const axis of specAxes.value) { + const el = document.querySelector( + `[data-spec-values="${axis.rowId}"]`, + ) as HTMLElement | null; + if (!el || axis.selectedValues.length < 2) continue; + const rowId = axis.rowId; + const { initializeSortable } = useSortable(el, { + animation: 150, + delay: 0, + handle: '.spec-value-drag-handle', + draggable: '.spec-value-chip', + onEnd(evt) { + const { oldIndex, newIndex } = evt; + if ( + oldIndex == null || + newIndex == null || + oldIndex === newIndex || + Number.isNaN(oldIndex) || + Number.isNaN(newIndex) + ) { + return; + } + const target = specAxes.value.find((a) => a.rowId === rowId); + if (!target) return; + const vals = [...target.selectedValues]; + const [moved] = vals.splice(oldIndex, 1); + if (moved === undefined) return; + vals.splice(newIndex, 0, moved); + target.selectedValues = vals; + syncSkuRowsFromSpecs(); + void refreshSpecSortables(); + }, + }); + valueSortables.set(rowId, await initializeSortable()); + } + } + + async function refreshSpecSortables() { + await initAxesSortable(); + await initValueSortables(); + } + + /** 规格轴数量或取值槽位数变化时重建拖拽 */ + watch( + () => + specAxes.value + .map((a) => `${a.rowId}:${a.selectedValues.length}`) + .join('|'), + () => { + void refreshSpecSortables(); + }, + ); + + function resetSpecAxisRowSeq(next = 1) { + specAxisRowSeq = next; + } + + function bumpSpecAxisRowSeqFromIds(ids: number[]) { + specAxisRowSeq = Math.max(0, ...ids, specAxisRowSeq - 1) + 1; + } + + function nextSpecAxisRowId() { + return specAxisRowSeq++; + } + + return { + specCatalog, + specAxes, + specAxesListRef, + canAddSpecAxis, + createSpecValueSlot, + normalizeSpecValueSlots, + mergeSpecValueSlots, + resetSpecValueSlotSeq, + buildSpecCatalog, + createAxisFromCatalog, + findDefaultCatalogItem, + labelOfAxisValue, + rebuildSpecCatalogAndSeed, + rebuildSpecCatalogPreservingUserData, + catalogOptionsForAxis, + onAxisCatalogChange, + addSpecAxis, + removeSpecAxis, + effectiveSpecSlots, + effectiveSpecValues, + specValueDisplay, + specValueAutoOptions, + resolveSpecValueToken, + onSpecValueInput, + onSpecValueCommit, + onSpecValueEnter, + addSpecValueSlot, + removeSpecValue, + destroySpecSortables, + refreshSpecSortables, + resetSpecAxisRowSeq, + bumpSpecAxisRowSeqFromIds, + nextSpecAxisRowId, + }; +} + +export type PublishSpecsApi = ReturnType;