feat: 新增拼多多发布工作台

This commit is contained in:
2026-09-14 11:43:01 +08:00
parent 6246bd2233
commit 6e12dc62e2
36 changed files with 6138 additions and 2827 deletions
@@ -7,6 +7,8 @@ import type {
PddGoodsPublishDTO,
PddGoodsPublishVO,
PddGoodsVO,
PddPublishDeskDTO,
PddPublishDeskVO,
} from './types';
/** 分页查询拼多多渠道商品 */
@@ -118,3 +120,78 @@ export async function publishPddGoodsApi(data: PddGoodsPublishDTO.Publish) {
data,
);
}
/** 发布工作台:草稿分页(含按店计数) */
export async function listPddPublishDeskDraftsApi(
params: PageQueryDTO<PddPublishDeskDTO.DraftFilters>,
) {
return requestClient.post<PddPublishDeskVO.DraftPage>(
'/channel/pdd/goods/publish-desk/drafts/list',
params,
);
}
export async function listPddPublishDeskShopCountsApi() {
return requestClient.get<PddPublishDeskVO.ShopCount[]>(
'/channel/pdd/goods/publish-desk/drafts/shop-counts',
);
}
export async function getPddPublishDeskDraftApi(id: number) {
return requestClient.get<PddPublishDeskVO.Draft>(
`/channel/pdd/goods/publish-desk/drafts/${id}`,
);
}
export async function createPddPublishDeskDraftApi(
data: PddPublishDeskDTO.DraftSave,
) {
return requestClient.post<PddPublishDeskVO.Draft>(
'/channel/pdd/goods/publish-desk/drafts',
data,
);
}
export async function updatePddPublishDeskDraftApi(
id: number,
data: PddPublishDeskDTO.DraftSave,
) {
return requestClient.put<PddPublishDeskVO.Draft>(
`/channel/pdd/goods/publish-desk/drafts/${id}`,
data,
);
}
export async function deletePddPublishDeskDraftApi(id: number) {
return requestClient.delete(`/channel/pdd/goods/publish-desk/drafts/${id}`);
}
export async function clonePddPublishDeskDraftApi(
data: PddPublishDeskDTO.Clone,
) {
return requestClient.post<PddPublishDeskVO.Draft[]>(
'/channel/pdd/goods/publish-desk/drafts/clone',
data,
);
}
export async function createPddPublishDeskJobApi(
data: PddPublishDeskDTO.JobCreate,
) {
return requestClient.post<PddPublishDeskVO.Job>(
'/channel/pdd/goods/publish-desk/jobs',
data,
);
}
export async function getPddPublishDeskJobApi(id: number) {
return requestClient.get<PddPublishDeskVO.Job>(
`/channel/pdd/goods/publish-desk/jobs/${id}`,
);
}
export async function retryPddPublishDeskJobFailedApi(id: number) {
return requestClient.post<PddPublishDeskVO.Job>(
`/channel/pdd/goods/publish-desk/jobs/${id}/retry-failed`,
);
}
@@ -1,4 +1,5 @@
export * from './publish';
export * from './publish-desk';
export namespace PddGoodsDTO {
export interface Filters {
@@ -0,0 +1,93 @@
/** 拼多多发布工作台类型 */
export namespace PddPublishDeskDTO {
export interface DraftFilters {
/** <=0 表示未分配店铺 */
pddShopId?: number;
status?: string;
keyword?: string;
}
export interface DraftSave {
pddShopId?: number;
title: string;
catId?: number;
skuCount?: number;
status?: string;
payloadJson?: string;
}
export interface CloneTarget {
pddShopId: number;
count: number;
}
export interface Clone {
sourceDraftId: number;
targets: CloneTarget[];
}
export interface JobCreate {
draftIds: number[];
}
}
export namespace PddPublishDeskVO {
export interface ShopCount {
pddShopId?: number | null;
draftCount: number;
}
export interface Draft {
id: number;
companyId?: number;
pddShopId?: number;
shopName?: string;
title: string;
catId?: number;
skuCount?: number;
status: string;
payloadJson?: string;
sourceDraftId?: number;
lastError?: string;
createdBy?: number;
createTime?: string;
updateTime?: string;
}
export interface DraftPage {
total: number;
page: number;
pageSize: number;
records: Draft[];
shopCounts: ShopCount[];
shopWithDraftCount?: number;
totalPendingCount?: number;
}
export interface JobItem {
id: number;
jobId: number;
draftId: number;
pddShopId?: number;
shopName?: string;
title: string;
status: string;
goodsId?: string;
errorMessage?: string;
updateTime?: string;
}
export interface Job {
id: number;
companyId?: number;
status: string;
totalCount: number;
successCount: number;
failCount: number;
message?: string;
startedAt?: string;
finishedAt?: string;
createTime?: string;
items?: JobItem[];
}
}
@@ -0,0 +1,20 @@
import type { RouteRecordRaw } from 'vue-router';
/**
* 发布草稿编辑页:静态注册,避免挂在工作台菜单子级导致无 router-view 跳转无效。
* 菜单里仍保留 embedded 项以绑定权限;路由以本静态路由为准。
*/
const staticRoutes: RouteRecordRaw[] = [
{
name: 'PddGoodsPublishDeskEdit',
path: '/pdd/goods/publish/edit/:draftId',
component: () => import('#/views/channel/pdd/goods/publish/edit.vue'),
meta: {
title: '编辑发布草稿',
hideInMenu: true,
ignoreAccess: true,
},
},
];
export default staticRoutes;
@@ -87,18 +87,18 @@ async function uploadFileToOssWithHeaderSignature(
}
}
/** multipart:经后端落盘/对象存储 */
/** multipart:经后端落盘/对象存储(支持多文件一次提交) */
async function uploadViaMultipart(
file: File,
files: File[],
options?: UploadOptions,
): Promise<FileVO.Info> {
): Promise<FileVO.Info[]> {
if (files.length === 0) return [];
const category = resolveCategory(options?.category);
const uploaded = await batchUploadFilesApi([file], category);
const first = uploaded[0];
if (!first) {
const uploaded = await batchUploadFilesApi(files, category);
if (!uploaded?.length || uploaded.length !== files.length) {
throw new Error('文件上传失败');
}
return {
return uploaded.map((first) => ({
id: first.id,
storageType: first.storageType,
storagePath: first.storagePath,
@@ -113,63 +113,98 @@ async function uploadViaMultipart(
accessUrl: first.accessUrl,
uploadTime: '',
updateTime: '',
};
}));
}
/** direct:签名直传 OSS 后入库 */
/**
* direct:一次 batch-sign-url → 直传 OSS → 一次 batch-create-oss
*(避免每张图各打一次签名接口)
*/
async function uploadViaDirect(
file: File,
files: File[],
options?: UploadOptions,
): Promise<FileVO.Info> {
): Promise<FileVO.Info[]> {
if (files.length === 0) return [];
const category = resolveCategory(options?.category);
const fileHash = await calculateFileHash(file);
const hashes = await Promise.all(files.map((f) => calculateFileHash(f)));
const signResponse = await batchSignUrlApi({
files: [{ filename: file.name, fileHash, category }],
files: files.map((file, i) => ({
filename: file.name,
fileHash: hashes[i]!,
category,
})),
});
const signInfo = signResponse.files?.[0];
if (!signInfo) {
throw new Error('获取签名失败');
const signInfos = signResponse.files ?? [];
if (signInfos.length !== files.length) {
throw new Error('获取签名失败:返回数量与请求不一致');
}
if (signInfo.exists && signInfo.fileInfo) {
return signInfo.fileInfo;
const results: (FileVO.Info | undefined)[] = Array.from({
length: files.length,
});
const toCreate: {
index: number;
file: File;
fileHash: string;
storagePath: string;
}[] = [];
for (let i = 0; i < files.length; i++) {
const file = files[i]!;
const signInfo = signInfos[i]!;
if (signInfo.exists && signInfo.fileInfo) {
results[i] = signInfo.fileInfo;
continue;
}
if (!signInfo.uploadUrl) {
throw new Error(`未获取到上传URL:${file.name}`);
}
if (!signInfo.uploadHeaders) {
throw new Error(`未获取到上传Header签名信息:${file.name}`);
}
if (!signInfo.storagePath) {
throw new Error(`未获取到存储路径:${file.name}`);
}
await uploadFileToOssWithHeaderSignature(
file,
signInfo.uploadUrl,
signInfo.uploadHeaders,
);
toCreate.push({
index: i,
file,
fileHash: hashes[i]!,
storagePath: signInfo.storagePath,
});
}
if (!signInfo.uploadUrl) {
throw new Error('未获取到上传URL');
}
if (!signInfo.uploadHeaders) {
throw new Error('未获取到上传Header签名信息');
}
if (!signInfo.storagePath) {
throw new Error('未获取到存储路径');
}
await uploadFileToOssWithHeaderSignature(
file,
signInfo.uploadUrl,
signInfo.uploadHeaders,
);
const createResponse = await batchCreateOssFilesApi({
files: [
{
if (toCreate.length > 0) {
const createResponse = await batchCreateOssFilesApi({
files: toCreate.map(({ file, fileHash, storagePath }) => ({
filename: file.name,
fileHash,
storagePath: signInfo.storagePath,
storagePath,
fileSize: file.size,
mimeType: file.type,
category,
},
],
});
const fileInfo = createResponse?.[0];
if (!fileInfo) {
throw new Error('创建文件记录失败');
})),
});
if (!createResponse?.length || createResponse.length !== toCreate.length) {
throw new Error('创建文件记录失败');
}
for (let j = 0; j < toCreate.length; j++) {
results[toCreate[j]!.index] = createResponse[j];
}
}
return fileInfo;
return results.map((info, i) => {
if (!info) {
throw new Error(`文件上传失败:${files[i]?.name || i}`);
}
return info;
});
}
/**
@@ -179,14 +214,29 @@ export async function uploadFile(
file: File,
options?: UploadOptions,
): Promise<FileVO.Info> {
const [info] = await uploadFiles([file], options);
if (!info) {
throw new Error(options?.errorMessage || '文件上传失败');
}
return info;
}
/**
* 批量上传:direct 模式合并为一次签名 + 一次入库;multipart 一次 batch-upload
*/
export async function uploadFiles(
files: File[],
options?: UploadOptions,
): Promise<FileVO.Info[]> {
if (files.length === 0) return [];
try {
const appConfig = useAppConfigStore();
await appConfig.ensureLoaded();
if (appConfig.isDirectUpload) {
return await uploadViaDirect(file, options);
return await uploadViaDirect(files, options);
}
return await uploadViaMultipart(file, options);
return await uploadViaMultipart(files, options);
} catch (error) {
console.error('文件上传失败:', error);
message.error(options?.errorMessage || '文件上传失败');
@@ -194,20 +244,6 @@ export async function uploadFile(
}
}
/**
* 批量上传(当前按文件串行,保持与单文件同一分流逻辑)
*/
export async function uploadFiles(
files: File[],
options?: UploadOptions,
): Promise<FileVO.Info[]> {
const results: FileVO.Info[] = [];
for (const file of files) {
results.push(await uploadFile(file, options));
}
return results;
}
/** @deprecated 使用 uploadFile */
export const uploadFileToOss = uploadFile;
/** @deprecated 使用 uploadFiles */
@@ -23,6 +23,11 @@ withDefaults(
resizable?: boolean;
splitHandle?: boolean;
splitLine?: boolean;
/** 店铺待发草稿数 */
draftCountByShopId?: Record<number, number>;
showUnassignedFilter?: boolean;
unassignedCount?: number;
unassignedSelected?: boolean;
}>(),
{
showAddAction: false,
@@ -34,12 +39,17 @@ withDefaults(
resizable: true,
splitHandle: false,
splitLine: false,
draftCountByShopId: undefined,
showUnassignedFilter: false,
unassignedCount: 0,
unassignedSelected: false,
},
);
const emit = defineEmits<{
'update:selectedShopId': [id: number | undefined];
select: [shop: PddShopVO.Info | null];
selectUnassigned: [];
addForShop: [shopId: number];
}>();
@@ -78,10 +88,15 @@ const { width: leftWidth, collapsed: leftCollapsed } =
show-collapse-action
:selected-shop-id="selectedShopId"
:show-add-action="showAddAction"
:draft-count-by-shop-id="draftCountByShopId"
:show-unassigned-filter="showUnassignedFilter"
:unassigned-count="unassignedCount"
:unassigned-selected="unassignedSelected"
@collapse="collapse"
@expand="expand"
@update:selected-shop-id="emit('update:selectedShopId', $event)"
@select="emit('select', $event)"
@select-unassigned="emit('selectUnassigned')"
@add-for-shop="emit('addForShop', $event)"
/>
</div>
@@ -6,6 +6,7 @@ import { computed, onMounted, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
Badge,
Button,
Card,
Empty,
@@ -28,6 +29,14 @@ const props = withDefaults(
fluid?: boolean;
showCollapseAction?: boolean;
collapsed?: boolean;
/** 店铺待发草稿数(发布工作台左栏徽章) */
draftCountByShopId?: Record<number, number>;
/** 是否展示「未分配」筛选项(发布工作台) */
showUnassignedFilter?: boolean;
/** 未分配草稿数 */
unassignedCount?: number;
/** 当前是否选中「未分配」(与 selectedShopId 互斥) */
unassignedSelected?: boolean;
}>(),
{
selectedShopId: undefined,
@@ -35,18 +44,25 @@ const props = withDefaults(
fluid: false,
showCollapseAction: false,
collapsed: false,
draftCountByShopId: undefined,
showUnassignedFilter: false,
unassignedCount: 0,
unassignedSelected: false,
},
);
const emit = defineEmits<{
'update:selectedShopId': [id: number | undefined];
select: [shop: PddShopVO.Info | null];
/** 选中未分配(无店铺)草稿 */
selectUnassigned: [];
addForShop: [shopId: number];
collapse: [];
expand: [];
}>();
const StoreIcon = createIconifyIcon('lucide:store');
const InboxIcon = createIconifyIcon('lucide:inbox');
const PlusIcon = createIconifyIcon('lucide:plus');
const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
const PanelOpenIcon = createIconifyIcon('lucide:panel-left-open');
@@ -63,7 +79,10 @@ const shopTotalPages = computed(() => {
return Math.max(1, Math.ceil(total / pageSize) || 1);
});
const allSelected = computed(() => props.selectedShopId === undefined);
/** 全部:未选具体店且未选「未分配」 */
const allSelected = computed(
() => props.selectedShopId === undefined && !props.unassignedSelected,
);
function shopLabel(shop: PddShopVO.Info) {
return shop.mallName || `店铺 #${shop.id}`;
@@ -109,6 +128,10 @@ function selectAll() {
emit('select', null);
}
function selectUnassigned() {
emit('selectUnassigned');
}
function selectShop(shop: PddShopVO.Info) {
emit('update:selectedShopId', shop.id);
emit('select', shop);
@@ -161,6 +184,31 @@ onMounted(() => {
</button>
</Tooltip>
<Tooltip v-if="showUnassignedFilter" title="未分配店铺">
<Badge
:count="unassignedCount || 0"
:number-style="{ backgroundColor: '#999', fontSize: '10px' }"
:offset="[-2, 2]"
>
<button
type="button"
class="inline-flex shrink-0 rounded-md p-0.5 transition-colors hover:bg-accent"
:class="
unassignedSelected
? 'ring-2 ring-primary ring-offset-1 ring-offset-background'
: undefined
"
@click="selectUnassigned"
>
<div
class="flex h-9 w-9 items-center justify-center rounded-md border border-dashed border-border bg-muted/50"
>
<InboxIcon class="h-4 w-4 text-muted-foreground" />
</div>
</button>
</Badge>
</Tooltip>
<Spin
:spinning="shopsLoading"
size="small"
@@ -285,6 +333,44 @@ onMounted(() => {
</div>
</Card>
<Card
v-if="showUnassignedFilter"
size="small"
:body-style="{ padding: '10px 12px' }"
class="mb-2 cursor-pointer !shadow-none hover:border-primary"
:class="
unassignedSelected ? 'border-primary bg-primary/5' : undefined
"
@click="selectUnassigned"
>
<div class="flex items-center gap-2">
<div
class="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-dashed border-border bg-muted/50"
>
<InboxIcon class="h-4 w-4 text-muted-foreground" />
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-2">
<span class="min-w-0 truncate text-sm font-medium">未分配</span>
<Badge
v-if="(unassignedCount || 0) > 0"
:count="unassignedCount"
:number-style="{
backgroundColor: '#999',
fontSize: '10px',
}"
/>
<span
v-else
class="shrink-0 text-xs text-muted-foreground"
>
无店铺
</span>
</div>
</div>
</div>
</Card>
<Spin :spinning="shopsLoading">
<Empty
v-if="!shopsLoading && shops.length === 0"
@@ -313,8 +399,19 @@ onMounted(() => {
/>
<div class="flex min-w-0 flex-1 items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium">
{{ shopLabel(shop) }}
<div class="flex items-center gap-1 truncate text-sm font-medium">
<span class="min-w-0 truncate">{{ shopLabel(shop) }}</span>
<Badge
v-if="
draftCountByShopId &&
(draftCountByShopId[shop.id] || 0) > 0
"
:count="draftCountByShopId[shop.id]"
:number-style="{
backgroundColor: '#1677ff',
fontSize: '10px',
}"
/>
</div>
<div
v-if="shop.mallId != null"
@@ -306,8 +306,11 @@ onMounted(async () => {
<div class="flex items-center justify-between gap-2">
<span class="text-base font-semibold">拼多多商品</span>
<PermissionGate code="channel:pdd:goods:create">
<Button type="primary" @click="publishOpen = true">
{{ publishHasDraft ? '继续发布' : '发布商品' }}
<Button type="primary" @click="$router.push('/pdd/goods/publish')">
发布工作台
</Button>
<Button class="ml-2" @click="publishOpen = true">
{{ publishHasDraft ? '继续弹窗发布' : '弹窗发布' }}
</Button>
</PermissionGate>
</div>
@@ -0,0 +1,61 @@
<script lang="ts" setup>
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import PddGoodsPublishEditor from '../components/PddGoodsPublishEditor.vue';
defineOptions({ name: 'PddGoodsPublishDeskEdit' });
const route = useRoute();
const router = useRouter();
const draftId = computed(() => {
const raw = route.params.draftId;
const n = Number(Array.isArray(raw) ? raw[0] : raw);
return Number.isFinite(n) ? n : null;
});
function goBack() {
void router.push('/pdd/goods/publish');
}
</script>
<template>
<!-- 不用 auto-content-height:标题区含店铺/类目后高度动态变化,改用 flex 占满 -->
<Page
class="flex min-h-0 flex-col"
:style="{ height: 'var(--vben-content-height)' }"
header-class="!items-start"
content-padding-class="p-0"
content-class="flex min-h-0 flex-1 flex-col overflow-hidden !h-auto !p-0"
>
<template #title>
<div class="w-full space-y-3">
<div class="mb-0 flex items-baseline text-lg font-semibold">
编辑发布草稿
<span
v-if="draftId"
class="text-muted-foreground ml-2 text-sm font-normal"
>
#{{ draftId }}
</span>
</div>
<!-- Editor 页面态 Teleport:店铺 / 类目 -->
<div id="pdd-publish-edit-header-fields" class="w-full min-w-0"></div>
</div>
</template>
<PddGoodsPublishEditor
v-if="draftId"
class="h-full min-h-0"
variant="page"
:open="true"
:draft-id="draftId"
@close="goBack"
@success="goBack"
@draft-saved="() => undefined"
/>
</Page>
</template>
@@ -0,0 +1,551 @@
<script lang="ts" setup>
import type { PddPublishDeskVO } from '#/api/channel/pdd/goods';
import type { PddShopVO } from '#/api/channel/pdd/shop';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
Badge,
Button,
Card,
Checkbox,
Empty,
InputNumber,
Modal,
Space,
Table,
Tag,
message,
} from 'ant-design-vue';
import {
clonePddPublishDeskDraftApi,
createPddPublishDeskDraftApi,
createPddPublishDeskJobApi,
deletePddPublishDeskDraftApi,
getPddPublishDeskJobApi,
listPddPublishDeskDraftsApi,
retryPddPublishDeskJobFailedApi,
} from '#/api/channel/pdd/goods';
import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import { PermissionGate } from '#/components/permission';
import PddShopColPage from '#/views/channel/pdd/components/PddShopColPage.vue';
defineOptions({ name: 'PddGoodsPublishDesk' });
const router = useRouter();
const loading = ref(false);
const selectedShopId = ref<number | undefined>(undefined);
/** 左栏「未分配」 */
const filterUnassigned = ref(false);
const drafts = ref<PddPublishDeskVO.Draft[]>([]);
const shopCounts = ref<PddPublishDeskVO.ShopCount[]>([]);
const totalPending = ref(0);
const shopWithDraft = ref(0);
const selectedRowKeys = ref<number[]>([]);
const shops = ref<PddShopVO.Info[]>([]);
const cloneOpen = ref(false);
const cloneSourceId = ref<number | undefined>();
const cloneTargets = ref<{ pddShopId: number; count: number; checked: boolean }[]>(
[],
);
const cloneSubmitting = ref(false);
const jobOpen = ref(false);
const jobLoading = ref(false);
const currentJob = ref<PddPublishDeskVO.Job | null>(null);
let jobPollTimer: ReturnType<typeof setInterval> | undefined;
const statusLabel: Record<string, { text: string; color: string }> = {
EDITING: { text: '编辑中', color: 'default' },
NEED_CHECK: { text: '待校验', color: 'orange' },
READY: { text: '可发布', color: 'blue' },
PUBLISHING: { text: '发布中', color: 'processing' },
FAILED: { text: '失败', color: 'error' },
PUBLISHED: { text: '已发布', color: 'success' },
};
const countByShopId = computed(() => {
const map = new Map<number | 'unassigned', number>();
for (const c of shopCounts.value) {
if (c.pddShopId == null) {
map.set('unassigned', Number(c.draftCount || 0));
} else {
map.set(c.pddShopId, Number(c.draftCount || 0));
}
}
return map;
});
const draftCountRecord = computed(() => {
const rec: Record<number, number> = {};
for (const [k, v] of countByShopId.value) {
if (typeof k === 'number') rec[k] = v;
}
return rec;
});
const summaryText = computed(
() =>
`${shopWithDraft.value || 0} 店 · ${totalPending.value || 0} 待发`,
);
const columns = [
{ type: 'selection', width: 48 },
{ title: '标题', dataIndex: 'title', key: 'title', ellipsis: true },
{ title: '店铺', dataIndex: 'shopName', key: 'shopName', width: 140 },
{ title: 'SKU数', dataIndex: 'skuCount', key: 'skuCount', width: 80 },
{ title: '状态', key: 'status', width: 100 },
{ title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', width: 170 },
{ title: '操作', key: 'actions', width: 200 },
];
async function loadShops() {
try {
const data = await getPddShopPageApi({
page: 1,
pageSize: 500,
filters: {},
});
shops.value = data.records ?? [];
} catch {
message.error('加载店铺失败');
}
}
async function loadDrafts() {
loading.value = true;
try {
const filters: {
pddShopId?: number;
} = {};
if (filterUnassigned.value) {
filters.pddShopId = 0;
} else if (selectedShopId.value != null) {
filters.pddShopId = selectedShopId.value;
}
const page = await listPddPublishDeskDraftsApi({
page: 1,
pageSize: 200,
filters,
});
drafts.value = page.records ?? [];
shopCounts.value = page.shopCounts ?? [];
totalPending.value = page.totalPendingCount ?? 0;
shopWithDraft.value = page.shopWithDraftCount ?? 0;
selectedRowKeys.value = [];
} catch (e: any) {
message.error(e?.message || '加载草稿失败');
} finally {
loading.value = false;
}
}
function onShopSelect(shop: PddShopVO.Info | null) {
filterUnassigned.value = false;
selectedShopId.value = shop?.id;
void loadDrafts();
}
function selectUnassigned() {
filterUnassigned.value = true;
selectedShopId.value = undefined;
void loadDrafts();
}
async function createDraft() {
try {
const draft = await createPddPublishDeskDraftApi({
title: '未命名草稿',
pddShopId: selectedShopId.value,
status: 'EDITING',
skuCount: 0,
});
message.success('已创建草稿');
await router.push(`/pdd/goods/publish/edit/${draft.id}`);
} catch (e: any) {
message.error(e?.message || '创建失败');
}
}
function openEdit(id: number) {
void router.push(`/pdd/goods/publish/edit/${id}`).catch((err) => {
console.error(err);
message.error('无法打开编辑页,请刷新后再试');
});
}
async function removeDraft(id: number) {
Modal.confirm({
title: '删除草稿?',
content: '删除后不可恢复',
okType: 'danger',
async onOk() {
await deletePddPublishDeskDraftApi(id);
message.success('已删除');
await loadDrafts();
},
});
}
function openClone(draftId: number) {
cloneSourceId.value = draftId;
cloneTargets.value = shops.value.map((s) => ({
pddShopId: s.id,
count: 1,
checked: selectedShopId.value === s.id,
}));
if (!cloneTargets.value.some((t) => t.checked) && cloneTargets.value[0]) {
cloneTargets.value[0]!.checked = true;
}
cloneOpen.value = true;
}
const clonePreview = computed(() =>
cloneTargets.value
.filter((t) => t.checked)
.map((t) => {
const shop = shops.value.find((s) => s.id === t.pddShopId);
return `${shop?.mallName || t.pddShopId}+${t.count}`;
})
.join('、'),
);
async function submitClone() {
if (cloneSourceId.value == null) return;
const targets = cloneTargets.value
.filter((t) => t.checked)
.map((t) => ({ pddShopId: t.pddShopId, count: t.count || 1 }));
if (targets.length === 0) {
message.warning('请至少勾选一个目标店铺');
return;
}
cloneSubmitting.value = true;
try {
const created = await clonePddPublishDeskDraftApi({
sourceDraftId: cloneSourceId.value,
targets,
});
message.success(`已克隆 ${created.length} 条草稿`);
cloneOpen.value = false;
await loadDrafts();
} catch (e: any) {
message.error(e?.message || '克隆失败');
} finally {
cloneSubmitting.value = false;
}
}
async function batchPublish() {
if (selectedRowKeys.value.length === 0) {
message.warning('请先勾选草稿');
return;
}
try {
const job = await createPddPublishDeskJobApi({
draftIds: selectedRowKeys.value,
});
currentJob.value = job;
jobOpen.value = true;
startJobPoll(job.id);
await loadDrafts();
} catch (e: any) {
message.error(e?.message || '创建发布任务失败');
}
}
/** 表格多选:在 script 中写 ref,避免模板自动解包后误用 .value */
function onDraftSelectionChange(keys: (string | number)[]) {
selectedRowKeys.value = keys.map(Number);
}
function startJobPoll(jobId: number) {
stopJobPoll();
jobPollTimer = setInterval(() => {
void refreshJob(jobId);
}, 2000);
void refreshJob(jobId);
}
function stopJobPoll() {
if (jobPollTimer) {
clearInterval(jobPollTimer);
jobPollTimer = undefined;
}
}
async function refreshJob(jobId: number) {
jobLoading.value = true;
try {
const job = await getPddPublishDeskJobApi(jobId);
currentJob.value = job;
if (
job.status === 'SUCCESS' ||
job.status === 'PARTIAL' ||
job.status === 'FAILED'
) {
stopJobPoll();
void loadDrafts();
}
} catch {
stopJobPoll();
} finally {
jobLoading.value = false;
}
}
async function retryFailed() {
if (!currentJob.value) return;
try {
const job = await retryPddPublishDeskJobFailedApi(currentJob.value.id);
currentJob.value = job;
startJobPoll(job.id);
} catch (e: any) {
message.error(e?.message || '重试失败');
}
}
watch(selectedShopId, () => {
// load via onShopSelect
});
onMounted(async () => {
await loadShops();
await loadDrafts();
});
onUnmounted(() => stopJobPoll());
</script>
<template>
<PddShopColPage
:selected-shop-id="selectedShopId"
:draft-count-by-shop-id="draftCountRecord"
show-unassigned-filter
:unassigned-count="countByShopId.get('unassigned') || 0"
:unassigned-selected="filterUnassigned"
@select="onShopSelect"
@select-unassigned="selectUnassigned"
>
<Card
class="publish-desk-card ml-1 flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden sm:ml-2"
:body-style="{
flex: 1,
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
}"
>
<template #title>
<div class="flex min-w-0 items-center gap-3">
<span class="text-base font-semibold">发布工作台</span>
<span class="text-muted-foreground truncate text-sm font-normal">
{{ summaryText }}
</span>
</div>
</template>
<template #extra>
<Space wrap class="py-1">
<PermissionGate code="channel:pdd:goods:create">
<Button type="primary" @click="createDraft">新建草稿</Button>
</PermissionGate>
<PermissionGate code="channel:pdd:goods:create">
<Button
:disabled="selectedRowKeys.length === 0"
@click="batchPublish"
>
批量发布选中
</Button>
</PermissionGate>
<Button @click="loadDrafts">刷新</Button>
</Space>
</template>
<div class="min-h-0 flex-1 overflow-auto px-2 pb-2 pt-2 sm:px-3">
<div
v-if="filterUnassigned"
class="text-muted-foreground mb-2 text-xs"
>
当前筛选:未分配店铺的草稿(点左侧「全部店铺」可查看全部)
</div>
<div
v-else-if="selectedShopId"
class="text-muted-foreground mb-2 text-xs"
>
当前店待发
<Badge
:count="countByShopId.get(selectedShopId) || 0"
:number-style="{ backgroundColor: '#1677ff' }"
/>
</div>
<Table
:loading="loading"
:columns="columns as any"
:data-source="drafts"
row-key="id"
:pagination="false"
:row-selection="{
selectedRowKeys,
onChange: onDraftSelectionChange,
}"
:locale="{ emptyText: '暂无待发草稿' }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'status'">
<Tag :color="statusLabel[record.status]?.color || 'default'">
{{ statusLabel[record.status]?.text || record.status }}
</Tag>
<div
v-if="record.lastError"
class="mt-1 max-w-[160px] truncate text-xs text-red-500"
:title="record.lastError"
>
{{ record.lastError }}
</div>
</template>
<template v-else-if="column.key === 'actions'">
<Space>
<Button type="link" size="small" @click="openEdit(record.id)">
编辑
</Button>
<Button
type="link"
size="small"
@click="openClone(record.id)"
>
克隆
</Button>
<Button
type="link"
size="small"
danger
@click="removeDraft(record.id)"
>
删除
</Button>
</Space>
</template>
</template>
</Table>
<Empty
v-if="!loading && drafts.length === 0"
class="mt-8"
description="暂无草稿,点击「新建草稿」开始"
/>
</div>
</Card>
<Modal
v-model:open="cloneOpen"
title="一键克隆"
:confirm-loading="cloneSubmitting"
ok-text="确认克隆"
destroy-on-close
@ok="submitClone"
>
<p class="mb-3 text-sm text-muted-foreground">
将选中母版复制到目标店(跨店标为「待校验」)。预览:
<span class="text-foreground">{{ clonePreview || '无' }}</span>
</p>
<div class="max-h-72 space-y-2 overflow-y-auto">
<div
v-for="t in cloneTargets"
:key="t.pddShopId"
class="flex items-center gap-3 rounded border border-border/60 px-2 py-1.5"
>
<Checkbox v-model:checked="t.checked" />
<span class="min-w-0 flex-1 truncate">
{{
shops.find((s) => s.id === t.pddShopId)?.mallName || t.pddShopId
}}
<Badge
class="ml-1"
:count="countByShopId.get(t.pddShopId) || 0"
:number-style="{ backgroundColor: '#1677ff' }"
/>
</span>
<span class="text-xs text-muted-foreground">份数</span>
<InputNumber
v-model:value="t.count"
:min="1"
:max="20"
class="w-20"
/>
</div>
</div>
</Modal>
<Modal
v-model:open="jobOpen"
title="批量发布进度"
:footer="null"
width="720px"
destroy-on-close
@cancel="stopJobPoll"
>
<div v-if="currentJob" class="space-y-3">
<div class="flex flex-wrap items-center gap-2 text-sm">
<Tag>{{ currentJob.status }}</Tag>
<span>
成功 {{ currentJob.successCount }} / 失败
{{ currentJob.failCount }} / 合计 {{ currentJob.totalCount }}
</span>
<Button
v-if="currentJob.failCount > 0"
size="small"
@click="retryFailed"
>
重试失败项
</Button>
<Button
size="small"
:loading="jobLoading"
@click="refreshJob(currentJob.id)"
>
刷新
</Button>
</div>
<Table
size="small"
:pagination="false"
:data-source="currentJob.items || []"
row-key="id"
:columns="[
{ title: '店铺', dataIndex: 'shopName', width: 140 },
{ title: '标题', dataIndex: 'title', ellipsis: true },
{ title: '状态', dataIndex: 'status', width: 100 },
{ title: 'goodsId', dataIndex: 'goodsId', width: 120 },
{ title: '错误', dataIndex: 'errorMessage', ellipsis: true },
]"
/>
</div>
</Modal>
</PddShopColPage>
</template>
<style scoped>
/* Card 标题区默认 overflow:hidden + nowrap,会裁切带 Badge 的操作按钮 */
.publish-desk-card :deep(.ant-card-head) {
flex-shrink: 0;
height: auto;
min-height: 48px;
overflow: visible;
}
.publish-desk-card :deep(.ant-card-head-wrapper) {
flex-wrap: wrap;
gap: 8px;
overflow: visible;
}
.publish-desk-card :deep(.ant-card-head-title),
.publish-desk-card :deep(.ant-card-extra) {
overflow: visible;
white-space: normal;
padding-top: 12px;
padding-bottom: 12px;
}
</style>