feat: 补齐拼多多类目属性单位与日期控件及发品传参

This commit is contained in:
2026-10-09 13:35:17 +08:00
parent 68ef451ab3
commit e5050317ec
6 changed files with 612 additions and 34 deletions
@@ -44,6 +44,7 @@ import {
import { getProductPageApi } from '#/api/ec/product';
import CatPropertyField from './components/CatPropertyField.vue';
import SpecAxesCard from './components/SpecAxesCard.vue';
import SkuTableCard from './components/SkuTableCard.vue';
import type { SpecAxis, SpecCatalogItem, SkuRow } from './types';
@@ -175,6 +176,7 @@ const draft = usePublishDraft({
catAuthMessage: category.catAuthMessage,
catAuthChecking: category.catAuthChecking,
selectedCatPathLabel: category.selectedCatPathLabel,
allNonSaleProps: category.allNonSaleProps,
nonSaleProps: category.nonSaleProps,
productOptions,
loadProducts,
@@ -696,24 +698,10 @@ function onSkuTableWrapRef(el: HTMLElement | null) {
:label="p.name"
:required="!!p.required"
>
<Select
v-if="p.values?.length"
<CatPropertyField
v-model:value="form.goodsPropValues[String(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.refPid)]"
allow-clear
v-model:unit="form.goodsPropUnits[String(p.refPid)]"
:property="p"
/>
</Form.Item>
</div>
@@ -0,0 +1,345 @@
<script lang="ts" setup>
/**
* 类目非销售属性控件:按 propertyValueType 渲染下拉/数值+单位/日期等。
*/
import type { Dayjs } from 'dayjs';
import type { PddGoodsPublishVO } from '#/api/channel/pdd/goods';
import { computed } from 'vue';
import {
DatePicker,
Input,
InputNumber,
Select,
Space,
TimePicker,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
effectiveValueUnits,
resolveCatPropControlKind,
} from '../utils/cat-property';
type CatProperty = PddGoodsPublishVO.CatProperty;
const props = defineProps<{
property: CatProperty;
value?: string;
unit?: string;
}>();
const emit = defineEmits<{
'update:value': [string | undefined];
'update:unit': [string | undefined];
}>();
const kind = computed(() => resolveCatPropControlKind(props.property));
const units = computed(() => effectiveValueUnits(props.property));
const multiSelect = computed(
() => (props.property.chooseMaxNum ?? 1) > 1,
);
const selectValue = computed(() => {
if (!props.value) return multiSelect.value ? [] : undefined;
if (multiSelect.value) {
return props.value.split(',').filter(Boolean);
}
return props.value;
});
const numberValue = computed(() => {
if (props.value == null || props.value === '') return undefined;
const n = Number(props.value);
return Number.isNaN(n) ? undefined : n;
});
const precision = computed(() => {
const p = props.property.valuePrecision;
return p != null && p > 0 ? p : undefined;
});
const dateValue = computed(() => {
if (!props.value) return undefined;
const d = dayjs(props.value, 'YYYY-MM-DD', true);
return d.isValid() ? d : undefined;
});
const monthValue = computed(() => {
if (!props.value) return undefined;
const d = dayjs(props.value, 'YYYY-MM', true);
return d.isValid() ? d : undefined;
});
const timeValue = computed(() => {
if (!props.value) return undefined;
const d = dayjs(props.value, 'HH:mm:ss', true);
return d.isValid() ? d : undefined;
});
const dateRangeValue = computed((): [Dayjs, Dayjs] | undefined => {
if (!props.value) return undefined;
const [a, b] = props.value.split(',');
if (!a?.trim() || !b?.trim()) return undefined;
const d1 = dayjs(a.trim(), 'YYYY-MM-DD', true);
const d2 = dayjs(b.trim(), 'YYYY-MM-DD', true);
if (!d1.isValid() || !d2.isValid()) return undefined;
return [d1, d2];
});
function emitValue(v: string | undefined) {
emit('update:value', v || undefined);
}
function onSelectChange(v: unknown) {
if (Array.isArray(v)) {
const tokens = v.map((x) => String(x)).filter(Boolean);
emitValue(tokens.length ? tokens.join(',') : undefined);
return;
}
if (v == null || v === '') {
emitValue(undefined);
return;
}
emitValue(String(v));
}
function onNumberChange(v: number | string | null | undefined) {
if (v == null || v === '') {
emitValue(undefined);
return;
}
emitValue(String(v));
}
/** 逗号分隔多段数值(范围 / 乘积) */
function partAt(index: number): number | undefined {
const parts = (props.value ?? '').split(',');
const raw = parts[index]?.trim();
if (raw == null || raw === '') return undefined;
const n = Number(raw);
return Number.isNaN(n) ? undefined : n;
}
function setPart(
index: number,
expect: number,
v: number | string | null | undefined,
) {
const parts = Array.from({ length: expect }, (_, i) => {
return (props.value ?? '').split(',')[i]?.trim() ?? '';
});
parts[index] = v == null || v === '' ? '' : String(v);
emitValue(parts.every((x) => !x) ? undefined : parts.join(','));
}
function formatDay(d: string | Dayjs | null | undefined, fmt: string) {
if (d == null || d === '') return undefined;
const parsed = typeof d === 'string' ? dayjs(d) : d;
return parsed.isValid() ? parsed.format(fmt) : undefined;
}
function onDateChange(d: string | Dayjs | null | undefined) {
emitValue(formatDay(d, 'YYYY-MM-DD'));
}
function onMonthChange(d: string | Dayjs | null | undefined) {
emitValue(formatDay(d, 'YYYY-MM'));
}
function onTimeChange(d: string | Dayjs | null | undefined) {
emitValue(formatDay(d, 'HH:mm:ss'));
}
function onDateRangeChange(
dates: [string, string] | [Dayjs, Dayjs] | null | undefined,
) {
if (!dates?.[0] || !dates?.[1]) {
emitValue(undefined);
return;
}
const a = formatDay(dates[0], 'YYYY-MM-DD');
const b = formatDay(dates[1], 'YYYY-MM-DD');
emitValue(a && b ? `${a},${b}` : undefined);
}
function onUnitChange(v: unknown) {
if (v == null || v === '') {
emit('update:unit', undefined);
return;
}
emit('update:unit', String(v));
}
const selectOptions = computed(() =>
(props.property.values || []).map((v) => ({
label: v.value,
value: String(v.vid ?? v.value),
})),
);
function popupContainer() {
return document.body;
}
</script>
<template>
<!--
半栏占满:左侧主控件包 flex-1 并强制 width:100%(覆盖 InputNumber 默认 90px),
右侧单位固定 88px,二者仅 gap-2,不会中间留白也不会互相挤扁。
-->
<div class="flex w-full min-w-0 items-center gap-2">
<div class="min-w-0 flex-1">
<Select
v-if="kind === 'select'"
class="w-full"
allow-clear
show-search
option-filter-prop="label"
:mode="multiSelect ? 'multiple' : undefined"
:max-tag-count="multiSelect ? 'responsive' : undefined"
:value="selectValue"
:options="selectOptions"
@update:value="onSelectChange"
/>
<InputNumber
v-else-if="kind === 'number'"
:style="{ width: '100%' }"
:value="numberValue"
:precision="precision"
:min="
property.minValue?.trim() ? Number(property.minValue) : undefined
"
:max="
property.maxValue?.trim() && Number(property.maxValue) > 0
? Number(property.maxValue)
: undefined
"
@update:value="onNumberChange"
/>
<Space v-else-if="kind === 'range'" :size="4">
<InputNumber
class="w-28"
:value="partAt(0)"
:precision="precision"
@update:value="(v) => setPart(0, 2, v)"
/>
<span>~</span>
<InputNumber
class="w-28"
:value="partAt(1)"
:precision="precision"
@update:value="(v) => setPart(1, 2, v)"
/>
</Space>
<Space v-else-if="kind === 'product2'" :size="4">
<InputNumber
class="w-24"
:value="partAt(0)"
:precision="precision"
@update:value="(v) => setPart(0, 2, v)"
/>
<span>×</span>
<InputNumber
class="w-24"
:value="partAt(1)"
:precision="precision"
@update:value="(v) => setPart(1, 2, v)"
/>
</Space>
<Space v-else-if="kind === 'product3'" :size="4">
<InputNumber
class="w-20"
:value="partAt(0)"
:precision="precision"
@update:value="(v) => setPart(0, 3, v)"
/>
<span>×</span>
<InputNumber
class="w-20"
:value="partAt(1)"
:precision="precision"
@update:value="(v) => setPart(1, 3, v)"
/>
<span>×</span>
<InputNumber
class="w-20"
:value="partAt(2)"
:precision="precision"
@update:value="(v) => setPart(2, 3, v)"
/>
</Space>
<DatePicker
v-else-if="kind === 'date'"
class="w-full"
allow-clear
format="YYYY-MM-DD"
:value="dateValue"
:get-popup-container="popupContainer"
@update:value="onDateChange"
/>
<DatePicker.RangePicker
v-else-if="kind === 'dateRange'"
class="w-full"
allow-clear
format="YYYY-MM-DD"
:value="dateRangeValue"
:get-popup-container="popupContainer"
@update:value="onDateRangeChange"
/>
<DatePicker
v-else-if="kind === 'month'"
class="w-full"
picker="month"
allow-clear
format="YYYY-MM"
:value="monthValue"
:get-popup-container="popupContainer"
@update:value="onMonthChange"
/>
<TimePicker
v-else-if="kind === 'time'"
class="w-full"
allow-clear
format="HH:mm:ss"
:value="timeValue"
:get-popup-container="popupContainer"
@update:value="onTimeChange"
/>
<Input
v-else-if="kind === 'material' || kind === 'unsupported'"
class="w-full"
disabled
placeholder="该属性类型暂不支持在线填写"
/>
<Input
v-else
class="w-full"
allow-clear
:value="value"
@update:value="emitValue"
/>
</div>
<Select
v-if="units.length"
:style="{ width: '88px', flex: 'none' }"
allow-clear
:value="unit"
:options="units.map((u) => ({ label: u, value: u }))"
placeholder="单位"
@update:value="onUnitChange"
/>
</div>
</template>
@@ -28,6 +28,10 @@ import type {
SpecAxis,
SpecCatalogItem,
} from '../types';
import {
isCatPropVisible,
seedDefaultPropUnits,
} from '../utils/cat-property';
/**
* 类目树 / Cascader / 发布权 / 类目规则与运费加载。
@@ -62,10 +66,16 @@ export function usePublishCategory(options: {
const catRule = ref<PddGoodsPublishVO.CatRule | null>(null);
const parentSpecs = ref<PddGoodsPublishVO.ParentSpec[]>([]);
/** 商品级非销售属性(SKU 维属性另处理) */
const nonSaleProps = computed(() =>
/** 商品级非销售属性(未按展示条件过滤,供默认单位等) */
const allNonSaleProps = computed(() =>
(catRule.value?.properties ?? []).filter((p) => !p.sale && !p.sku),
);
/** 当前可见的非销售属性(含 show_condition) */
const nonSaleProps = computed(() =>
allNonSaleProps.value.filter((p) =>
isCatPropVisible(p, form.goodsPropValues),
),
);
const saleProps = computed(() =>
(catRule.value?.properties ?? []).filter((p) => p.sale),
);
@@ -449,6 +459,7 @@ export function usePublishCategory(options: {
parentSpecs.value = [];
// 类目属性随规则变,需清空;规格/SKU 尽量沿用
form.goodsPropValues = {};
form.goodsPropUnits = {};
await refreshCatAuth(path);
if (!form.pddShopId || !form.catId) return;
if (catAuthAuthorized.value === false) {
@@ -467,6 +478,7 @@ export function usePublishCategory(options: {
]);
catRule.value = tpl;
parentSpecs.value = specs ?? [];
form.goodsPropUnits = seedDefaultPropUnits(tpl?.properties ?? []);
rebuildSpecCatalogPreservingUserData();
} catch (e: any) {
message.error(e?.message || '加载类目发布规则失败');
@@ -547,6 +559,7 @@ export function usePublishCategory(options: {
catRule.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
form.goodsPropUnits = {};
clearSkuRows();
specAxes.value = [];
specCatalog.value = [];
@@ -637,6 +650,11 @@ export function usePublishCategory(options: {
]);
catRule.value = tpl;
parentSpecs.value = specs ?? [];
// 回填后补默认单位,不覆盖草稿已存单位
form.goodsPropUnits = seedDefaultPropUnits(
tpl?.properties ?? [],
form.goodsPropUnits,
);
specCatalog.value = buildSpecCatalog();
} catch (e: any) {
message.error(e?.message || '加载类目发布规则失败');
@@ -668,6 +686,7 @@ export function usePublishCategory(options: {
specCatalog.value = [];
logisticsOptions.value = [];
form.goodsPropValues = {};
form.goodsPropUnits = {};
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
rootCatOptions.value = [];
@@ -706,6 +725,7 @@ export function usePublishCategory(options: {
costTemplateDetailLoading,
catRule,
parentSpecs,
allNonSaleProps,
nonSaleProps,
saleProps,
rootCatOptions,
@@ -27,6 +27,12 @@ import {
type SpecCatalogItem,
type SkuRow,
} from '../types';
import {
buildGoodsPropertyItems,
isCatPropVisible,
seedDefaultPropUnits,
validateCatPropValue,
} from '../utils/cat-property';
type EmitDraft = {
(e: 'draft-saved', draftId: number): void;
@@ -57,6 +63,7 @@ export function usePublishDraft(options: {
catAuthMessage: Ref<string>;
catAuthChecking: Ref<boolean>;
selectedCatPathLabel: Ref<string>;
allNonSaleProps: ComputedRef<PddGoodsPublishVO.CatProperty[]>;
nonSaleProps: ComputedRef<PddGoodsPublishVO.CatProperty[]>;
// products
productOptions: Ref<{ label: string; value: number; name: string }[]>;
@@ -101,6 +108,7 @@ export function usePublishDraft(options: {
catAuthMessage,
catAuthChecking,
selectedCatPathLabel,
allNonSaleProps,
nonSaleProps,
productOptions,
loadProducts,
@@ -193,10 +201,15 @@ export function usePublishDraft(options: {
return false;
}
for (const p of nonSaleProps.value) {
if (!p.required) continue;
if (!isCatPropVisible(p, form.goodsPropValues)) continue;
const key = String(p.refPid);
if (!form.goodsPropValues[key]) {
message.warning(`请填写必填属性:${p.name || key}`);
const err = validateCatPropValue(
p,
form.goodsPropValues[key],
form.goodsPropUnits[key],
);
if (err) {
message.warning(err);
return false;
}
}
@@ -246,22 +259,18 @@ export function usePublishDraft(options: {
detailFileIds: number[],
thumbFileIdBySkuKey: Map<number, number>,
): Promise<PddGoodsPublishDTO.Publish> {
// 非销售属性 → goods_properties(不传 parent_spec_id / spec_id)
// 非销售属性 → goods_properties(不传 parent_spec_id / spec_id;带 value_unit)
const goodsProperties: PddGoodsPublishDTO.GoodsProperty[] = [];
for (const p of nonSaleProps.value) {
if (!isCatPropVisible(p, form.goodsPropValues)) continue;
const key = String(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(
...buildGoodsPropertyItems(
p,
form.goodsPropValues[key],
form.goodsPropUnits[key],
),
);
goodsProperties.push({
refPid: p.refPid,
valueUnit: p.valueUnits?.[0],
vid: matched?.vid,
value: matched?.value ?? raw,
groupId: matched?.groupId,
});
}
/**
@@ -471,6 +480,19 @@ export function usePublishDraft(options: {
...(es.goodsPropValues as Record<string, string>),
};
}
if (
es.goodsPropUnits &&
typeof es.goodsPropUnits === 'object' &&
!Array.isArray(es.goodsPropUnits)
) {
form.goodsPropUnits = {
...(es.goodsPropUnits as Record<string, string>),
};
}
form.goodsPropUnits = seedDefaultPropUnits(
allNonSaleProps.value,
form.goodsPropUnits,
);
const savedAxes = Array.isArray(es.specAxes)
? (es.specAxes as SpecAxis[])
@@ -674,6 +696,7 @@ export function usePublishDraft(options: {
secondHand: form.secondHand,
twoPiecesDiscount: form.twoPiecesDiscount,
goodsPropValues: { ...form.goodsPropValues },
goodsPropUnits: { ...form.goodsPropUnits },
specAxes: specAxes.value.map((a) => ({
rowId: a.rowId,
catalogKey: a.catalogKey,
@@ -101,7 +101,10 @@ export type PublishFormFields = {
secondHand: boolean;
/** 表单展示用折扣:0–10,9.5=9.5折;提交接口时 *10 */
twoPiecesDiscount: number;
/** 非销售属性取值,key=refPid */
goodsPropValues: Record<string, string>;
/** 非销售属性单位(value_unit),key=refPid */
goodsPropUnits: Record<string, string>;
};
/** 表单折扣 → 拼多多接口整数(9.5 → 95) */
@@ -134,6 +137,7 @@ export function createEmptyPublishForm(): PublishFormFields {
secondHand: false,
twoPiecesDiscount: 9.5,
goodsPropValues: {},
goodsPropUnits: {},
};
}
@@ -0,0 +1,198 @@
import type {
PddGoodsPublishDTO,
PddGoodsPublishVO,
} from '#/api/channel/pdd/goods';
type CatProperty = PddGoodsPublishVO.CatProperty;
/** 属性取值控件类型(按 propertyValueType) */
export type CatPropControlKind =
| 'select'
| 'text'
| 'number'
| 'range'
| 'product2'
| 'product3'
| 'date'
| 'dateRange'
| 'month'
| 'time'
| 'material'
| 'unsupported';
/** 非空单位列表 */
export function effectiveValueUnits(p: CatProperty): string[] {
return (p.valueUnits ?? []).map((u) => String(u).trim()).filter(Boolean);
}
/** 根据规则字段决定控件形态;有枚举值时优先下拉 */
export function resolveCatPropControlKind(p: CatProperty): CatPropControlKind {
if (p.values?.length) return 'select';
switch (p.propertyValueType ?? 0) {
case 1:
return 'number';
case 2:
return 'range';
case 3:
return 'product2';
case 4:
return 'product3';
case 5:
return 'date';
case 6:
return 'dateRange';
case 7:
return 'month';
case 8:
return 'time';
case 9:
return 'material';
default:
return 'text';
}
}
/** show_condition:未配置则始终展示;配置了则父属性需命中 parentVids */
export function isCatPropVisible(
p: CatProperty,
goodsPropValues: Record<string, string>,
): boolean {
const conds = p.showCondition;
if (!conds?.length) return true;
return conds.every((c) => {
if (c.parentRefPid == null) return true;
const raw = goodsPropValues[String(c.parentRefPid)]?.trim();
if (!raw) return false;
const parentVids = c.parentVids ?? [];
if (!parentVids.length) return true;
const selected = raw
.split(',')
.map((s) => Number(s.trim()))
.filter((n) => !Number.isNaN(n));
return parentVids.some((vid) => selected.includes(vid));
});
}
/** 切换类目后为数值+单位属性预填首个单位 */
export function seedDefaultPropUnits(
props: CatProperty[],
existing: Record<string, string> = {},
): Record<string, string> {
const next = { ...existing };
for (const p of props) {
if (p.sale || p.sku || p.refPid == null) continue;
const key = String(p.refPid);
if (next[key]) continue;
const units = effectiveValueUnits(p);
if (units[0]) next[key] = units[0];
}
return next;
}
/** 单条非销售属性 → goods_properties 项(多选拆成多条) */
export function buildGoodsPropertyItems(
p: CatProperty,
rawValue: string | undefined,
valueUnit: string | undefined,
): PddGoodsPublishDTO.GoodsProperty[] {
const raw = rawValue?.trim();
if (!raw) return [];
const unit = valueUnit?.trim() || undefined;
const kind = resolveCatPropControlKind(p);
if (kind === 'select' && p.values?.length) {
const tokens = raw.split(',').map((s) => s.trim()).filter(Boolean);
const items: PddGoodsPublishDTO.GoodsProperty[] = [];
for (const token of tokens) {
const matched = p.values.find(
(v) => String(v.vid) === token || v.value === token,
);
items.push({
refPid: p.refPid,
valueUnit: unit,
vid: matched?.vid,
value: matched?.value ?? token,
groupId: matched?.groupId,
});
}
return items;
}
return [
{
refPid: p.refPid,
valueUnit: unit,
value: raw,
},
];
}
/**
* 校验必填/单位/数值范围。
* @returns 失败提示文案;通过返回 null
*/
export function validateCatPropValue(
p: CatProperty,
rawValue: string | undefined,
valueUnit: string | undefined,
): string | null {
const label = p.name || String(p.refPid);
const raw = rawValue?.trim() ?? '';
const kind = resolveCatPropControlKind(p);
if (kind === 'material') {
if (p.required) return `属性「${label}」暂不支持材质表填写,请更换类目或联系运营`;
return null;
}
if (p.required && !raw) {
return `请填写必填属性:${label}`;
}
if (!raw) return null;
const units = effectiveValueUnits(p);
if (units.length && !(valueUnit?.trim())) {
return `请选择属性「${label}」的单位`;
}
if (kind === 'number') {
const n = Number(raw);
if (Number.isNaN(n)) return `属性「${label}」须为数字`;
const min = p.minValue?.trim();
const max = p.maxValue?.trim();
if (min !== undefined && min !== '' && n < Number(min)) {
return `属性「${label}」不能小于 ${min}`;
}
// maxValue 为 "0" 且无业务含义时常见于日期类;数值属性有上限才校验
if (max !== undefined && max !== '' && Number(max) > 0 && n > Number(max)) {
return `属性「${label}」不能大于 ${max}`;
}
}
if (kind === 'range' || kind === 'product2' || kind === 'product3') {
const parts = raw.split(',').map((s) => s.trim());
const expect =
kind === 'range' || kind === 'product2' ? 2 : 3;
if (parts.length !== expect || parts.some((x) => !x || Number.isNaN(Number(x)))) {
return `属性「${label}」请按要求填写完整数值`;
}
}
if (kind === 'date' && !/^\d{4}-\d{2}-\d{2}$/.test(raw)) {
return `属性「${label}」请选择日期(YYYY-MM-DD)`;
}
if (kind === 'month' && !/^\d{4}-\d{2}$/.test(raw)) {
return `属性「${label}」请选择月份(YYYY-MM)`;
}
if (kind === 'dateRange') {
const parts = raw.split(',');
if (
parts.length !== 2 ||
!parts.every((x) => /^\d{4}-\d{2}-\d{2}$/.test(x.trim()))
) {
return `属性「${label}」请选择日期区间`;
}
}
return null;
}