feat: 完善成本同步

This commit is contained in:
2026-08-29 17:04:14 +08:00
parent f42e6aeb44
commit 7fcb9abf69
36 changed files with 1644 additions and 513 deletions
@@ -1,471 +1,138 @@
<script lang="ts" setup>
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
import type { CostSyncVO } from '#/api/ec/cost-sync';
import { onUnmounted, ref, watch } from 'vue';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DatePicker, message } from 'ant-design-vue';
import { Alert, Button, Table, message } from 'ant-design-vue';
import {
batchSyncCostsToOrdersApi,
countOrdersForCostSyncApi,
} from '#/api/ec/product/sku/cost';
import { getProductSkusByIdsApi } from '#/api/ec/product/sku/apis';
applyPendingCostImpactsApi,
listPendingCostImpactsApi,
} from '#/api/ec/cost-sync';
defineOptions({ name: 'ProductCostSyncToOrdersModal' });
type ProductCostSyncModalEntry = 'after-save' | 'manual';
interface ProductCostSyncOpenOptions {
/** 保存后提示 / 用户主动同步 */
entry?: ProductCostSyncModalEntry;
/** 打开时预填日期范围 `YYYY-MM-DD`;不传则清空由用户选择 */
initialDateRange?: [string, string];
}
/** 将选中的日期范围转为接口所需 LocalDateTime 字符串(起日 00:00:00,止日 23:59:59) */
function dateRangeToApiTimes(range: [string, string]): {
endTime: string;
startTime: string;
} {
const [startDate, endDate] = range;
return {
startTime: `${startDate} 00:00:00`,
endTime: `${endDate} 23:59:59`,
};
}
const [SyncModal, syncModalApi] = useVbenModal({
title: '成本变更同步确认',
class: 'w-[720px] max-w-[calc(100vw-2rem)]',
title: '成本待同步',
class: 'w-[800px] max-w-[calc(100vw-2rem)]',
draggable: true,
contentClass: 'px-5 py-4 min-h-[480px]',
cancelText: '暂不同步',
confirmText: '立即同步',
onConfirm: handleSyncConfirm,
onCancel: () => {
syncModalApi.close();
},
contentClass: 'px-5 py-4 min-h-[360px]',
showCancelButton: true,
cancelText: '关闭',
showConfirmButton: false,
});
const syncFormData = ref<[string, string] | undefined>(undefined);
const pendingCostChangedSkus = ref<ProductSkuVO.Info[]>([]);
const selectedSyncSkuIds = ref<number[]>([]);
const costSyncModalEntry = ref<ProductCostSyncModalEntry>('after-save');
const loading = ref(false);
const applying = ref(false);
const pending = ref<CostSyncVO.Impact[]>([]);
const lastResult = ref<CostSyncVO.ApplyResult | null>(null);
const costSyncOrderCount = ref<null | number>(null);
const costSyncOrderCountLoading = ref(false);
let costSyncCountTimer: null | ReturnType<typeof setTimeout> = null;
const columns = [
{ title: 'SKU ID', dataIndex: 'skuId', key: 'skuId', width: 100 },
{ title: '商品 ID', dataIndex: 'productId', key: 'productId', width: 100 },
{
title: '影响区间',
key: 'range',
customRender: ({ record }: { record: CostSyncVO.Impact }) =>
`${record.dateFrom} ~ ${record.dateTo}`,
},
{
title: '成本快照',
key: 'cost',
customRender: ({ record }: { record: CostSyncVO.Impact }) =>
`¥${Number(record.lastProductCost ?? 0).toFixed(2)} / ¥${Number(record.lastShippingCost ?? 0).toFixed(2)} / ¥${Number(record.lastOtherCost ?? 0).toFixed(2)}`,
},
];
function scheduleFetchCostSyncOrderCount() {
if (costSyncCountTimer) {
clearTimeout(costSyncCountTimer);
}
costSyncCountTimer = setTimeout(() => {
costSyncCountTimer = null;
void fetchCostSyncOrderCount();
}, 300);
}
async function fetchCostSyncOrderCount() {
const range = syncFormData.value;
if (!range?.[0] || !range[1]) {
costSyncOrderCount.value = null;
return;
}
if (selectedSyncSkuIds.value.length === 0) {
costSyncOrderCount.value = null;
return;
}
costSyncOrderCountLoading.value = true;
async function reload() {
loading.value = true;
lastResult.value = null;
try {
const { startTime, endTime } = dateRangeToApiTimes(range);
costSyncOrderCount.value = await countOrdersForCostSyncApi({
skuIds: [...selectedSyncSkuIds.value],
startTime,
endTime,
});
pending.value = (await listPendingCostImpactsApi()) ?? [];
} catch {
costSyncOrderCount.value = null;
pending.value = [];
message.error('加载待同步影响面失败');
} finally {
costSyncOrderCountLoading.value = false;
loading.value = false;
}
}
watch(
() => [...selectedSyncSkuIds.value],
() => {
scheduleFetchCostSyncOrderCount();
},
);
watch(
syncFormData,
() => {
scheduleFetchCostSyncOrderCount();
},
{ deep: true },
);
/**
* 打开成本同步弹窗(先拉取SKU详情再展示)
* 打开账本一键回刷(skuIds 保留兼容旧调用,实际按公司全部 PENDING)。
*/
async function open(skuIds: number[], options?: ProductCostSyncOpenOptions) {
const entry = options?.entry ?? 'after-save';
costSyncModalEntry.value = entry;
syncModalApi.setState?.({
title: entry === 'manual' ? '同步成本到订单' : '成本变更同步确认',
});
try {
const skus = await getProductSkusByIdsApi(skuIds);
pendingCostChangedSkus.value = skus ?? [];
selectedSyncSkuIds.value = [...skuIds];
syncFormData.value = options?.initialDateRange
? [options.initialDateRange[0], options.initialDateRange[1]]
: undefined;
costSyncOrderCount.value = null;
syncModalApi.open();
if (options?.initialDateRange) {
scheduleFetchCostSyncOrderCount();
}
} catch (error) {
console.error('获取SKU详情失败:', error);
message.error('获取SKU详情失败,无法进行成本同步');
}
async function open(_skuIds?: number[], _options?: { entry?: string }) {
syncModalApi.open();
await reload();
}
function toggleSku(skuId: number) {
const idx = selectedSyncSkuIds.value.indexOf(skuId);
if (idx === -1) {
selectedSyncSkuIds.value.push(skuId);
} else {
selectedSyncSkuIds.value.splice(idx, 1);
}
}
async function handleSyncConfirm() {
if (selectedSyncSkuIds.value.length === 0) {
message.warning('请至少选择一个SKU');
return;
}
const range = syncFormData.value;
if (!range?.[0] || !range[1]) {
message.warning('请选择同步日期范围');
async function handleApply() {
if (pending.value.length === 0) {
message.info('没有待同步的影响面');
return;
}
applying.value = true;
try {
syncModalApi.setState?.({ confirmLoading: true });
const { startTime, endTime } = dateRangeToApiTimes(range);
const totalUpdated = await batchSyncCostsToOrdersApi({
skuIds: selectedSyncSkuIds.value,
startTime,
endTime,
});
message.success(`成本同步完成,共更新 ${totalUpdated ?? 0} 条订单`);
syncModalApi.close?.();
} catch (error) {
console.error('成本同步失败:', error);
message.error('成本同步失败');
const result = await applyPendingCostImpactsApi();
lastResult.value = result ?? null;
message.success(
`已创建 ${result?.taskCount ?? 0} 个店铺成本同步任务(影响面 ${result?.impactCount ?? 0} 条)`,
);
await reload();
} catch (e) {
console.error(e);
} finally {
syncModalApi.setState?.({ confirmLoading: false });
applying.value = false;
}
}
onUnmounted(() => {
if (costSyncCountTimer) {
clearTimeout(costSyncCountTimer);
costSyncCountTimer = null;
}
});
defineExpose({ open });
</script>
<template>
<SyncModal>
<div class="product-cost-sync py-4">
<div class="sync-alert">
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
<Alert
type="info"
show-icon
class="mb-4"
message="调价后会记入待同步影响面。确认不再改价后,一键按店创建成本同步任务,并预建下游 BI 全量重算(按日先改订单明细再投计算)。"
/>
<div class="mb-3 flex items-center justify-between gap-2">
<span class="text-muted-foreground text-sm">
待同步 {{ pending.length }} 条
</span>
<div class="flex gap-2">
<Button :loading="loading" @click="reload">刷新</Button>
<Button
type="primary"
:loading="applying"
:disabled="pending.length === 0"
@click="handleApply"
>
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<template v-if="costSyncModalEntry === 'after-save'">
检测到
<strong>{{ pendingCostChangedSkus.length }}</strong>
个SKU的<strong>当前生效</strong>成本已写入,请勾选需要同步到订单的SKU:
</template>
<template v-else>
将所选SKU<strong>当前生效</strong>的商品成本、运费、其他成本写入订单(会覆盖该时间范围内订单上的对应成本字段)。请勾选需要同步的SKU,共
<strong>{{ pendingCostChangedSkus.length }}</strong> 个:
</template>
</div>
<div
class="sku-list mb-4 max-h-72 min-h-[200px] overflow-y-auto rounded-lg"
>
<div
v-for="sku in pendingCostChangedSkus"
:key="sku.id"
class="sku-item-card"
:class="{ active: selectedSyncSkuIds.includes(sku.id) }"
@click="toggleSku(sku.id)"
>
<div class="checkbox-wrapper">
<div class="custom-checkbox">
<span
v-if="selectedSyncSkuIds.includes(sku.id)"
class="check-icon"
>
✓
</span>
</div>
</div>
<div class="sku-info">
<div class="sku-title">{{ sku.name }}</div>
<div class="sku-code">{{ sku.skuCode || '无编码' }}</div>
</div>
<div class="cost-snapshot">
<div class="cost-tag changed">
<span>商品成本</span>
<span>¥{{ Number(sku.productCost || 0).toFixed(2) }}</span>
</div>
<div class="cost-tag">
<span>运费</span>
<span>¥{{ Number(sku.shippingCost || 0).toFixed(2) }}</span>
</div>
<div class="cost-tag">
<span>其他</span>
<span>¥{{ Number(sku.otherCost || 0).toFixed(2) }}</span>
</div>
</div>
</div>
</div>
<div class="time-range-section">
<label class="section-label">同步日期范围</label>
<DatePicker.RangePicker
v-model:value="syncFormData"
class="w-full"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
/>
<div
class="sync-order-count mt-2 text-sm text-gray-600 dark:text-[hsl(240deg_5%_64.9%)]"
>
<template v-if="costSyncOrderCountLoading">正在统计订单数…</template>
<template
v-else-if="
costSyncOrderCount !== null &&
syncFormData &&
syncFormData[0] &&
syncFormData[1] &&
selectedSyncSkuIds.length > 0
"
>
当前日期范围内共
<strong class="text-gray-900 dark:text-[hsl(0deg_0%_95%)]">{{
costSyncOrderCount
}}</strong>
条订单将更新成本
</template>
</div>
一键同步并重算
</Button>
</div>
</div>
<Table
size="small"
row-key="id"
:loading="loading"
:columns="columns"
:data-source="pending"
:pagination="false"
/>
<div v-if="lastResult" class="text-muted-foreground mt-4 text-sm">
批次 {{ lastResult.applyBatchId }} · 任务
{{ lastResult.taskCount }} 个
<ul v-if="lastResult.tasks?.length" class="mt-1 list-disc pl-5">
<li v-for="t in lastResult.tasks" :key="t.costSyncTaskId">
店 #{{ t.shopId }} 成本任务 #{{ t.costSyncTaskId }} → BI #{{
t.biCalcTaskId ?? '-'
}}
({{ t.dateFrom }}~{{ t.dateTo }},{{ t.totalDays }} 天)
</li>
</ul>
</div>
</SyncModal>
</template>
<style scoped lang="scss">
.sync-alert {
display: flex;
align-items: center;
gap: 10px;
background: #fff8f1;
padding: 12px 16px;
border-radius: 8px;
border: 1px solid #ffe8d5;
margin-bottom: 24px;
color: #af6a2b;
font-size: 14px;
}
.sku-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.sku-item-card {
display: flex;
align-items: center;
padding: 16px;
border: 2px solid #eef0f2;
border-radius: 10px;
transition: all 0.2s;
cursor: pointer;
background: #fff;
}
.sku-item-card:hover {
border-color: #d1d9ff;
background: #fafbff;
}
.sku-item-card.active {
border-color: #5b6df5;
background: #f0f2ff;
}
.checkbox-wrapper {
margin-right: 16px;
flex-shrink: 0;
}
.custom-checkbox {
width: 20px;
height: 20px;
border: 2px solid #cbd5e1;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
transition: all 0.2s;
}
.active .custom-checkbox {
background: #5b6df5;
border-color: #5b6df5;
}
.check-icon {
color: #fff;
font-size: 14px;
font-weight: bold;
line-height: 1;
}
.sku-info {
flex: 1;
min-width: 0;
}
.sku-title {
font-size: 14px;
font-weight: 500;
color: #2d3436;
margin-bottom: 4px;
display: -webkit-box;
-webkit-line-clamp: 1;
line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
.sku-code {
font-size: 12px;
color: #636e72;
font-family: monospace;
}
.cost-snapshot {
display: flex;
flex-direction: column;
gap: 4px;
padding-left: 20px;
border-left: 1px solid #e2e8f0;
margin-left: 15px;
min-width: 100px;
}
.cost-tag {
font-size: 12px;
color: #636e72;
display: flex;
justify-content: space-between;
gap: 10px;
}
.cost-tag span:last-child {
font-weight: 600;
color: #2d3436;
}
.cost-tag.changed span:last-child {
color: #f2994a;
}
.time-range-section {
margin-top: 24px;
}
.section-label {
font-size: 14px;
font-weight: 600;
color: #2d3436;
margin-bottom: 12px;
display: block;
}
</style>
<style lang="scss">
$card-text: hsl(var(--foreground));
$muted-text: hsl(var(--muted-foreground));
$accent-bg: hsl(var(--accent));
$border-base: hsl(var(--border));
$primary: hsl(var(--primary));
html.dark .product-cost-sync {
.section-label,
.sku-code,
.cost-tag {
color: $muted-text;
}
.sync-alert {
background: hsl(var(--warning) / 12%);
border-color: hsl(var(--warning) / 35%);
color: hsl(var(--warning));
}
.sku-item-card {
border-color: $border-base;
background: hsl(var(--muted));
&:hover {
border-color: hsl(var(--primary) / 50%);
background: $accent-bg;
}
&.active {
border-color: $primary;
background: hsl(var(--primary) / 10%);
}
}
.custom-checkbox {
background: hsl(var(--muted));
border-color: $border-base;
}
.sku-title {
color: $card-text;
}
.cost-snapshot {
border-left-color: $border-base;
}
.cost-tag span:last-child {
color: $card-text;
}
}
</style>
@@ -179,10 +179,8 @@ async function handleSave() {
await loadHistory(selectedSkuId.value);
emit('success');
if (vo?.costChanged) {
message.success('调价已保存');
void costSyncModalRef.value?.open([selectedSkuId.value], {
entry: 'manual',
});
message.success('调价已保存,已记入待同步影响面');
void costSyncModalRef.value?.open();
} else {
message.info('成本未变化,未写入新记录');
}
@@ -194,11 +192,7 @@ async function handleSave() {
}
function handleSyncCurrent() {
if (selectedSkuId.value == null) {
message.warning('请先选择 SKU');
return;
}
void costSyncModalRef.value?.open([selectedSkuId.value], { entry: 'manual' });
void costSyncModalRef.value?.open();
}
defineExpose({ open });
@@ -76,8 +76,9 @@ type FullTaskRow = {
lastError?: string;
/** 全量转换:上游同步任务 id */
syncTaskId?: number;
/** 全量计算:上游转换任务 id */
upstreamConvertTaskId?: number;
/** 全量计算:创建来源 / 多态上游 */
triggerSource?: string;
upstreamTaskId?: number;
};
const openFlag = ref(false);
@@ -183,9 +184,31 @@ function statusTag(status: string) {
return map[status] || { color: 'default', text: status };
}
/** 有上游任务 id → 上游创建;否则手动创建 */
function taskOriginTag(upstreamTaskId?: null | number) {
if (upstreamTaskId != null) {
/** 创建来源标签:优先 triggerSource + upstreamTaskId */
function taskOriginTag(
triggerSource?: null | string,
upstreamTaskId?: null | number,
) {
const source = triggerSource?.toUpperCase();
if (source === 'COST_SYNC') {
return {
color: 'purple' as const,
text: '成本同步',
tip:
upstreamTaskId != null
? `上游成本任务 #${upstreamTaskId}`
: '成本同步触发',
};
}
if (source === 'CONVERT' || (upstreamTaskId != null && source !== 'MANUAL')) {
return {
color: 'blue' as const,
text: '上游创建',
tip:
upstreamTaskId != null ? `上游任务 #${upstreamTaskId}` : '转换任务触发',
};
}
if (upstreamTaskId != null && !source) {
return {
color: 'blue' as const,
text: '上游创建',
@@ -983,12 +1006,12 @@ defineExpose({ open, close: handleClose });
</Tag>
</template>
<template v-else-if="column.key === 'origin'">
<Tooltip :title="taskOriginTag(asConvertTask(record).syncTaskId).tip">
<Tooltip :title="taskOriginTag(undefined, asConvertTask(record).syncTaskId).tip">
<Tag
:color="taskOriginTag(asConvertTask(record).syncTaskId).color"
:color="taskOriginTag(undefined, asConvertTask(record).syncTaskId).color"
class="!mr-0"
>
{{ taskOriginTag(asConvertTask(record).syncTaskId).text }}
{{ taskOriginTag(undefined, asConvertTask(record).syncTaskId).text }}
</Tag>
</Tooltip>
</template>
@@ -1160,19 +1183,26 @@ defineExpose({ open, close: handleClose });
<template v-else-if="column.key === 'origin'">
<Tooltip
:title="
taskOriginTag(asCalcTask(record).upstreamConvertTaskId).tip
taskOriginTag(
asCalcTask(record).triggerSource,
asCalcTask(record).upstreamTaskId,
).tip
"
>
<Tag
:color="
taskOriginTag(asCalcTask(record).upstreamConvertTaskId)
.color
taskOriginTag(
asCalcTask(record).triggerSource,
asCalcTask(record).upstreamTaskId,
).color
"
class="!mr-0"
>
{{
taskOriginTag(asCalcTask(record).upstreamConvertTaskId)
.text
taskOriginTag(
asCalcTask(record).triggerSource,
asCalcTask(record).upstreamTaskId,
).text
}}
</Tag>
</Tooltip>