feat: SKU 成本支持删除段与历史编辑模态,调价/删除均进入待同步影响面

This commit is contained in:
2026-08-31 23:48:32 +08:00
parent d29e23a4f2
commit a3ac5b1e8d
6 changed files with 403 additions and 113 deletions
@@ -77,6 +77,28 @@ public class ProductSkuCostController {
return ApiResponse.success(changed ? "调价成功,已记入待同步影响面" : "成本未变化", vo);
}
/**
* 删除成本历史段,并记入待同步影响面(与调价同一条回刷链路)。
*/
@DeleteMapping("/record/{id}")
@RequirePermission(value = "ec:product:update", description = "删除SKU成本段", allowSuper = true)
public ApiResponse<ProductSkuVO> deleteCostRecord(@PathVariable Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
var impactSnap = productSkuCostService.deleteCostSegment(id, companyId);
impactService.recordAfterAdjust(
companyId,
impactSnap.getSkuId(),
impactSnap.getEffectiveFrom(),
impactSnap.getProductCost() != null ? impactSnap.getProductCost() : BigDecimal.ZERO,
impactSnap.getShippingCost() != null ? impactSnap.getShippingCost() : BigDecimal.ZERO,
impactSnap.getOtherCost() != null ? impactSnap.getOtherCost() : BigDecimal.ZERO,
userId);
ProductSkuVO vo = productSkuService.toVo(productSkuService.getById(impactSnap.getSkuId()));
vo.setCostChanged(true);
return ApiResponse.success("删除成功,已记入待同步影响面", vo);
}
/** @deprecated 请使用 POST /api/ec/cost-sync/apply-pending */
@PostMapping("/sync-to-orders")
@RequirePermission(value = "ec:product:update", description = "同步成本到订单", allowSuper = true)
@@ -50,4 +50,11 @@ public interface ProductSkuCostService {
/** 业务日成本:effective_from ≤ onDate 的最新一条 */
ProductSkuCostPO getCostAsOf(Long skuId, LocalDate onDate);
/**
* 删除一条成本历史段;删后该生效日起回落到前一段(或无成本)。
*
* @return 用于记 PENDING 的快照(effectiveFrom=被删段起始日,金额=回落后成本)
*/
ProductSkuCostPO deleteCostSegment(Long costId, Long companyId);
}
@@ -3,6 +3,7 @@ package top.xyquan.ecomdmbbackend.modules.ec.product.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuCostMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuCostPO;
@@ -157,6 +158,36 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
return getBaselineCost(skuId, onDate);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ProductSkuCostPO deleteCostSegment(Long costId, Long companyId) {
if (costId == null || companyId == null) {
throw new BusinessException("成本记录/公司不能为空");
}
ProductSkuCostPO row = getById(costId);
if (row == null || !companyId.equals(row.getCompanyId())) {
throw new BusinessException("成本记录不存在");
}
Long skuId = row.getSkuId();
LocalDate effectiveFrom = row.getEffectiveFrom();
if (skuId == null || effectiveFrom == null) {
throw new BusinessException("成本记录数据不完整");
}
removeById(costId);
// 回落后的成本(供 PENDING 账本与一键回刷使用)
ProductSkuCostPO fallback = getBaselineCost(skuId, effectiveFrom);
ProductSkuCostPO impactSnap = new ProductSkuCostPO();
impactSnap.setCompanyId(companyId);
impactSnap.setSkuId(skuId);
impactSnap.setEffectiveFrom(effectiveFrom);
impactSnap.setProductCost(fallback != null ? nz(fallback.getProductCost()) : BigDecimal.ZERO);
impactSnap.setShippingCost(fallback != null ? nz(fallback.getShippingCost()) : BigDecimal.ZERO);
impactSnap.setOtherCost(fallback != null ? nz(fallback.getOtherCost()) : BigDecimal.ZERO);
return impactSnap;
}
/** 取 effective_from <= 指定日 的最新一条(含当日) */
private ProductSkuCostPO getBaselineCost(Long skuId, LocalDate onOrBefore) {
LambdaQueryWrapper<ProductSkuCostPO> w = new LambdaQueryWrapper<>();
@@ -55,3 +55,12 @@ export async function adjustSkuCostApi(
data,
);
}
/**
* 删除成本历史段,并记入待同步影响面
*/
export async function deleteSkuCostRecordApi(costId: number) {
return requestClient.delete<ProductSkuVO.Info>(
`/ec/product/sku/cost/record/${costId}`,
);
}
@@ -1,27 +1,27 @@
<script lang="ts" setup>
import type { ProductVO } from '#/api/ec/product/types';
import type { ProductSkuCostVO } from '#/api/ec/product/sku/cost/types';
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
import { computed, reactive, ref, watch } from 'vue';
import { computed, h, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import {
Alert,
Button,
DatePicker,
Drawer,
Form,
Input,
InputNumber,
message,
Popconfirm,
Space,
Table,
Typography,
message,
} from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';
import { adjustSkuCostApi, listSkuCostsApi } from '#/api/ec/product/sku/cost';
import { deleteSkuCostRecordApi, listSkuCostsApi } from '#/api/ec/product/sku/cost';
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
import ProductSkuCostFormModal from './ProductSkuCostFormModal.vue';
defineOptions({ name: 'ProductSkuCostDrawer' });
@@ -29,28 +29,27 @@ const emit = defineEmits<{
success: [];
}>();
const PlusIcon = createIconifyIcon('lucide:plus');
const EditIcon = createIconifyIcon('lucide:square-pen');
const TrashIcon = createIconifyIcon('lucide:trash-2');
const openFlag = ref(false);
const productName = ref('');
const skus = ref<ProductVO.SkuInfo[]>([]);
const selectedSkuId = ref<number | null>(null);
const history = ref<ProductSkuCostVO.History[]>([]);
const historyLoading = ref(false);
const saving = ref(false);
const formState = reactive({
effectiveFrom: dayjs() as Dayjs,
productCost: 0 as number,
shippingCost: 0 as number,
otherCost: 0 as number,
remark: '',
});
const deletingId = ref<number | null>(null);
const costSyncModalRef = ref<InstanceType<
typeof ProductCostSyncToOrdersModal
> | null>(null);
const costFormModalRef = ref<InstanceType<
typeof ProductSkuCostFormModal
> | null>(null);
const selectedSku = computed(() =>
skus.value.find((s) => s.id === selectedSkuId.value) ?? null,
const selectedSku = computed(
() => skus.value.find((s) => s.id === selectedSkuId.value) ?? null,
);
const historyColumns = [
@@ -91,18 +90,78 @@ const historyColumns = [
ellipsis: true,
customRender: ({ text }: { text?: string }) => text || '—',
},
{
title: '操作',
key: 'action',
width: 88,
align: 'center' as const,
customRender: ({ record }: { record: ProductSkuCostVO.History }) => {
return h(
Space,
{ size: 0 },
{
default: () => [
h(
Button,
{
type: 'text',
size: 'small',
title: '编辑',
onClick: () => openEdit(record),
},
{
icon: () => h(EditIcon, { class: 'h-4 w-4' }),
},
),
h(
Popconfirm,
{
title:
'删除该成本段后将回落到前一段,并记入待同步影响面。确定删除?',
okText: '删除',
okType: 'danger',
cancelText: '取消',
onConfirm: () => handleDeleteHistory(record),
},
{
default: () =>
h(
Button,
{
type: 'text',
danger: true,
size: 'small',
title: '删除',
loading: deletingId.value === record.id,
},
{
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
},
),
},
),
],
},
);
},
},
];
function formatMoney(v?: number) {
return `¥${Number(v ?? 0).toFixed(2)}`;
}
function fillFormFromSku(sku: ProductVO.SkuInfo | null) {
formState.effectiveFrom = dayjs();
formState.productCost = Number(sku?.productCost ?? 0);
formState.shippingCost = Number(sku?.shippingCost ?? 0);
formState.otherCost = Number(sku?.otherCost ?? 0);
formState.remark = '';
function applySkuVo(vo: ProductSkuVO.Info | null | undefined) {
if (!vo || selectedSkuId.value == null) return;
const idx = skus.value.findIndex((s) => s.id === selectedSkuId.value);
if (idx < 0) return;
skus.value[idx] = {
...skus.value[idx]!,
productCost: Number(vo.productCost ?? 0),
shippingCost: Number(vo.shippingCost ?? 0),
otherCost: Number(vo.otherCost ?? 0),
costEffectiveFrom: vo.costEffectiveFrom,
};
}
async function loadHistory(skuId: number) {
@@ -118,8 +177,6 @@ async function loadHistory(skuId: number) {
}
watch(selectedSkuId, (id) => {
const sku = skus.value.find((s) => s.id === id) ?? null;
fillFormFromSku(sku);
if (id != null) {
void loadHistory(id);
} else {
@@ -127,9 +184,7 @@ watch(selectedSkuId, (id) => {
}
});
/**
* 打开成本管理抽屉
*/
/** 打开成本管理抽屉 */
function open(product: ProductVO.Info, preferredSkuId?: number) {
productName.value = product.name ?? '';
skus.value = [...(product.skus ?? [])];
@@ -138,56 +193,63 @@ function open(product: ProductVO.Info, preferredSkuId?: number) {
(skus.value[0]?.id != null ? Number(skus.value[0].id) : null);
selectedSkuId.value = firstId;
if (firstId != null) {
const sku = skus.value.find((s) => s.id === firstId) ?? null;
fillFormFromSku(sku);
void loadHistory(firstId);
} else {
fillFormFromSku(null);
history.value = [];
}
openFlag.value = true;
}
async function handleSave() {
function openCreate() {
if (selectedSkuId.value == null) {
message.warning('请先选择 SKU');
return;
}
if (!formState.effectiveFrom) {
message.warning('请选择生效起始日');
const sku = selectedSku.value;
costFormModalRef.value?.openCreate(selectedSkuId.value, {
productCost: sku?.productCost,
shippingCost: sku?.shippingCost,
otherCost: sku?.otherCost,
});
}
function openEdit(row: ProductSkuCostVO.History) {
if (selectedSkuId.value == null) {
message.warning('请先选择 SKU');
return;
}
saving.value = true;
try {
const vo = await adjustSkuCostApi(selectedSkuId.value, {
effectiveFrom: formState.effectiveFrom.format('YYYY-MM-DD'),
productCost: formState.productCost ?? 0,
shippingCost: formState.shippingCost ?? 0,
otherCost: formState.otherCost ?? 0,
remark: formState.remark?.trim() || undefined,
});
const idx = skus.value.findIndex((s) => s.id === selectedSkuId.value);
if (idx >= 0 && vo) {
skus.value[idx] = {
...skus.value[idx]!,
productCost: Number(vo.productCost ?? 0),
shippingCost: Number(vo.shippingCost ?? 0),
otherCost: Number(vo.otherCost ?? 0),
costEffectiveFrom: vo.costEffectiveFrom,
};
}
costFormModalRef.value?.openEdit(selectedSkuId.value, row);
}
async function onCostFormSuccess(payload: {
costChanged: boolean;
sku: ProductSkuVO.Info;
}) {
applySkuVo(payload.sku);
if (selectedSkuId.value != null) {
await loadHistory(selectedSkuId.value);
emit('success');
if (vo?.costChanged) {
message.success('调价已保存,已记入待同步影响面');
void costSyncModalRef.value?.open();
} else {
message.info('成本未变化,未写入新记录');
}
emit('success');
if (payload.costChanged) {
void costSyncModalRef.value?.open();
}
}
async function handleDeleteHistory(row: ProductSkuCostVO.History) {
deletingId.value = row.id;
try {
const vo = await deleteSkuCostRecordApi(row.id);
applySkuVo(vo);
if (selectedSkuId.value != null) {
await loadHistory(selectedSkuId.value);
}
emit('success');
message.success('已删除成本段,已记入待同步影响面');
void costSyncModalRef.value?.open();
} catch (e) {
console.error(e);
} finally {
saving.value = false;
deletingId.value = null;
}
}
@@ -210,7 +272,7 @@ defineExpose({ open });
type="info"
show-icon
class="mb-4"
message="取某日成本 = 该 SKU 下 effective_from ≤ 业务日且最大的一条;同日再次保存会覆盖当日记录。"
message="取某日成本 = effective_from ≤ 业务日且最大的一条。添加可指定生效日;编辑仅改金额(生效日锁定);删除后回落前一段。变更会记入待同步影响面(回刷订单 + BI)。"
/>
<div v-if="skus.length === 0" class="py-10 text-center text-slate-400">
@@ -234,7 +296,9 @@ defineExpose({ open });
>
<span class="font-medium text-slate-800 dark:text-slate-100">
{{ sku.name || '未命名' }}
<span class="ml-1 font-normal text-slate-500">{{ sku.skuCode || '无编码' }}</span>
<span class="ml-1 font-normal text-slate-500">{{
sku.skuCode || '无编码'
}}</span>
</span>
<span class="mt-0.5 text-xs text-slate-500">
当前 {{ formatMoney(sku.productCost) }} /
@@ -247,58 +311,19 @@ defineExpose({ open });
</button>
</div>
<Typography.Title :level="5" class="!mb-2">调价</Typography.Title>
<Form layout="vertical" class="mb-2">
<Form.Item label="生效起始日" required>
<DatePicker
v-model:value="formState.effectiveFrom"
class="w-full"
format="YYYY-MM-DD"
:allow-clear="false"
/>
</Form.Item>
<div class="grid grid-cols-3 gap-3">
<Form.Item label="商品成本">
<InputNumber
v-model:value="formState.productCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
<Form.Item label="运费成本">
<InputNumber
v-model:value="formState.shippingCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
<Form.Item label="其他成本">
<InputNumber
v-model:value="formState.otherCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
</div>
<Form.Item label="备注">
<Input
v-model:value="formState.remark"
placeholder="调价原因(可选)"
allow-clear
/>
</Form.Item>
<div class="mb-3 flex items-center justify-between gap-2">
<Typography.Title :level="5" class="!mb-0">成本历史</Typography.Title>
<Space>
<Button type="primary" :loading="saving" @click="handleSave">
保存调价
<Button type="primary" @click="openCreate">
<template #icon>
<PlusIcon class="h-4 w-4" />
</template>
添加成本段
</Button>
<Button @click="handleSyncCurrent">同步当前成本到订单</Button>
<Button @click="handleSyncCurrent">同步到订单</Button>
</Space>
</Form>
</div>
<Typography.Title :level="5" class="!mb-2 !mt-6">成本历史</Typography.Title>
<Table
size="small"
:loading="historyLoading"
@@ -306,10 +331,14 @@ defineExpose({ open });
:data-source="history"
:pagination="false"
row-key="id"
:scroll="{ y: 240 }"
:scroll="{ y: 420 }"
/>
</template>
<ProductSkuCostFormModal
ref="costFormModalRef"
@success="onCostFormSuccess"
/>
<ProductCostSyncToOrdersModal ref="costSyncModalRef" />
</Drawer>
</template>
@@ -0,0 +1,192 @@
<script lang="ts" setup>
import type { ProductSkuCostVO } from '#/api/ec/product/sku/cost/types';
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
import { computed, reactive, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
} from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';
import { adjustSkuCostApi } from '#/api/ec/product/sku/cost';
defineOptions({ name: 'ProductSkuCostFormModal' });
const emit = defineEmits<{
/** 保存成功;costChanged 为 true 时调用方应打开待同步 */
success: [payload: { costChanged: boolean; sku: ProductSkuVO.Info }];
}>();
const [Modal, modalApi] = useVbenModal({
title: '添加成本段',
class: 'w-[520px]',
draggable: true,
destroyOnClose: true,
confirmText: '保存',
onConfirm: handleOk,
onCancel: close,
});
const saving = ref(false);
const mode = ref<'create' | 'edit'>('create');
const skuId = ref<number>();
const formState = reactive({
effectiveFrom: dayjs() as Dayjs,
productCost: 0 as number,
shippingCost: 0 as number,
otherCost: 0 as number,
remark: '',
});
const isEdit = computed(() => mode.value === 'edit');
function resetForm(baseline?: {
otherCost?: number;
productCost?: number;
shippingCost?: number;
}) {
formState.effectiveFrom = dayjs();
formState.productCost = Number(baseline?.productCost ?? 0);
formState.shippingCost = Number(baseline?.shippingCost ?? 0);
formState.otherCost = Number(baseline?.otherCost ?? 0);
formState.remark = '';
}
function close() {
if (saving.value) return;
modalApi.close();
}
/**
* 打开「添加」:生效日可选,金额默认带当前成本
*/
function openCreate(
targetSkuId: number,
baseline?: {
otherCost?: number;
productCost?: number;
shippingCost?: number;
},
) {
mode.value = 'create';
skuId.value = targetSkuId;
resetForm(baseline);
modalApi.setState({ title: '添加成本段' });
modalApi.open();
}
/**
* 打开「编辑」:生效日锁定,仅改金额/备注(同日覆盖)
*/
function openEdit(targetSkuId: number, row: ProductSkuCostVO.History) {
mode.value = 'edit';
skuId.value = targetSkuId;
formState.effectiveFrom = dayjs(row.effectiveFrom);
formState.productCost = Number(row.productCost ?? 0);
formState.shippingCost = Number(row.shippingCost ?? 0);
formState.otherCost = Number(row.otherCost ?? 0);
formState.remark = row.remark ?? '';
modalApi.setState({ title: '编辑成本段' });
modalApi.open();
}
async function handleOk() {
if (skuId.value == null) {
return;
}
if (!formState.effectiveFrom) {
message.warning('请选择生效起始日');
return;
}
saving.value = true;
modalApi.setState({ submitting: true });
try {
const vo = await adjustSkuCostApi(skuId.value, {
effectiveFrom: formState.effectiveFrom.format('YYYY-MM-DD'),
productCost: formState.productCost ?? 0,
shippingCost: formState.shippingCost ?? 0,
otherCost: formState.otherCost ?? 0,
remark: formState.remark?.trim() || undefined,
});
if (!vo?.costChanged) {
message.info('成本未变化,未写入新记录');
modalApi.close();
return;
}
message.success(
isEdit.value
? '编辑成功,已记入待同步影响面'
: '添加成功,已记入待同步影响面',
);
modalApi.close();
emit('success', { costChanged: true, sku: vo });
} catch (error) {
console.error(error);
} finally {
saving.value = false;
modalApi.setState({ submitting: false });
}
}
defineExpose({ openCreate, openEdit });
</script>
<template>
<Modal>
<Form layout="vertical" class="px-1 pt-1">
<Form.Item label="生效起始日" required>
<DatePicker
v-model:value="formState.effectiveFrom"
class="w-full"
format="YYYY-MM-DD"
:allow-clear="false"
:disabled="isEdit"
/>
<p v-if="isEdit" class="mt-1 mb-0 text-xs text-slate-400">
编辑时不可修改生效日;保存将覆盖该日成本记录
</p>
</Form.Item>
<div class="grid grid-cols-3 gap-3">
<Form.Item label="商品成本">
<InputNumber
v-model:value="formState.productCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
<Form.Item label="运费成本">
<InputNumber
v-model:value="formState.shippingCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
<Form.Item label="其他成本">
<InputNumber
v-model:value="formState.otherCost"
:min="0"
:precision="2"
class="w-full"
/>
</Form.Item>
</div>
<Form.Item label="备注">
<Input
v-model:value="formState.remark"
:placeholder="isEdit ? '修改说明(可选)' : '调价原因(可选)'"
allow-clear
/>
</Form.Item>
</Form>
</Modal>
</template>