mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
refactor: 去掉弹窗发布并将发布编辑器拆为页面壳与 composables
This commit is contained in:
-4259
File diff suppressed because it is too large
Load Diff
-75
@@ -1,75 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import { watch } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import PddGoodsPublishEditor from './PddGoodsPublishEditor.vue';
|
||||
|
||||
defineOptions({ name: 'PddGoodsPublishModal' });
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
presetPddShopId?: number | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
success: [];
|
||||
}>();
|
||||
|
||||
const hasDraft = defineModel<boolean>('hasDraft', { default: false });
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[1100px] max-h-[80vh]',
|
||||
contentClass: 'flex min-h-0 flex-1 flex-col overflow-hidden px-5 py-4',
|
||||
destroyOnClose: false,
|
||||
closeOnClickModal: false,
|
||||
footer: false,
|
||||
onOpenChange(isOpen: boolean) {
|
||||
if (!isOpen) {
|
||||
emit('update:open', false);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(v) => {
|
||||
if (v) {
|
||||
modalApi.open();
|
||||
} else {
|
||||
modalApi.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
function onEditorClose(mode: 'close' | 'minimize') {
|
||||
if (mode === 'minimize') {
|
||||
hasDraft.value = true;
|
||||
} else {
|
||||
hasDraft.value = false;
|
||||
}
|
||||
emit('update:open', false);
|
||||
modalApi.close();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal title="发布拼多多商品">
|
||||
<PddGoodsPublishEditor
|
||||
v-model:has-draft="hasDraft"
|
||||
variant="modal"
|
||||
:open="open"
|
||||
:preset-pdd-shop-id="presetPddShopId"
|
||||
@success="
|
||||
() => {
|
||||
emit('success');
|
||||
emit('update:open', false);
|
||||
modalApi.close();
|
||||
}
|
||||
"
|
||||
@close="onEditorClose"
|
||||
/>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -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<InstanceType<typeof PddGoodsDetailDrawer>>();
|
||||
const shopDetailModalRef = ref<InstanceType<typeof PddShopDetailModal>>();
|
||||
const publishOpen = ref(false);
|
||||
const publishHasDraft = ref(false);
|
||||
/** 左侧选中的拼多多渠道店铺 ID */
|
||||
const selectedShopId = ref<number | undefined>(undefined);
|
||||
const shopNameById = ref<Record<number, string>>({});
|
||||
@@ -309,9 +306,6 @@ onMounted(async () => {
|
||||
<Button type="primary" @click="$router.push('/pdd/goods/publish')">
|
||||
发布工作台
|
||||
</Button>
|
||||
<Button class="ml-2" @click="publishOpen = true">
|
||||
{{ publishHasDraft ? '继续弹窗发布' : '弹窗发布' }}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</div>
|
||||
</template>
|
||||
@@ -384,12 +378,6 @@ onMounted(async () => {
|
||||
|
||||
<PddGoodsDetailDrawer ref="detailDrawerRef" />
|
||||
<PddShopDetailModal ref="shopDetailModalRef" />
|
||||
<PddGoodsPublishModal
|
||||
v-model:open="publishOpen"
|
||||
v-model:has-draft="publishHasDraft"
|
||||
:preset-pdd-shop-id="selectedShopId"
|
||||
@success="() => gridApi.reload()"
|
||||
/>
|
||||
</PddShopColPage>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -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 }}
|
||||
</span>
|
||||
</div>
|
||||
<!-- Editor 页面态 Teleport:店铺 / 类目 -->
|
||||
<!-- Editor Teleport:店铺 / 类目 -->
|
||||
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -73,10 +73,9 @@ function goBack() {
|
||||
class="flex min-h-0 flex-1 overflow-hidden"
|
||||
>
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
|
||||
<PddGoodsPublishEditor
|
||||
<PddPublishEditor
|
||||
ref="editorRef"
|
||||
class="h-full min-h-0"
|
||||
variant="page"
|
||||
:open="true"
|
||||
:draft-id="draftId"
|
||||
@close="goBack"
|
||||
|
||||
+811
@@ -0,0 +1,811 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 拼多多发布编辑器壳:编排 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<SkuRow[]>([]);
|
||||
const specAxes = ref<SpecAxis[]>([]);
|
||||
const specCatalog = ref<SpecCatalogItem[]>([]);
|
||||
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;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<Form
|
||||
layout="vertical"
|
||||
class="flex min-h-0 flex-1 flex-col overflow-hidden"
|
||||
>
|
||||
<Teleport defer to="#pdd-publish-edit-header-fields">
|
||||
<div class="w-full min-w-0 space-y-2">
|
||||
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div class="min-w-0">
|
||||
<div class="mb-1 text-sm font-medium">
|
||||
渠道店铺 <span class="text-destructive">*</span>
|
||||
</div>
|
||||
<Select
|
||||
v-model:value="form.pddShopId"
|
||||
show-search
|
||||
allow-clear
|
||||
class="w-full"
|
||||
placeholder="搜索店铺名称"
|
||||
:filter-option="false"
|
||||
:options="shopOptions"
|
||||
@search="(kw: string) => loadShops(kw)"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="mb-1 flex items-center gap-1.5 text-sm font-medium">
|
||||
<span>
|
||||
叶子类目 <span class="text-destructive">*</span>
|
||||
</span>
|
||||
<Tooltip
|
||||
v-if="form.pddShopId && catSourceDegraded"
|
||||
:title="catDegradeHint"
|
||||
>
|
||||
<WarningOutlined class="text-warning cursor-help text-sm" />
|
||||
</Tooltip>
|
||||
<Tooltip v-if="catAuthHint" :title="catAuthHint.title">
|
||||
<LoadingOutlined
|
||||
v-if="catAuthHint.tone === 'info'"
|
||||
class="cursor-help text-sm text-blue-500"
|
||||
spin
|
||||
/>
|
||||
<CheckCircleOutlined
|
||||
v-else-if="catAuthHint.tone === 'success'"
|
||||
class="cursor-help text-sm text-green-600"
|
||||
/>
|
||||
<CloseCircleOutlined
|
||||
v-else-if="catAuthHint.tone === 'error'"
|
||||
class="cursor-help text-sm text-red-500"
|
||||
/>
|
||||
<ExclamationCircleOutlined
|
||||
v-else
|
||||
class="text-warning cursor-help text-sm"
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Cascader
|
||||
v-model:value="form.catPath"
|
||||
v-model:search-value="catCascaderSearch"
|
||||
class="w-full"
|
||||
:options="displayCatOptions"
|
||||
:load-data="catLoadData"
|
||||
:show-search="{
|
||||
filter: catCascaderFilter,
|
||||
limit: 50,
|
||||
}"
|
||||
:display-render="catDisplayRender"
|
||||
change-on-select
|
||||
:placeholder="
|
||||
!form.pddShopId
|
||||
? '请先选择渠道店铺'
|
||||
: catsLoading || catSearchLoading
|
||||
? '类目加载中…'
|
||||
: localCatReady
|
||||
? '搜索类目名称或逐级展开选择'
|
||||
: '逐级展开选择(搜索仅匹配已展开)'
|
||||
"
|
||||
:disabled="!form.pddShopId || catsLoading"
|
||||
@search="onCatCascaderSearch"
|
||||
@change="(v: any) => onCatChange(v || [])"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<div
|
||||
class="min-h-0 flex-1 space-y-4 overflow-y-auto overscroll-y-contain px-4 py-3"
|
||||
>
|
||||
<Form.Item label="主内部商品" required>
|
||||
<Select
|
||||
v-model:value="form.primaryProductId"
|
||||
show-search
|
||||
allow-clear
|
||||
class="w-full"
|
||||
placeholder="搜索并选择主商品(标题默认带出)"
|
||||
:filter-option="false"
|
||||
:options="productOptions"
|
||||
@search="(kw: string) => loadProducts(kw)"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="商品标题" required>
|
||||
<Input v-model:value="form.goodsName" :maxlength="60" show-count />
|
||||
</Form.Item>
|
||||
<Form.Item label="商品描述">
|
||||
<Input.TextArea
|
||||
v-model:value="form.goodsDesc"
|
||||
:rows="2"
|
||||
placeholder="可选,20-500 字"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="运费模板" required>
|
||||
<Select
|
||||
v-model:value="form.costTemplateId"
|
||||
class="w-full"
|
||||
:options="logisticsOptions"
|
||||
placeholder="选择运费模板"
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:disabled="!form.pddShopId"
|
||||
allow-clear
|
||||
@change="(v: any) => loadCostTemplateDetail(v)"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Card
|
||||
v-if="form.costTemplateId || costTemplateDetailLoading"
|
||||
size="small"
|
||||
class="mb-3"
|
||||
title="运费模板详情"
|
||||
>
|
||||
<Spin :spinning="costTemplateDetailLoading">
|
||||
<template v-if="costTemplateDetail">
|
||||
<Descriptions bordered size="small" :column="2" class="mb-3">
|
||||
<Descriptions.Item label="模板名称">
|
||||
{{ costTemplateDetail.templateName || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="计费方式">
|
||||
{{ costTemplateDetail.costTypeLabel || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="增值服务">
|
||||
{{ costTemplateDetail.additionalServiceLabel || '-' }}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="其它">
|
||||
<Space :size="4" wrap>
|
||||
<Tag v-if="costTemplateDetail.sfFree" color="success">
|
||||
顺丰包邮
|
||||
</Tag>
|
||||
<Tag
|
||||
v-if="costTemplateDetail.freeDeliverHouse"
|
||||
color="processing"
|
||||
>
|
||||
包邮区送货上门
|
||||
</Tag>
|
||||
<span
|
||||
v-if="
|
||||
!costTemplateDetail.sfFree &&
|
||||
!costTemplateDetail.freeDeliverHouse
|
||||
"
|
||||
>
|
||||
-
|
||||
</span>
|
||||
</Space>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="包邮省份" :span="2">
|
||||
<Space v-if="costTemplateDetail.freeProvinces?.length" wrap>
|
||||
<Tag
|
||||
v-for="(p, idx) in costTemplateDetail.freeProvinces"
|
||||
:key="`${p.provinceId}-${idx}`"
|
||||
>
|
||||
{{ p.province || p.provinceId }}
|
||||
</Tag>
|
||||
</Space>
|
||||
<span v-else>暂无</span>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item
|
||||
v-if="costTemplateDetail.freeDeliverHouseAreas?.length"
|
||||
label="送货上门地区"
|
||||
:span="2"
|
||||
>
|
||||
{{
|
||||
costTemplateDetail.freeDeliverHouseAreas
|
||||
.map((a) => a.areaText)
|
||||
.filter(Boolean)
|
||||
.join('、') || '-'
|
||||
}}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Table
|
||||
v-if="costTemplateDetail.paidRegions?.length"
|
||||
size="small"
|
||||
:pagination="false"
|
||||
:data-source="costTemplateDetail.paidRegions"
|
||||
:row-key="(_: any, i?: number) => `paid-${i ?? 0}`"
|
||||
:columns="[
|
||||
{ title: '买家付邮地区', dataIndex: 'provincesText' },
|
||||
{ title: '首费规则', key: 'first', width: 160 },
|
||||
{ title: '续费规则', key: 'add', width: 160 },
|
||||
{ title: '条件包邮', dataIndex: 'freeRuleText', width: 160 },
|
||||
]"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'first'">
|
||||
首{{ record.firstStandard ?? '-'
|
||||
}}{{ costTemplateDetail?.costType === 1 ? 'kg' : '件' }}
|
||||
/ {{ record.firstCostYuan ?? '-' }}元
|
||||
</template>
|
||||
<template v-else-if="column.key === 'add'">
|
||||
续{{ record.addStandard ?? '-'
|
||||
}}{{ costTemplateDetail?.costType === 1 ? 'kg' : '件' }}
|
||||
/ {{ record.addCostYuan ?? '-' }}元
|
||||
</template>
|
||||
</template>
|
||||
</Table>
|
||||
</template>
|
||||
<Empty
|
||||
v-else-if="!costTemplateDetailLoading"
|
||||
description="暂无模板详情"
|
||||
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||
/>
|
||||
</Spin>
|
||||
</Card>
|
||||
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<Form.Item label="参考价(元)" required>
|
||||
<InputNumber
|
||||
v-model:value="form.marketPriceYuan"
|
||||
class="w-full"
|
||||
:min="0.01"
|
||||
:precision="2"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="发货时限" required>
|
||||
<Select
|
||||
v-model:value="form.shipmentLimitSecond"
|
||||
class="w-full"
|
||||
:options="[
|
||||
{ label: '24小时', value: 86400 },
|
||||
{ label: '48小时', value: 172800 },
|
||||
]"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item label="满两件折扣" required>
|
||||
<InputNumber
|
||||
v-model:value="form.twoPiecesDiscount"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:max="100"
|
||||
:precision="0"
|
||||
placeholder="95 表示 95 折,0 取消"
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-6">
|
||||
<Form.Item label="假一赔十" required>
|
||||
<Switch v-model:checked="form.isFolt" />
|
||||
</Form.Item>
|
||||
<Form.Item label="7天无理由" required>
|
||||
<Switch v-model:checked="form.isRefundable" />
|
||||
</Form.Item>
|
||||
<Form.Item label="预售" required>
|
||||
<Switch v-model:checked="form.isPreSale" />
|
||||
</Form.Item>
|
||||
<Form.Item label="二手" required>
|
||||
<Switch v-model:checked="form.secondHand" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<template v-if="nonSaleProps.length">
|
||||
<div class="mb-1 text-sm font-medium">类目属性</div>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<Form.Item
|
||||
v-for="p in nonSaleProps"
|
||||
:key="String(p.templatePid ?? p.refPid)"
|
||||
:label="p.name"
|
||||
:required="!!p.required"
|
||||
>
|
||||
<Select
|
||||
v-if="p.values?.length"
|
||||
v-model:value="
|
||||
form.goodsPropValues[String(p.templatePid ?? p.refPid)]
|
||||
"
|
||||
class="w-full"
|
||||
allow-clear
|
||||
show-search
|
||||
option-filter-prop="label"
|
||||
:options="
|
||||
(p.values || []).map((v) => ({
|
||||
label: v.value,
|
||||
value: String(v.vid ?? v.value),
|
||||
}))
|
||||
"
|
||||
/>
|
||||
<Input
|
||||
v-else
|
||||
v-model:value="
|
||||
form.goodsPropValues[String(p.templatePid ?? p.refPid)]
|
||||
"
|
||||
allow-clear
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<Form.Item label="轮播图" required>
|
||||
<Upload
|
||||
v-model:file-list="carouselFileList"
|
||||
list-type="picture-card"
|
||||
accept="image/jpeg,image/png,image/jpg"
|
||||
:before-upload="beforeUploadCarousel"
|
||||
:on-preview="onPreviewUploadFile"
|
||||
:on-remove="onRemoveCarousel"
|
||||
>
|
||||
<div>
|
||||
<PlusOutlined />
|
||||
<div class="mt-1 text-xs">选择</div>
|
||||
</div>
|
||||
</Upload>
|
||||
</Form.Item>
|
||||
<Form.Item label="详情图" required>
|
||||
<Upload
|
||||
v-model:file-list="detailFileList"
|
||||
list-type="picture-card"
|
||||
accept="image/jpeg,image/png,image/jpg"
|
||||
:before-upload="beforeUploadDetail"
|
||||
:on-preview="onPreviewUploadFile"
|
||||
:on-remove="onRemoveDetail"
|
||||
>
|
||||
<div>
|
||||
<PlusOutlined />
|
||||
<div class="mt-1 text-xs">选择</div>
|
||||
</div>
|
||||
</Upload>
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<div v-if="form.catId" class="space-y-4">
|
||||
<SpecAxesCard
|
||||
:spec-catalog="specCatalog"
|
||||
:spec-axes="specAxes"
|
||||
:can-add-spec-axis="canAddSpecAxis"
|
||||
:catalog-options-for-axis="catalogOptionsForAxis"
|
||||
:spec-value-display="specValueDisplay"
|
||||
:spec-value-auto-options="specValueAutoOptions"
|
||||
@set-list-ref="onSpecAxesListRef"
|
||||
@axis-catalog-change="onAxisCatalogChange"
|
||||
@spec-value-input="onSpecValueInput"
|
||||
@spec-value-commit="onSpecValueCommit"
|
||||
@spec-value-enter="onSpecValueEnter"
|
||||
@add-spec-value="addSpecValueSlot"
|
||||
@remove-spec-value="removeSpecValue"
|
||||
@remove-spec-axis="removeSpecAxis"
|
||||
@add-spec-axis="addSpecAxis"
|
||||
/>
|
||||
|
||||
<SkuTableCard
|
||||
v-model:bind-pick-sku-ids="bindPickSkuIds"
|
||||
:sku-select-options="skuSelectOptions"
|
||||
:sku-rows="skuRows"
|
||||
:spec-axes-length="specAxes.length"
|
||||
:sku-table-columns="skuTableColumns"
|
||||
:sku-table-scroll-x="skuTableScrollX"
|
||||
:sku-spec-cell-display="skuSpecCellDisplay"
|
||||
:sku-spec-cell-auto-options="skuSpecCellAutoOptions"
|
||||
:before-upload-sku="beforeUploadSku"
|
||||
:on-preview-upload-file="onPreviewUploadFile"
|
||||
@search="debouncedLoadSkuCandidates"
|
||||
@dropdown-visible-change="onSkuSelectDropdownOpen"
|
||||
@apply-internal-skus="applyInternalSkusInOrder"
|
||||
@clear-internal-skus="clearInternalSkuBindings"
|
||||
@set-table-wrap-ref="onSkuTableWrapRef"
|
||||
@sku-spec-input="onSkuSpecCellInput"
|
||||
@sku-spec-commit="onSkuSpecCellCommit"
|
||||
@out-sku-sn-change="onOutSkuSnChange"
|
||||
@out-sku-sn-blur="onOutSkuSnBlur"
|
||||
@bind-internal-sku="bindInternalSku"
|
||||
@sku-thumb-file-list-change="onSkuThumbFileListChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="border-border bg-background flex shrink-0 flex-wrap justify-end gap-2 border-t px-4 py-3"
|
||||
>
|
||||
<Space wrap>
|
||||
<Button @click="handleClose">返回</Button>
|
||||
<Button :loading="draftSaving" @click="saveDeskDraft(false)">
|
||||
保存系统草稿
|
||||
</Button>
|
||||
<Button
|
||||
type="default"
|
||||
:loading="draftSaving"
|
||||
:disabled="catAuthAuthorized === false || catAuthChecking"
|
||||
@click="saveDeskDraft(true)"
|
||||
>
|
||||
保存并标记可发布
|
||||
</Button>
|
||||
<Button
|
||||
:loading="platformPushing || draftSaving"
|
||||
:disabled="catAuthAuthorized === false || catAuthChecking"
|
||||
@click="pushToPlatformDraft"
|
||||
>
|
||||
推送到拼多多草稿箱
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
:loading="submitting"
|
||||
:disabled="catAuthAuthorized === false || catAuthChecking"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
立即发布
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Image
|
||||
:style="{ display: 'none' }"
|
||||
:preview="{
|
||||
visible: previewVisible,
|
||||
onVisibleChange: setPreviewVisible,
|
||||
}"
|
||||
:src="previewImage"
|
||||
/>
|
||||
</Form>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,277 @@
|
||||
<script lang="ts" setup>
|
||||
import type { UploadFile, UploadProps } from 'ant-design-vue';
|
||||
import type { SkuRow } from './types';
|
||||
|
||||
import { PlusOutlined } from '@ant-design/icons-vue';
|
||||
|
||||
import {
|
||||
Alert,
|
||||
AutoComplete,
|
||||
Button,
|
||||
Card,
|
||||
Input,
|
||||
InputNumber,
|
||||
Select,
|
||||
Table,
|
||||
Upload,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
defineOptions({ name: 'SkuTableCard' });
|
||||
|
||||
defineProps<{
|
||||
bindPickSkuIds: number[];
|
||||
skuSelectOptions: Array<{ label: string; value: number }>;
|
||||
skuRows: SkuRow[];
|
||||
specAxesLength: number;
|
||||
skuTableColumns: any[];
|
||||
skuTableScrollX: number;
|
||||
skuSpecCellDisplay: (record: Record<string, any>, axisKey: string) => string;
|
||||
skuSpecCellAutoOptions: (
|
||||
record: Record<string, any>,
|
||||
axisKey: string,
|
||||
) => Array<{ label: string; value: string }>;
|
||||
beforeUploadSku: (rowKey: number) => UploadProps['beforeUpload'];
|
||||
onPreviewUploadFile: (file: UploadFile) => void;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:bindPickSkuIds': [ids: number[]];
|
||||
search: [keyword: string];
|
||||
'dropdown-visible-change': [open: boolean];
|
||||
'apply-internal-skus': [];
|
||||
'clear-internal-skus': [];
|
||||
'set-table-wrap-ref': [el: HTMLElement | null];
|
||||
'sku-spec-input': [rowKey: number, axisKey: string, text: string];
|
||||
'sku-spec-commit': [rowKey: number, axisKey: string];
|
||||
'out-sku-sn-change': [rowKey: number, value: string];
|
||||
'out-sku-sn-blur': [rowKey: number];
|
||||
'bind-internal-sku': [rowKey: number, skuId?: number];
|
||||
'sku-thumb-file-list-change': [rowKey: number, list: UploadFile[]];
|
||||
}>();
|
||||
|
||||
function setTableWrapRef(el: unknown) {
|
||||
emit('set-table-wrap-ref', (el as HTMLElement | null) ?? null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card size="small" title="内部 SKU 拉入">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Select
|
||||
:value="bindPickSkuIds"
|
||||
mode="multiple"
|
||||
show-search
|
||||
allow-clear
|
||||
class="min-w-[240px] flex-1"
|
||||
placeholder="搜索并多选内部 SKU"
|
||||
:filter-option="false"
|
||||
:options="skuSelectOptions"
|
||||
@update:value="(v) => emit('update:bindPickSkuIds', (v as number[]) ?? [])"
|
||||
@search="(kw: string) => emit('search', kw)"
|
||||
@dropdown-visible-change="
|
||||
(open: boolean) => emit('dropdown-visible-change', open)
|
||||
"
|
||||
/>
|
||||
<Button type="primary" @click="emit('apply-internal-skus')">
|
||||
按行序填入
|
||||
</Button>
|
||||
<Button @click="emit('clear-internal-skus')">清空关联</Button>
|
||||
</div>
|
||||
<p class="mt-2 mb-0 text-xs text-muted-foreground">
|
||||
按下方 SKU 表从上到下依次关联;一行一个。有内部编码时会写入商家编码。
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
<Card size="small">
|
||||
<template #title>
|
||||
SKU 列表
|
||||
<span class="ml-1 text-sm font-normal text-muted-foreground">
|
||||
({{ skuRows.length }} 个组合)
|
||||
</span>
|
||||
</template>
|
||||
<Alert
|
||||
v-if="specAxesLength > 0 && skuRows.length === 0"
|
||||
type="warning"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
message="请先为规格填写取值"
|
||||
/>
|
||||
|
||||
<div :ref="setTableWrapRef">
|
||||
<Table
|
||||
:pagination="false"
|
||||
:scroll="{ x: skuTableScrollX, y: 400 }"
|
||||
:data-source="skuRows"
|
||||
row-key="key"
|
||||
:locale="{ emptyText: '暂无 SKU 组合' }"
|
||||
:columns="skuTableColumns"
|
||||
>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="String(column.key || '').startsWith('spec_')">
|
||||
<AutoComplete
|
||||
:value="
|
||||
skuSpecCellDisplay(
|
||||
record,
|
||||
String(column.key).replace(/^spec_/, ''),
|
||||
)
|
||||
"
|
||||
class="w-full min-w-[100px]"
|
||||
:options="
|
||||
skuSpecCellAutoOptions(
|
||||
record,
|
||||
String(column.key).replace(/^spec_/, ''),
|
||||
)
|
||||
"
|
||||
placeholder="规格值"
|
||||
allow-clear
|
||||
@update:value="
|
||||
(v) =>
|
||||
emit(
|
||||
'sku-spec-input',
|
||||
record.key,
|
||||
String(column.key).replace(/^spec_/, ''),
|
||||
v == null ? '' : String(v),
|
||||
)
|
||||
"
|
||||
@blur="
|
||||
emit(
|
||||
'sku-spec-commit',
|
||||
record.key,
|
||||
String(column.key).replace(/^spec_/, ''),
|
||||
)
|
||||
"
|
||||
@select="
|
||||
() =>
|
||||
emit(
|
||||
'sku-spec-commit',
|
||||
record.key,
|
||||
String(column.key).replace(/^spec_/, ''),
|
||||
)
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'code'">
|
||||
<Input
|
||||
:value="record.outSkuSn"
|
||||
placeholder="商家编码"
|
||||
@update:value="
|
||||
(v) =>
|
||||
emit(
|
||||
'out-sku-sn-change',
|
||||
record.key,
|
||||
v == null ? '' : String(v),
|
||||
)
|
||||
"
|
||||
@blur="() => emit('out-sku-sn-blur', record.key)"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'internalSku'">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<template v-if="record.codeMatchStatus === 'checking'">
|
||||
<span class="text-xs text-muted-foreground">校验中…</span>
|
||||
</template>
|
||||
<template v-else-if="record.codeMatchStatus === 'unmatched'">
|
||||
<span class="text-xs text-orange-500">非内部SKU</span>
|
||||
</template>
|
||||
<template v-else-if="record.internalSkuId">
|
||||
<div
|
||||
class="truncate text-xs"
|
||||
:title="
|
||||
[record.productName, record.internalSkuName]
|
||||
.filter(Boolean)
|
||||
.join(' / ') || undefined
|
||||
"
|
||||
>
|
||||
{{ record.productName || '—' }}
|
||||
</div>
|
||||
<div class="flex items-center gap-1 text-xs">
|
||||
<span
|
||||
class="min-w-0 truncate text-muted-foreground"
|
||||
:title="record.internalSkuName || undefined"
|
||||
>
|
||||
{{ record.internalSkuName || '已关联' }}
|
||||
</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
class="h-auto shrink-0 px-0"
|
||||
@click="emit('bind-internal-sku', record.key, undefined)"
|
||||
>
|
||||
清除
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="text-xs text-muted-foreground">未关联</span>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'price'">
|
||||
<InputNumber
|
||||
v-model:value="record.priceYuan"
|
||||
:min="0.01"
|
||||
:precision="2"
|
||||
class="w-full"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'multi'">
|
||||
<InputNumber
|
||||
v-model:value="record.multiPriceYuan"
|
||||
:min="0.01"
|
||||
:precision="2"
|
||||
class="w-full"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'qty'">
|
||||
<InputNumber
|
||||
v-model:value="record.quantity"
|
||||
:min="0"
|
||||
class="w-full"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'weight'">
|
||||
<InputNumber
|
||||
v-model:value="record.weight"
|
||||
:min="1"
|
||||
class="w-full"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'thumb'">
|
||||
<Upload
|
||||
class="sku-thumb-upload"
|
||||
:file-list="record.thumbFileList"
|
||||
list-type="picture-card"
|
||||
accept="image/jpeg,image/png,image/jpg"
|
||||
:max-count="1"
|
||||
:before-upload="beforeUploadSku(record.key)"
|
||||
:on-preview="onPreviewUploadFile"
|
||||
@update:file-list="
|
||||
(list: UploadFile[]) =>
|
||||
emit('sku-thumb-file-list-change', record.key, list)
|
||||
"
|
||||
>
|
||||
<div v-if="record.thumbFileList.length === 0">
|
||||
<PlusOutlined />
|
||||
</div>
|
||||
</Upload>
|
||||
</template>
|
||||
</template>
|
||||
</Table>
|
||||
</div>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* SKU 列内缩略图:更小的 picture-card,悬停仍显示预览/删除 */
|
||||
.sku-thumb-upload :deep(.ant-upload-select),
|
||||
.sku-thumb-upload :deep(.ant-upload-list-item-container) {
|
||||
width: 56px !important;
|
||||
height: 56px !important;
|
||||
margin-block: 0 !important;
|
||||
margin-inline-end: 0 !important;
|
||||
}
|
||||
|
||||
.sku-thumb-upload :deep(.ant-upload-list-item) {
|
||||
padding: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script lang="ts" setup>
|
||||
import type { SpecAxis, SpecCatalogItem } from './types';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
import { MinusOutlined, PlusOutlined } from '@ant-design/icons-vue';
|
||||
|
||||
import { Alert, AutoComplete, Button, Card, Empty, Select } from 'ant-design-vue';
|
||||
|
||||
defineOptions({ name: 'SpecAxesCard' });
|
||||
|
||||
/** 规格轴 / 规格值拖拽手柄 */
|
||||
const GripVerticalIcon = createIconifyIcon('lucide:grip-vertical');
|
||||
|
||||
defineProps<{
|
||||
specCatalog: SpecCatalogItem[];
|
||||
specAxes: SpecAxis[];
|
||||
canAddSpecAxis: boolean;
|
||||
catalogOptionsForAxis: (rowId: number) => Array<{ label: string; value: string }>;
|
||||
specValueDisplay: (axis: SpecAxis, index: number) => string;
|
||||
specValueAutoOptions: (
|
||||
axis: SpecAxis,
|
||||
index: number,
|
||||
) => Array<{ label: string; value: string }>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'set-list-ref': [el: HTMLElement | null];
|
||||
'axis-catalog-change': [rowId: number, catalogKey: string];
|
||||
'spec-value-input': [rowId: number, index: number, text: string];
|
||||
'spec-value-commit': [rowId: number, index: number];
|
||||
'spec-value-enter': [rowId: number, index: number];
|
||||
'add-spec-value': [rowId: number];
|
||||
'remove-spec-value': [rowId: number, index: number];
|
||||
'remove-spec-axis': [rowId: number];
|
||||
'add-spec-axis': [];
|
||||
}>();
|
||||
|
||||
function setListRef(el: unknown) {
|
||||
emit('set-list-ref', (el as HTMLElement | null) ?? null);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card size="small" title="销售规格">
|
||||
<Alert
|
||||
type="info"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
message="默认一条「款式」;最多两种规格。拖拽可调顺序。规格文案可改,已填商家编码会保留;增删规格值才会增删 SKU 行。"
|
||||
/>
|
||||
<Empty
|
||||
v-if="specCatalog.length === 0"
|
||||
description="当前类目暂无销售规格,无法生成 SKU 组合,请更换类目。"
|
||||
:image="Empty.PRESENTED_IMAGE_SIMPLE"
|
||||
/>
|
||||
<div v-else class="space-y-3">
|
||||
<div :ref="setListRef" class="space-y-3">
|
||||
<div
|
||||
v-for="axis in specAxes"
|
||||
:key="axis.rowId"
|
||||
class="spec-axis-card flex flex-wrap items-start gap-2 rounded-md border border-border/60 bg-muted/20 p-3"
|
||||
>
|
||||
<span
|
||||
v-if="specAxes.length > 1"
|
||||
class="spec-axis-drag-handle mt-1.5 shrink-0 cursor-grab text-muted-foreground active:cursor-grabbing"
|
||||
title="拖动调整规格顺序"
|
||||
>
|
||||
<GripVerticalIcon class="size-4" />
|
||||
</span>
|
||||
<Select
|
||||
:value="axis.catalogKey"
|
||||
class="w-28 shrink-0"
|
||||
:options="catalogOptionsForAxis(axis.rowId)"
|
||||
@change="
|
||||
(v: any) => emit('axis-catalog-change', axis.rowId, String(v))
|
||||
"
|
||||
/>
|
||||
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-2">
|
||||
<div
|
||||
:data-spec-values="axis.rowId"
|
||||
class="flex flex-wrap items-center gap-2"
|
||||
>
|
||||
<div
|
||||
v-for="(slot, vi) in axis.selectedValues"
|
||||
:key="slot.id"
|
||||
class="spec-value-chip flex items-center gap-1"
|
||||
:data-spec-value-input="`${axis.rowId}_${vi}`"
|
||||
>
|
||||
<span
|
||||
class="spec-value-drag-handle shrink-0 cursor-grab text-muted-foreground active:cursor-grabbing"
|
||||
title="拖动调整取值顺序"
|
||||
>
|
||||
<GripVerticalIcon class="size-3.5" />
|
||||
</span>
|
||||
<AutoComplete
|
||||
:value="specValueDisplay(axis, vi)"
|
||||
class="w-36"
|
||||
:options="specValueAutoOptions(axis, vi)"
|
||||
placeholder="输入或选预设,回车新增"
|
||||
allow-clear
|
||||
@update:value="
|
||||
(v) =>
|
||||
emit(
|
||||
'spec-value-input',
|
||||
axis.rowId,
|
||||
vi,
|
||||
v == null ? '' : String(v),
|
||||
)
|
||||
"
|
||||
@blur="emit('spec-value-commit', axis.rowId, vi)"
|
||||
@select="() => emit('spec-value-commit', axis.rowId, vi)"
|
||||
@keydown.enter.prevent="
|
||||
emit('spec-value-enter', axis.rowId, vi)
|
||||
"
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
size="small"
|
||||
title="删除规格值"
|
||||
@click="emit('remove-spec-value', axis.rowId, vi)"
|
||||
>
|
||||
<template #icon>
|
||||
<MinusOutlined />
|
||||
</template>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="dashed" @click="emit('add-spec-value', axis.rowId)">
|
||||
<template #icon>
|
||||
<PlusOutlined />
|
||||
</template>
|
||||
规格值
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
v-if="specAxes.length > 1"
|
||||
type="link"
|
||||
danger
|
||||
class="shrink-0"
|
||||
@click="emit('remove-spec-axis', axis.rowId)"
|
||||
>
|
||||
删除规格
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
v-if="canAddSpecAxis"
|
||||
type="dashed"
|
||||
block
|
||||
@click="emit('add-spec-axis')"
|
||||
>
|
||||
<PlusOutlined />
|
||||
添加规格
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -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<string, string>;
|
||||
};
|
||||
|
||||
/** 类目可选父规格(下拉候选);用户手动添加进编辑区 */
|
||||
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<string, string>;
|
||||
};
|
||||
|
||||
/** 创建空白发布表单字段 */
|
||||
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,
|
||||
};
|
||||
}
|
||||
+238
@@ -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<SpecAxis[]>;
|
||||
specCatalog: Ref<SpecCatalogItem[]>;
|
||||
skuRows: Ref<SkuRow[]>;
|
||||
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<string, unknown>): 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<string, unknown>): 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<string, unknown>): 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<string>();
|
||||
const prevByCatalog = new Map(
|
||||
specAxes.value.map((a) => [a.catalogKey, a] as const),
|
||||
);
|
||||
const prevByName = new Map(
|
||||
specAxes.value.map((a) => [a.name, a] as const),
|
||||
);
|
||||
const 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<string, unknown>,
|
||||
): 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<typeof usePublishAgent>;
|
||||
+742
@@ -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<boolean>;
|
||||
/** 切换店铺/清空类目时清空 SKU */
|
||||
clearSkuRows: () => void;
|
||||
specAxes: Ref<SpecAxis[]>;
|
||||
specCatalog: Ref<SpecCatalogItem[]>;
|
||||
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<PddGoodsPublishVO.CostTemplateDetail | null>(
|
||||
null,
|
||||
);
|
||||
const costTemplateDetailLoading = ref(false);
|
||||
const catTemplate = ref<PddGoodsPublishVO.CatTemplate | null>(null);
|
||||
const parentSpecs = ref<PddGoodsPublishVO.ParentSpec[]>([]);
|
||||
|
||||
const nonSaleProps = computed(() =>
|
||||
(catTemplate.value?.properties ?? []).filter((p) => !p.sale),
|
||||
);
|
||||
const saleProps = computed(() =>
|
||||
(catTemplate.value?.properties ?? []).filter((p) => p.sale),
|
||||
);
|
||||
|
||||
const rootCatOptions = ref<CatCascaderNode[]>([]);
|
||||
const catsLoading = ref(false);
|
||||
/** 已按 parent 拉过的类目,避免重复请求 */
|
||||
const loadedCatParents = ref<Set<number>>(new Set());
|
||||
|
||||
/** 本地库同步状态:仅 SUCCESS 走本地树 + 跨层搜索,其余降级拼多多授权类目接口 */
|
||||
const catSyncStatus = ref<null | string>(null);
|
||||
const localCatReady = computed(() => catSyncStatus.value === 'SUCCESS');
|
||||
const catSourceDegraded = computed(() => !localCatReady.value);
|
||||
|
||||
/** Cascader 搜索框文案;本地就绪时用于跨层检索 */
|
||||
const catCascaderSearch = ref('');
|
||||
/** 本地跨层搜索命中(扁平叶子),非空时临时替换树选项 */
|
||||
const catSearchHitOptions = ref<CatCascaderNode[]>([]);
|
||||
const catSearchLoading = ref(false);
|
||||
let catSearchTimer: undefined | ReturnType<typeof setTimeout>;
|
||||
/** 选中后展示的完整路径文案 */
|
||||
const selectedCatPathLabel = ref('');
|
||||
/**
|
||||
* 搜索选中的叶子:清空搜索结果后仍挂到 options 上,避免 Cascader 只显示裸 catId。
|
||||
*/
|
||||
const pinnedSelectedCat = ref<CatCascaderNode | null>(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<boolean | null>(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<CatCascaderNode[]> {
|
||||
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<typeof usePublishCategory>;
|
||||
+854
@@ -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<boolean>;
|
||||
emit: EmitDraft;
|
||||
closeEditor: () => void;
|
||||
// category
|
||||
loadShops: (keyword?: string) => Promise<void>;
|
||||
loadRootCats: () => Promise<void>;
|
||||
loadLogistics: () => Promise<void>;
|
||||
loadCostTemplateDetail: (templateId?: number) => Promise<void>;
|
||||
loadCatContextForHydrate: (
|
||||
catId: number,
|
||||
path: number[],
|
||||
pathLabel: string,
|
||||
) => Promise<void>;
|
||||
resolveFullCatPath: () => number[];
|
||||
catAuthAuthorized: Ref<boolean | null>;
|
||||
catAuthMessage: Ref<string>;
|
||||
catAuthChecking: Ref<boolean>;
|
||||
selectedCatPathLabel: Ref<string>;
|
||||
nonSaleProps: ComputedRef<PddGoodsPublishVO.CatProperty[]>;
|
||||
// products
|
||||
productOptions: Ref<{ label: string; value: number; name: string }[]>;
|
||||
loadProducts: (keyword?: string) => Promise<void>;
|
||||
// specs
|
||||
specAxes: Ref<SpecAxis[]>;
|
||||
specCatalog: Ref<SpecCatalogItem[]>;
|
||||
normalizeSpecValueSlots: (raw: unknown) => SpecAxis['selectedValues'];
|
||||
rebuildSpecCatalogAndSeed: () => void;
|
||||
labelOfAxisValue: (axis: SpecAxis, value: string) => string;
|
||||
effectiveSpecValues: (axis: SpecAxis) => string[];
|
||||
refreshSpecSortables: () => Promise<void>;
|
||||
bumpSpecAxisRowSeqFromIds: (ids: number[]) => void;
|
||||
// sku
|
||||
skuRows: Ref<SkuRow[]>;
|
||||
loadSkuCandidates: (keyword?: string) => Promise<void>;
|
||||
comboKeyFromSlots: (
|
||||
parts: Array<{ axisKey: string; slotId: number }>,
|
||||
) => string;
|
||||
bumpSkuRowSeqFromKeys: (keys: number[]) => void;
|
||||
nextSkuRowKey: () => number;
|
||||
// images
|
||||
carouselFileList: Ref<UploadFile[]>;
|
||||
detailFileList: Ref<UploadFile[]>;
|
||||
ensurePersistedUploads: (files: UploadFile[]) => Promise<PersistedUpload[]>;
|
||||
toUploadFilesFromPersisted: (
|
||||
items: PersistedUpload[],
|
||||
) => Promise<UploadFile[]>;
|
||||
}) {
|
||||
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<number | null>(null);
|
||||
const submitting = ref(false);
|
||||
const specIdCache = new Map<string, number>();
|
||||
|
||||
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<number> {
|
||||
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<number, number>,
|
||||
): Promise<PddGoodsPublishDTO.Publish> {
|
||||
// 非销售属性 → 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<string>();
|
||||
|
||||
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<string, unknown> | undefined;
|
||||
if (draft.payloadJson) {
|
||||
try {
|
||||
const root = JSON.parse(draft.payloadJson) as {
|
||||
editorState?: Record<string, unknown>;
|
||||
};
|
||||
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<string, string>),
|
||||
};
|
||||
}
|
||||
|
||||
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<string, unknown>;
|
||||
const thumb = r.thumb as PersistedUpload | null | undefined;
|
||||
const rowIndex = rows.length;
|
||||
const saleValues =
|
||||
r.saleValues && typeof r.saleValues === 'object'
|
||||
? { ...(r.saleValues as Record<string, string>) }
|
||||
: {};
|
||||
// 按 saleValues 反查槽位,重绑 comboKey(兼容旧草稿 token 键)
|
||||
const parts = specAxes.value.map((a) => {
|
||||
const token = saleValues[a.key] ?? '';
|
||||
const slot =
|
||||
a.selectedValues.find((s) => s.token === token) ||
|
||||
a.selectedValues.find(
|
||||
(s) => labelOfAxisValue(a, s.token) === token,
|
||||
);
|
||||
return { axisKey: a.key, slotId: slot?.id ?? -1 };
|
||||
});
|
||||
rows.push({
|
||||
key: Number(r.key) || 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<number, PersistedUpload>();
|
||||
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<number, number>();
|
||||
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<number, number>();
|
||||
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<typeof usePublishDraft>;
|
||||
+361
@@ -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<SkuRow[]>) {
|
||||
let uploadUidSeq = 1;
|
||||
|
||||
const carouselFileList = ref<UploadFile[]>([]);
|
||||
const detailFileList = ref<UploadFile[]>([]);
|
||||
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<number> {
|
||||
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<PersistedUpload[]> {
|
||||
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<number, string>();
|
||||
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<ReturnType<typeof uploadFiles>> = [];
|
||||
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<PersistedUpload> {
|
||||
const [one] = await ensurePersistedUploads([file]);
|
||||
if (!one) {
|
||||
throw new Error(`图片上传失败:${file.name || file.uid}`);
|
||||
}
|
||||
return one;
|
||||
}
|
||||
|
||||
async function toUploadFilesFromPersisted(
|
||||
items: PersistedUpload[],
|
||||
): Promise<UploadFile[]> {
|
||||
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<number, string>();
|
||||
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<UploadFile> {
|
||||
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<typeof usePublishImages>;
|
||||
@@ -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<SkuRow[]>;
|
||||
specAxes: Ref<SpecAxis[]>;
|
||||
catTemplate: Ref<PddGoodsPublishVO.CatTemplate | null>;
|
||||
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<ProductSkuVO.Info[]>([]);
|
||||
/** SKU 规格列内联编辑草稿:`${rowKey}_${axisKey}` → 输入中文案 */
|
||||
const skuSpecDraft = ref<Record<string, string>>({});
|
||||
/** 上方「内部 SKU 拉入」多选 */
|
||||
const bindPickSkuIds = ref<number[]>([]);
|
||||
/** 商家编码校验防抖定时器(按行) */
|
||||
const outSkuSnTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
/** 商家编码校验序号,防止乱序回写 */
|
||||
const outSkuSnValidateSeq = new Map<number, number>();
|
||||
/** 规格表容器:新增后滚到表体底部 */
|
||||
const skuTableWrapRef = ref<HTMLElement | null>(null);
|
||||
|
||||
/** 规格列行合并:前缀规格值相同则合并(笛卡尔积顺序下连续) */
|
||||
const skuSpecRowSpans = computed(() => {
|
||||
const rows = skuRows.value;
|
||||
const axes = specAxes.value;
|
||||
const spansByAxisKey = new Map<string, number[]>();
|
||||
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<T>(lists: T[][]): T[][] {
|
||||
if (lists.length === 0) return [];
|
||||
return lists.reduce<T[][]>(
|
||||
(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<string, string> },
|
||||
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<string, any>, 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<string, any>, axisKey: string) {
|
||||
const axis = specAxes.value.find((a) => a.key === axisKey);
|
||||
if (!axis) return [];
|
||||
const current = (record.saleValues?.[axisKey] as string | undefined) ?? '';
|
||||
const index = axis.selectedValues.findIndex((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<string, string> = {};
|
||||
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<string, SkuRow>();
|
||||
for (const r of prevRows) {
|
||||
const code = r.outSkuSn.trim();
|
||||
if (code && !prevByCode.has(code)) prevByCode.set(code, r);
|
||||
}
|
||||
const usedCodes = new Set<string>();
|
||||
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<typeof usePublishSku>;
|
||||
+629
@@ -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<PddGoodsPublishVO.CatProperty[]> | ComputedRef<PddGoodsPublishVO.CatProperty[]>;
|
||||
parentSpecs: Ref<PddGoodsPublishVO.ParentSpec[]>;
|
||||
/** 与 category / draft 共享,由壳层创建 */
|
||||
specAxes: Ref<SpecAxis[]>;
|
||||
specCatalog: Ref<SpecCatalogItem[]>;
|
||||
skuRows: Ref<SkuRow[]>;
|
||||
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<HTMLElement | null>(null);
|
||||
let axesSortable: null | Sortable = null;
|
||||
/** 各轴规格值容器的 Sortable 实例 */
|
||||
const valueSortables = new Map<number, Sortable>();
|
||||
|
||||
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<string>();
|
||||
/** 旧轴 key → 新轴 key */
|
||||
const keyMap = new Map<string, string>();
|
||||
/** 旧轴 key → (旧 token → 新 token) */
|
||||
const valueMaps = new Map<string, Map<string, string>>();
|
||||
|
||||
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<string, string>();
|
||||
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<string, string> = {};
|
||||
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<typeof usePublishSpecs>;
|
||||
Reference in New Issue
Block a user