feat: 完善sku成本

This commit is contained in:
2026-08-15 09:26:55 +08:00
parent 3828e309df
commit 2dda6a2d30
24 changed files with 912 additions and 239 deletions
@@ -8,21 +8,16 @@ import org.springframework.web.bind.annotation.*;
import java.util.List;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.BatchSyncCostDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.CreateProductSkuDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.ProductSkuFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.SyncCostDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.UpdateProductSkuDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuVO;
import top.xyquan.ecomdmbbackend.modules.ec.order.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService.ProductSkuQueryDTO;
@@ -35,17 +30,11 @@ import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService.Pr
public class ProductSkuController {
private final ProductSkuService productSkuService;
private final ProductSkuCostService productSkuCostService;
private final OrderService orderService;
private final CurrentUserContext currentUserContext;
public ProductSkuController(ProductSkuService productSkuService,
ProductSkuCostService productSkuCostService,
OrderService orderService,
CurrentUserContext currentUserContext) {
this.productSkuService = productSkuService;
this.productSkuCostService = productSkuCostService;
this.orderService = orderService;
this.currentUserContext = currentUserContext;
}
@@ -113,74 +102,4 @@ public class ProductSkuController {
List<ProductVO> productVOs = productSkuService.getProductSkusByProductAndSkus(queries);
return ApiResponse.success("批量查询SKU成功", productVOs);
}
@Operation(summary = "同步SKU成本到历史订单")
@PostMapping("/sync-costs-to-orders")
@RequirePermission(value = "ecom:product:update", description = "同步成本到订单", allowSuper = true)
public ApiResponse<Integer> syncCostsToOrders(@Valid @RequestBody SyncCostDTO syncCostDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
ProductSkuPO sku = productSkuService.getById(syncCostDTO.getSkuId());
if (sku == null || !sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在");
}
int updatedCount = orderService.syncCostsToOrders(
syncCostDTO.getSkuId(),
syncCostDTO.getProductCost(),
syncCostDTO.getShippingCost(),
syncCostDTO.getOtherCost(),
syncCostDTO.getStartTime(),
syncCostDTO.getEndTime());
return ApiResponse.success("成本同步成功,共更新" + updatedCount + "条订单", updatedCount);
}
@Operation(summary = "统计成本同步将影响的订单数量")
@PostMapping("/count-orders-for-cost-sync")
@RequirePermission(value = "ecom:product:read", description = "统计成本同步订单数", allowSuper = true)
public ApiResponse<Long> countOrdersForCostSync(@Valid @RequestBody BatchSyncCostDTO batchSyncCostDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<ProductSkuPO> skus = productSkuService.getByIds(batchSyncCostDTO.getSkuIds());
if (skus.isEmpty()) {
return ApiResponse.success("统计成功", 0L);
}
for (ProductSkuPO sku : skus) {
if (!sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在,SKU ID: " + sku.getId());
}
}
long count = orderService.countOrdersForCostSync(
companyId,
batchSyncCostDTO.getSkuIds(),
batchSyncCostDTO.getStartTime(),
batchSyncCostDTO.getEndTime());
return ApiResponse.success("统计成功", count);
}
@Operation(summary = "批量同步SKU成本到历史订单")
@PostMapping("/batch-sync-costs-to-orders")
@RequirePermission(value = "ecom:product:update", description = "批量同步成本到订单", allowSuper = true)
public ApiResponse<Integer> batchSyncCostsToOrders(@Valid @RequestBody BatchSyncCostDTO batchSyncCostDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<ProductSkuPO> skus = productSkuService.getByIds(batchSyncCostDTO.getSkuIds());
if (skus.isEmpty()) {
return ApiResponse.success("没有找到需要同步的SKU", 0);
}
for (ProductSkuPO sku : skus) {
if (!sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在,SKU ID: " + sku.getId());
}
}
int totalUpdated = 0;
for (ProductSkuPO sku : skus) {
var cost = productSkuCostService.getCurrentCost(sku.getId());
int updated = orderService.syncCostsToOrders(
sku.getId(),
cost != null ? cost.getProductCost() : null,
cost != null ? cost.getShippingCost() : null,
cost != null ? cost.getOtherCost() : null,
batchSyncCostDTO.getStartTime(),
batchSyncCostDTO.getEndTime());
totalUpdated += updated;
}
return ApiResponse.success("批量成本同步成功,共更新" + totalUpdated + "条订单", totalUpdated);
}
}
@@ -0,0 +1,148 @@
package top.xyquan.ecomdmbbackend.modules.ec.product.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ec.order.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.AdjustSkuCostDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.BatchSyncCostDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.dto.SyncCostDTO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuCostHistoryVO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuVO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
/**
* 商品 SKU 成本:历史、调价、同步到订单
*/
@Tag(name = "电商-商品SKU成本", description = "SKU成本历史、按生效日调价、同步到订单")
@RestController
@RequestMapping("/api/ec/product/sku/cost")
public class ProductSkuCostController {
private final ProductSkuService productSkuService;
private final ProductSkuCostService productSkuCostService;
private final OrderService orderService;
private final CurrentUserContext currentUserContext;
public ProductSkuCostController(ProductSkuService productSkuService,
ProductSkuCostService productSkuCostService,
OrderService orderService,
CurrentUserContext currentUserContext) {
this.productSkuService = productSkuService;
this.productSkuCostService = productSkuCostService;
this.orderService = orderService;
this.currentUserContext = currentUserContext;
}
@Operation(summary = "查询SKU成本历史")
@GetMapping("/{skuId}")
@RequirePermission(value = "ecom:product:read", description = "查询SKU成本历史", allowSuper = true)
public ApiResponse<List<ProductSkuCostHistoryVO>> listSkuCosts(
@Parameter(description = "SKU ID") @PathVariable Long skuId) {
ProductSkuPO sku = requireCompanySku(skuId);
return ApiResponse.success("查询成本历史成功", productSkuCostService.listCostHistory(sku.getId()));
}
@Operation(summary = "SKU调价(按生效日追加/同日纠错)")
@PostMapping("/{skuId}")
@RequirePermission(value = "ecom:product:update", description = "SKU调价", allowSuper = true)
public ApiResponse<ProductSkuVO> adjustSkuCost(
@Parameter(description = "SKU ID") @PathVariable Long skuId,
@Valid @RequestBody AdjustSkuCostDTO dto) {
ProductSkuPO sku = requireCompanySku(skuId);
Long userId = currentUserContext.getCurrentUserId();
boolean changed = productSkuCostService.adjustCost(
sku.getId(), sku.getCompanyId(), sku.getProductId(),
dto.getEffectiveFrom(),
dto.getProductCost(), dto.getShippingCost(), dto.getOtherCost(),
dto.getRemark(), userId);
ProductSkuVO vo = productSkuService.toVo(productSkuService.getById(sku.getId()));
vo.setCostChanged(changed);
return ApiResponse.success(changed ? "调价成功" : "成本未变化", vo);
}
@Operation(summary = "同步SKU成本到历史订单")
@PostMapping("/sync-to-orders")
@RequirePermission(value = "ecom:product:update", description = "同步成本到订单", allowSuper = true)
public ApiResponse<Integer> syncCostsToOrders(@Valid @RequestBody SyncCostDTO syncCostDTO) {
requireCompanySku(syncCostDTO.getSkuId());
int updatedCount = orderService.syncCostsToOrders(
syncCostDTO.getSkuId(),
syncCostDTO.getProductCost(),
syncCostDTO.getShippingCost(),
syncCostDTO.getOtherCost(),
syncCostDTO.getStartTime(),
syncCostDTO.getEndTime());
return ApiResponse.success("成本同步成功,共更新" + updatedCount + "条订单", updatedCount);
}
@Operation(summary = "统计成本同步将影响的订单数量")
@PostMapping("/count-orders-for-sync")
@RequirePermission(value = "ecom:product:read", description = "统计成本同步订单数", allowSuper = true)
public ApiResponse<Long> countOrdersForCostSync(@Valid @RequestBody BatchSyncCostDTO batchSyncCostDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<ProductSkuPO> skus = productSkuService.getByIds(batchSyncCostDTO.getSkuIds());
if (skus.isEmpty()) {
return ApiResponse.success("统计成功", 0L);
}
for (ProductSkuPO sku : skus) {
if (!sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在,SKU ID: " + sku.getId());
}
}
long count = orderService.countOrdersForCostSync(
companyId,
batchSyncCostDTO.getSkuIds(),
batchSyncCostDTO.getStartTime(),
batchSyncCostDTO.getEndTime());
return ApiResponse.success("统计成功", count);
}
@Operation(summary = "批量同步SKU当前生效成本到历史订单")
@PostMapping("/batch-sync-to-orders")
@RequirePermission(value = "ecom:product:update", description = "批量同步成本到订单", allowSuper = true)
public ApiResponse<Integer> batchSyncCostsToOrders(@Valid @RequestBody BatchSyncCostDTO batchSyncCostDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
List<ProductSkuPO> skus = productSkuService.getByIds(batchSyncCostDTO.getSkuIds());
if (skus.isEmpty()) {
return ApiResponse.success("没有找到需要同步的SKU", 0);
}
for (ProductSkuPO sku : skus) {
if (!sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在,SKU ID: " + sku.getId());
}
}
int totalUpdated = 0;
for (ProductSkuPO sku : skus) {
var cost = productSkuCostService.getCurrentCost(sku.getId());
int updated = orderService.syncCostsToOrders(
sku.getId(),
cost != null ? cost.getProductCost() : null,
cost != null ? cost.getShippingCost() : null,
cost != null ? cost.getOtherCost() : null,
batchSyncCostDTO.getStartTime(),
batchSyncCostDTO.getEndTime());
totalUpdated += updated;
}
return ApiResponse.success("批量成本同步成功,共更新" + totalUpdated + "条订单", totalUpdated);
}
private ProductSkuPO requireCompanySku(Long skuId) {
Long companyId = currentUserContext.getCurrentCompanyId();
ProductSkuPO sku = productSkuService.getById(skuId);
if (sku == null || !sku.getCompanyId().equals(companyId)) {
throw new BusinessException("SKU不存在");
}
return sku;
}
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.ec.product.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* SKU 调价(按生效日追加/同日纠错)
*/
@Data
@Schema(description = "SKU调价参数")
public class AdjustSkuCostDTO {
@NotNull(message = "生效起始日不能为空")
@Schema(description = "生效起始日(含)", requiredMode = Schema.RequiredMode.REQUIRED)
private LocalDate effectiveFrom;
@NotNull(message = "商品成本不能为空")
@Schema(description = "商品成本", requiredMode = Schema.RequiredMode.REQUIRED)
private BigDecimal productCost;
@Schema(description = "运费成本")
private BigDecimal shippingCost;
@Schema(description = "其他成本")
private BigDecimal otherCost;
@Schema(description = "备注(如调价原因)")
private String remark;
}
@@ -25,14 +25,13 @@ public class UpdateProductSkuDTO {
@Schema(description = "SKU编码")
private String skuCode;
@Schema(description = "商品成本", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品成本不能为空")
@Schema(description = "商品成本(已废弃:调价请走 /product-sku/{id}/costs)")
private BigDecimal productCost;
@Schema(description = "运费成本")
@Schema(description = "运费成本(已废弃:调价请走独立成本接口)")
private BigDecimal shippingCost;
@Schema(description = "其他成本")
@Schema(description = "其他成本(已废弃:调价请走独立成本接口)")
private BigDecimal otherCost;
@Schema(description = "备注")
@@ -0,0 +1,37 @@
package top.xyquan.ecomdmbbackend.modules.ec.product.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* SKU 成本历史条目
*/
@Data
@Schema(description = "SKU成本历史条目")
public class ProductSkuCostHistoryVO {
@Schema(description = "成本记录ID")
private Long id;
@Schema(description = "生效起始日(含)")
private LocalDate effectiveFrom;
@Schema(description = "商品成本")
private BigDecimal productCost;
@Schema(description = "运费成本")
private BigDecimal shippingCost;
@Schema(description = "其他成本")
private BigDecimal otherCost;
@Schema(description = "备注")
private String remark;
@Schema(description = "创建时间")
private LocalDateTime createTime;
}
@@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
@@ -43,6 +44,9 @@ public class ProductSkuVO {
@Schema(description = "其他成本(当前生效)")
private BigDecimal otherCost;
@Schema(description = "当前成本生效起始日")
private LocalDate costEffectiveFrom;
@Schema(description = "备注")
private String remark;
@@ -1,13 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.ec.product.service;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuCostPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuCostHistoryVO;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* SKU 成本读写:当前成本查询与按日 upsert
* SKU 成本读写:当前成本查询、历史列表与按日调价
*/
public interface ProductSkuCostService {
@@ -17,8 +20,22 @@ public interface ProductSkuCostService {
/** 批量读当前成本,key=skuId */
Map<Long, ProductSkuCostPO> getCurrentCosts(Collection<Long> skuIds);
/** 成本历史:按 effective_from 降序 */
List<ProductSkuCostHistoryVO> listCostHistory(Long skuId);
/**
* 按生效日调价:同日已有行则 UPDATE,否则 INSERT。
* 相对「该生效日及之前最近一条」比较,无变化则不写。
*
* @return 是否实际写入(含同日纠错)
*/
boolean adjustCost(Long skuId, Long companyId, Long productId, LocalDate effectiveFrom,
BigDecimal productCost, BigDecimal shippingCost, BigDecimal otherCost,
String remark, Long userId);
/**
* 成本有变则写入:当日已有行则 UPDATE,否则 INSERT effective_from=今天。
* 供导入等旁路复用;商品编辑调价请走 {@link #adjustCost}。
*
* @return 成本是否相对当前生效值发生变化
*/
@@ -361,19 +361,13 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
}
}
// 更新规格(走标准更新流程,内部会检测成本是否变化)
// 更新规格(成本变更请走独立调价接口)
UpdateProductSkuDTO updateSpecDto = new UpdateProductSkuDTO();
updateSpecDto.setName(specDTO.getName());
updateSpecDto.setSkuCode(specDTO.getSkuCode());
updateSpecDto.setProductCost(specDTO.getProductCost());
updateSpecDto.setShippingCost(specDTO.getShippingCost());
updateSpecDto.setOtherCost(specDTO.getOtherCost());
updateSpecDto.setRemark(specDTO.getRemark());
updateSpecDto.setImageId(specDTO.getImageId());
ProductSkuVO specVO = productSkuService.updateProductSku(updateSpecDto, specDTO.getId());
if (Boolean.TRUE.equals(specVO.getCostChanged())) {
rawCostChangedSkuIds.add(specDTO.getId());
}
productSkuService.updateProductSku(updateSpecDto, specDTO.getId());
}
for (UpdateProductDTO.ProductSkuUpdateDTO specDTO : newSpecs) {
@@ -3,12 +3,15 @@ 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 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;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.vo.ProductSkuCostHistoryVO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductSkuCostService;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
@@ -44,7 +47,6 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
if (ids.isEmpty()) {
return result;
}
// 一次查出后按 sku 取 effective_from 最新一条,避免 N+1
List<ProductSkuCostPO> rows = list(new LambdaQueryWrapper<ProductSkuCostPO>()
.in(ProductSkuCostPO::getSkuId, ids)
.orderByDesc(ProductSkuCostPO::getEffectiveFrom));
@@ -54,17 +56,87 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
return result;
}
@Override
public List<ProductSkuCostHistoryVO> listCostHistory(Long skuId) {
if (skuId == null) {
return List.of();
}
List<ProductSkuCostPO> rows = list(new LambdaQueryWrapper<ProductSkuCostPO>()
.eq(ProductSkuCostPO::getSkuId, skuId)
.orderByDesc(ProductSkuCostPO::getEffectiveFrom)
.orderByDesc(ProductSkuCostPO::getId));
List<ProductSkuCostHistoryVO> list = new ArrayList<>(rows.size());
for (ProductSkuCostPO row : rows) {
ProductSkuCostHistoryVO vo = new ProductSkuCostHistoryVO();
vo.setId(row.getId());
vo.setEffectiveFrom(row.getEffectiveFrom());
vo.setProductCost(row.getProductCost());
vo.setShippingCost(row.getShippingCost());
vo.setOtherCost(row.getOtherCost());
vo.setRemark(row.getRemark());
vo.setCreateTime(row.getCreateTime());
list.add(vo);
}
return list;
}
@Override
public boolean adjustCost(Long skuId, Long companyId, Long productId, LocalDate effectiveFrom,
BigDecimal productCost, BigDecimal shippingCost, BigDecimal otherCost,
String remark, Long userId) {
if (skuId == null || companyId == null || productId == null) {
throw new BusinessException("SKU/公司/商品不能为空");
}
if (effectiveFrom == null) {
throw new BusinessException("生效起始日不能为空");
}
ProductSkuCostPO baseline = getBaselineCost(skuId, effectiveFrom);
ProductSkuCostPO sameDay = getCostOnDate(skuId, effectiveFrom);
BigDecimal pc = nz(productCost);
BigDecimal sc = nz(shippingCost);
BigDecimal oc = nz(otherCost);
if (sameDay != null) {
boolean changed = isCostChanged(sameDay, pc, sc, oc)
|| !Objects.equals(trimToNull(remark), trimToNull(sameDay.getRemark()));
if (!changed) {
return false;
}
sameDay.setProductCost(pc);
sameDay.setShippingCost(sc);
sameDay.setOtherCost(oc);
sameDay.setRemark(trimToNull(remark));
sameDay.setUpdateBy(userId);
updateById(sameDay);
return true;
}
if (!isCostChanged(baseline, pc, sc, oc)) {
return false;
}
ProductSkuCostPO row = new ProductSkuCostPO();
row.setCompanyId(companyId);
row.setProductId(productId);
row.setSkuId(skuId);
row.setProductCost(pc);
row.setShippingCost(sc);
row.setOtherCost(oc);
row.setEffectiveFrom(effectiveFrom);
row.setRemark(trimToNull(remark));
row.setCreateBy(userId);
row.setUpdateBy(userId);
save(row);
return true;
}
@Override
public boolean upsertCostIfChanged(Long skuId, Long companyId, Long productId,
BigDecimal productCost, BigDecimal shippingCost, BigDecimal otherCost,
Long userId) {
ProductSkuCostPO current = getCurrentCost(skuId);
boolean changed = isCostChanged(current, productCost, shippingCost, otherCost);
if (!changed) {
return false;
}
writeCostForToday(skuId, companyId, productId, productCost, shippingCost, otherCost, userId);
return true;
return adjustCost(skuId, companyId, productId, LocalDate.now(),
productCost, shippingCost, otherCost, null, userId);
}
@Override
@@ -74,35 +146,24 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
if (!hasAnyCostValue(productCost, shippingCost, otherCost)) {
return;
}
writeCostForToday(skuId, companyId, productId, productCost, shippingCost, otherCost, userId);
adjustCost(skuId, companyId, productId, LocalDate.now(),
productCost, shippingCost, otherCost, null, userId);
}
private void writeCostForToday(Long skuId, Long companyId, Long productId,
BigDecimal productCost, BigDecimal shippingCost, BigDecimal otherCost,
Long userId) {
LocalDate today = LocalDate.now();
/** 取 effective_from <= 指定日 的最新一条(含当日) */
private ProductSkuCostPO getBaselineCost(Long skuId, LocalDate onOrBefore) {
LambdaQueryWrapper<ProductSkuCostPO> w = new LambdaQueryWrapper<>();
w.eq(ProductSkuCostPO::getSkuId, skuId).eq(ProductSkuCostPO::getEffectiveFrom, today);
ProductSkuCostPO existing = getOne(w);
if (existing != null) {
existing.setProductCost(nz(productCost));
existing.setShippingCost(nz(shippingCost));
existing.setOtherCost(nz(otherCost));
existing.setUpdateBy(userId);
updateById(existing);
return;
}
ProductSkuCostPO row = new ProductSkuCostPO();
row.setCompanyId(companyId);
row.setProductId(productId);
row.setSkuId(skuId);
row.setProductCost(nz(productCost));
row.setShippingCost(nz(shippingCost));
row.setOtherCost(nz(otherCost));
row.setEffectiveFrom(today);
row.setCreateBy(userId);
row.setUpdateBy(userId);
save(row);
w.eq(ProductSkuCostPO::getSkuId, skuId)
.le(ProductSkuCostPO::getEffectiveFrom, onOrBefore)
.orderByDesc(ProductSkuCostPO::getEffectiveFrom)
.last("LIMIT 1");
return getOne(w);
}
private ProductSkuCostPO getCostOnDate(Long skuId, LocalDate effectiveFrom) {
LambdaQueryWrapper<ProductSkuCostPO> w = new LambdaQueryWrapper<>();
w.eq(ProductSkuCostPO::getSkuId, skuId).eq(ProductSkuCostPO::getEffectiveFrom, effectiveFrom);
return getOne(w);
}
private static boolean isCostChanged(ProductSkuCostPO current,
@@ -139,4 +200,12 @@ public class ProductSkuCostServiceImpl extends ServiceImpl<ProductSkuCostMapper,
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static String trimToNull(String s) {
if (s == null) {
return null;
}
String t = s.trim();
return t.isEmpty() ? null : t;
}
}
@@ -108,30 +108,22 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
throw new BusinessException("SKU名称已存在");
}
ProductSkuCostPO currentCost = productSkuCostService.getCurrentCost(id);
boolean costChanged = ProductSkuCostServiceImpl.isSingleCostChanged(
currentCost != null ? currentCost.getProductCost() : null, dto.getProductCost())
|| ProductSkuCostServiceImpl.isSingleCostChanged(
currentCost != null ? currentCost.getShippingCost() : null, dto.getShippingCost())
|| ProductSkuCostServiceImpl.isSingleCostChanged(
currentCost != null ? currentCost.getOtherCost() : null, dto.getOtherCost());
// 调价走独立成本接口;此处只更新 SKU 基础字段
ProductSkuPO sku = new ProductSkuPO();
BeanCopyUtils.copyProperties(dto, sku);
sku.setId(id);
sku.setCompanyId(companyId);
sku.setProductId(existing.getProductId());
sku.setName(dto.getName());
sku.setSkuCode(dto.getSkuCode());
sku.setRemark(dto.getRemark());
if (dto.getImageId() != null) {
sku.setImageId(dto.getImageId());
}
sku.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(sku);
if (costChanged) {
productSkuCostService.upsertCostIfChanged(id, companyId, existing.getProductId(),
dto.getProductCost(), dto.getShippingCost(), dto.getOtherCost(),
currentUserContext.getCurrentUserId());
}
ProductSkuVO vo = toVo(this.getById(id));
vo.setCostChanged(costChanged);
vo.setCostChanged(false);
return vo;
}
@@ -437,6 +429,7 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
vo.setProductCost(cost.getProductCost());
vo.setShippingCost(cost.getShippingCost());
vo.setOtherCost(cost.getOtherCost());
vo.setCostEffectiveFrom(cost.getEffectiveFrom());
}
// 有系统图 id 则覆盖外链
if (sku.getImageId() != null) {
@@ -80,24 +80,3 @@ export async function getProductSkusByIdsApi(skuIds: number[]) {
skuIds,
);
}
/**
* 同步 SKU 成本到历史订单(单个 SKU)
*/
export async function syncCostsToOrdersApi(data: ProductSkuDTO.SyncCost) {
return requestClient.post<number>('/ec/product-sku/sync-costs-to-orders', data);
}
/**
* 批量同步 SKU 成本到历史订单
*/
export async function batchSyncCostsToOrdersApi(data: ProductSkuDTO.BatchSyncCost) {
return requestClient.post<number>('/ec/product-sku/batch-sync-costs-to-orders', data);
}
/**
* 统计指定 SKU 与时间范围内将参与成本同步的订单数量
*/
export async function countOrdersForCostSyncApi(data: ProductSkuDTO.BatchSyncCost) {
return requestClient.post<number>('/ec/product-sku/count-orders-for-cost-sync', data);
}
@@ -0,0 +1,57 @@
import type { ProductSkuCostDTO, ProductSkuCostVO } from './types';
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
import { requestClient } from '#/api/request';
/**
* 同步 SKU 成本到历史订单(单个 SKU)
*/
export async function syncCostsToOrdersApi(data: ProductSkuCostDTO.SyncCost) {
return requestClient.post<number>('/ec/product/sku/cost/sync-to-orders', data);
}
/**
* 批量同步 SKU 当前生效成本到历史订单
*/
export async function batchSyncCostsToOrdersApi(
data: ProductSkuCostDTO.BatchSyncCost,
) {
return requestClient.post<number>(
'/ec/product/sku/cost/batch-sync-to-orders',
data,
);
}
/**
* 统计指定 SKU 与时间范围内将参与成本同步的订单数量
*/
export async function countOrdersForCostSyncApi(
data: ProductSkuCostDTO.BatchSyncCost,
) {
return requestClient.post<number>(
'/ec/product/sku/cost/count-orders-for-sync',
data,
);
}
/**
* 查询 SKU 成本历史
*/
export async function listSkuCostsApi(skuId: number) {
return requestClient.get<ProductSkuCostVO.History[]>(
`/ec/product/sku/cost/${skuId}`,
);
}
/**
* SKU 调价(按生效日追加 / 同日纠错)
*/
export async function adjustSkuCostApi(
skuId: number,
data: ProductSkuCostDTO.AdjustCost,
) {
return requestClient.post<ProductSkuVO.Info>(
`/ec/product/sku/cost/${skuId}`,
data,
);
}
@@ -0,0 +1,5 @@
/**
* 商品 SKU 成本模块 API
*/
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,31 @@
/**
* SKU 成本相关 DTO
*/
export namespace ProductSkuCostDTO {
/** 同步 SKU 成本到订单(单个 SKU) */
export interface SyncCost {
skuId: number;
productCost: number;
shippingCost?: number;
otherCost?: number;
startTime: string;
endTime: string;
}
/** 批量同步 SKU 成本到订单 */
export interface BatchSyncCost {
skuIds: number[];
startTime: string;
endTime: string;
}
/** SKU 调价(按生效日) */
export interface AdjustCost {
/** 生效起始日 yyyy-MM-dd */
effectiveFrom: string;
productCost: number;
shippingCost?: number;
otherCost?: number;
remark?: string;
}
}
@@ -0,0 +1,16 @@
/**
* SKU 成本相关 VO
*/
export namespace ProductSkuCostVO {
/** 成本历史条目 */
export interface History {
id: number;
/** 生效起始日 yyyy-MM-dd */
effectiveFrom: string;
productCost: number;
shippingCost?: number;
otherCost?: number;
remark?: string;
createTime?: string;
}
}
@@ -64,30 +64,4 @@ export namespace ProductSkuDTO {
/** SKU 编码 */
skuCode: string;
}
/** 同步 SKU 成本到订单(单个 SKU) */
export interface SyncCost {
/** SKU ID */
skuId: number;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 订单开始时间 */
startTime: string;
/** 订单结束时间 */
endTime: string;
}
/** 批量同步 SKU 成本到订单 */
export interface BatchSyncCost {
/** SKU ID 列表 */
skuIds: number[];
/** 订单时间下限(含) */
startTime: string;
/** 订单时间上限(含) */
endTime: string;
}
}
@@ -23,6 +23,8 @@ export namespace ProductSkuVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 当前成本生效起始日 yyyy-MM-dd */
costEffectiveFrom?: string;
/** 备注 */
remark?: string;
/** SKU 图 URL(系统文件或渠道外链) */
@@ -68,6 +68,8 @@ export namespace ProductVO {
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 当前成本生效起始日 yyyy-MM-dd */
costEffectiveFrom?: string;
/** 备注 */
remark?: string;
/** SKU 图 URL(系统文件或渠道外链) */
@@ -10,8 +10,8 @@ import { DatePicker, message } from 'ant-design-vue';
import {
batchSyncCostsToOrdersApi,
countOrdersForCostSyncApi,
getProductSkusByIdsApi,
} from '#/api/ec/product/sku/apis';
} from '#/api/ec/product/sku/cost';
import { getProductSkusByIdsApi } from '#/api/ec/product/sku/apis';
defineOptions({ name: 'ProductCostSyncToOrdersModal' });
@@ -201,10 +201,10 @@ defineExpose({ open });
<template v-if="costSyncModalEntry === 'after-save'">
检测到
<strong>{{ pendingCostChangedSkus.length }}</strong>
个SKU的成本已更新,请勾选需要同步的SKU:
个SKU的<strong>当前生效</strong>成本已写入,请勾选需要同步到订单的SKU:
</template>
<template v-else>
将所选SKU<strong>当前</strong>的商品成本、运费、其他成本写入订单(会覆盖该时间范围内订单上的对应成本字段)。请勾选需要同步的SKU,共
将所选SKU<strong>当前生效</strong>的商品成本、运费、其他成本写入订单(会覆盖该时间范围内订单上的对应成本字段)。请勾选需要同步的SKU,共
<strong>{{ pendingCostChangedSkus.length }}</strong> 个:
</template>
</div>
@@ -21,6 +21,7 @@ const router = useRouter();
const emit = defineEmits<{
edit: [product: ProductVO.Info];
manageCost: [product: ProductVO.Info];
}>();
/** 金额展示 */
@@ -75,7 +76,7 @@ const skuColumns = [
title: '运费成本',
dataIndex: 'shippingCost',
key: 'shippingCost',
width: 110,
width: 100,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.shippingCost),
},
@@ -83,10 +84,17 @@ const skuColumns = [
title: '其他成本',
dataIndex: 'otherCost',
key: 'otherCost',
width: 110,
width: 100,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.otherCost),
},
{
title: '成本生效日',
dataIndex: 'costEffectiveFrom',
key: 'costEffectiveFrom',
width: 120,
customRender: ({ text }: { text?: string }) => text || '-',
},
{
title: '备注',
dataIndex: 'remark',
@@ -129,6 +137,13 @@ function handleEdit() {
emit('edit', current);
}
function handleManageCost() {
if (!product.value) return;
const current = product.value;
modalApi.close();
emit('manageCost', current);
}
defineExpose({
open,
});
@@ -195,7 +210,7 @@ defineExpose({
row-key="id"
size="small"
bordered
:scroll="{ x: 820 }"
:scroll="{ x: 920 }"
/>
</div>
@@ -206,6 +221,7 @@ defineExpose({
<ChartIcon class="mr-1 h-4 w-4" />
经营统计
</Button>
<Button @click="handleManageCost">管理成本</Button>
<Button type="primary" @click="handleEdit">
<EditIcon class="mr-1 h-4 w-4" />
编辑商品
@@ -23,7 +23,8 @@ import { getCategoryTreeApi } from '#/api/ec/product/category';
import { createProductApi, updateProductApi } from '#/api/ec/product';
import { uploadFileToOss } from '#/utils/oss-upload';
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
import ProductCostSyncToOrdersModal from '#/views/ec/product/components/ProductCostSyncToOrdersModal.vue';
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
interface Emits {
(e: 'success'): void;
@@ -60,6 +61,9 @@ const TrashIcon = createIconifyIcon('lucide:trash-2');
const productCostSyncModalRef = ref<InstanceType<
typeof ProductCostSyncToOrdersModal
> | null>(null);
const productSkuCostDrawerRef = ref<InstanceType<
typeof ProductSkuCostDrawer
> | null>(null);
async function openSyncModal(skuIds: number[]) {
await productCostSyncModalRef.value?.open(skuIds, {
@@ -71,6 +75,15 @@ async function openSyncModal(skuIds: number[]) {
});
}
function openCostDrawer() {
const product = currentProductData.value as ProductVO.Info | null;
if (!product?.id) {
message.warning('请先保存商品后再管理成本');
return;
}
productSkuCostDrawerRef.value?.open(product);
}
// 内部状态管理
const isEdit = ref(false);
const currentProductData = ref<null | Partial<ProductVO.Info> | ProductVO.Info>(
@@ -152,6 +165,7 @@ const categoryTreeDropdownRender: DropdownRender = (opt) => {
type SkuFormRow = ProductDTO.Sku & {
_clientKey?: string;
id?: number;
costEffectiveFrom?: string;
/** 已有图预览 URL(系统文件或渠道外链) */
imageUrl?: string;
/** 新选择待上传的文件 */
@@ -217,6 +231,7 @@ function initFormData() {
productCost: spec.productCost ?? 0,
shippingCost: spec.shippingCost ?? 0,
otherCost: spec.otherCost ?? 0,
costEffectiveFrom: spec.costEffectiveFrom,
remark: spec.remark || '',
imageUrl: spec.imageUrl || '',
});
@@ -552,6 +567,44 @@ function clearSkuNewImage(record: SkuFormRow) {
}
// 表格列配置
function canEditSkuCost(record: SkuFormRow) {
// 新建商品,或编辑时新增的 SKU,可填初始成本;已有 SKU 调价走成本抽屉
return !isEdit.value || record.id == null;
}
function renderCostCell(
record: SkuFormRow,
field: 'productCost' | 'shippingCost' | 'otherCost',
placeholder: string,
) {
if (!canEditSkuCost(record)) {
const amount = Number(record[field] ?? 0).toFixed(2);
const from = record.costEffectiveFrom
? `自 ${record.costEffectiveFrom}`
: '';
return h(
'div',
{ class: 'text-xs leading-tight text-slate-700 dark:text-slate-200' },
[
h('div', `¥${amount}`),
from
? h('div', { class: 'text-[11px] text-slate-400' }, from)
: null,
],
);
}
return h(InputNumber, {
value: record[field] ?? 0,
placeholder,
min: 0,
precision: 2,
style: { width: '100%' },
'onUpdate:value': (value: null | number) => {
record[field] = value ?? 0;
},
} as any);
}
const skuColumns = [
{
title: '图片',
@@ -670,67 +723,34 @@ const skuColumns = [
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 100,
width: 110,
customRender: ({
record,
}: {
record: SkuFormRow;
}) => {
return h(InputNumber, {
value: record.productCost,
placeholder: '商品成本',
min: 0,
precision: 2,
style: { width: '100%' },
'onUpdate:value': (value: null | number) => {
record.productCost = value ?? 0;
},
} as any);
},
}) => renderCostCell(record, 'productCost', '商品成本'),
},
{
title: '运费成本',
dataIndex: 'shippingCost',
key: 'shippingCost',
width: 90,
width: 100,
customRender: ({
record,
}: {
record: SkuFormRow;
}) => {
return h(InputNumber, {
value: record.shippingCost ?? 0,
placeholder: '运费',
min: 0,
precision: 2,
style: { width: '100%' },
'onUpdate:value': (value: null | number) => {
record.shippingCost = value ?? 0;
},
} as any);
},
}) => renderCostCell(record, 'shippingCost', '运费'),
},
{
title: '其他成本',
dataIndex: 'otherCost',
key: 'otherCost',
width: 90,
width: 100,
customRender: ({
record,
}: {
record: SkuFormRow;
}) => {
return h(InputNumber, {
value: record.otherCost ?? 0,
placeholder: '其他',
min: 0,
precision: 2,
style: { width: '100%' },
'onUpdate:value': (value: null | number) => {
record.otherCost = value ?? 0;
},
} as any);
},
}) => renderCostCell(record, 'otherCost', '其他'),
},
{
title: '备注',
@@ -966,6 +986,13 @@ onUnmounted(() => {
</template>
{{ showSkus ? '收起 SKU' : '添加 SKU' }}
</Button>
<Button
v-if="isEdit && currentProductData?.id"
type="link"
@click="openCostDrawer"
>
管理成本
</Button>
</Space>
<Button v-if="showSkus" type="primary" @click="addSku">
<template #icon>
@@ -974,6 +1001,12 @@ onUnmounted(() => {
添加 SKU
</Button>
</div>
<p
v-if="isEdit && showSkus"
class="text-xs text-slate-400"
>
已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。
</p>
<div
v-if="showSkus"
@@ -1000,6 +1033,10 @@ onUnmounted(() => {
</Modal>
<ProductCostSyncToOrdersModal ref="productCostSyncModalRef" />
<ProductSkuCostDrawer
ref="productSkuCostDrawerRef"
@success="emit('success')"
/>
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
</template>
@@ -0,0 +1,321 @@
<script lang="ts" setup>
import type { ProductVO } from '#/api/ec/product/types';
import type { ProductSkuCostVO } from '#/api/ec/product/sku/cost/types';
import { computed, reactive, ref, watch } from 'vue';
import {
Alert,
Button,
DatePicker,
Drawer,
Form,
Input,
InputNumber,
message,
Space,
Table,
Typography,
} from 'ant-design-vue';
import dayjs, { type Dayjs } from 'dayjs';
import { adjustSkuCostApi, listSkuCostsApi } from '#/api/ec/product/sku/cost';
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
defineOptions({ name: 'ProductSkuCostDrawer' });
const emit = defineEmits<{
success: [];
}>();
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 costSyncModalRef = ref<InstanceType<
typeof ProductCostSyncToOrdersModal
> | null>(null);
const selectedSku = computed(() =>
skus.value.find((s) => s.id === selectedSkuId.value) ?? null,
);
const historyColumns = [
{
title: '生效日',
dataIndex: 'effectiveFrom',
key: 'effectiveFrom',
width: 120,
},
{
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 100,
customRender: ({ text }: { text?: number }) =>
`¥${Number(text ?? 0).toFixed(2)}`,
},
{
title: '运费',
dataIndex: 'shippingCost',
key: 'shippingCost',
width: 90,
customRender: ({ text }: { text?: number }) =>
`¥${Number(text ?? 0).toFixed(2)}`,
},
{
title: '其他',
dataIndex: 'otherCost',
key: 'otherCost',
width: 90,
customRender: ({ text }: { text?: number }) =>
`¥${Number(text ?? 0).toFixed(2)}`,
},
{
title: '备注',
dataIndex: 'remark',
key: 'remark',
ellipsis: true,
customRender: ({ text }: { text?: string }) => text || '—',
},
];
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 = '';
}
async function loadHistory(skuId: number) {
historyLoading.value = true;
try {
history.value = (await listSkuCostsApi(skuId)) ?? [];
} catch {
history.value = [];
message.error('加载成本历史失败');
} finally {
historyLoading.value = false;
}
}
watch(selectedSkuId, (id) => {
const sku = skus.value.find((s) => s.id === id) ?? null;
fillFormFromSku(sku);
if (id != null) {
void loadHistory(id);
} else {
history.value = [];
}
});
/**
* 打开成本管理抽屉
*/
function open(product: ProductVO.Info, preferredSkuId?: number) {
productName.value = product.name ?? '';
skus.value = [...(product.skus ?? [])];
const firstId =
preferredSkuId ??
(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() {
if (selectedSkuId.value == null) {
message.warning('请先选择 SKU');
return;
}
if (!formState.effectiveFrom) {
message.warning('请选择生效起始日');
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,
};
}
await loadHistory(selectedSkuId.value);
emit('success');
if (vo?.costChanged) {
message.success('调价已保存');
void costSyncModalRef.value?.open([selectedSkuId.value], {
entry: 'manual',
});
} else {
message.info('成本未变化,未写入新记录');
}
} catch (e) {
console.error(e);
} finally {
saving.value = false;
}
}
function handleSyncCurrent() {
if (selectedSkuId.value == null) {
message.warning('请先选择 SKU');
return;
}
void costSyncModalRef.value?.open([selectedSkuId.value], { entry: 'manual' });
}
defineExpose({ open });
</script>
<template>
<Drawer
v-model:open="openFlag"
:title="`成本管理${productName ? ` · ${productName}` : ''}`"
width="720"
destroy-on-close
:mask-closable="true"
>
<Alert
type="info"
show-icon
class="mb-4"
message="取某日成本 = 该 SKU 下 effective_from ≤ 业务日且最大的一条;同日再次保存会覆盖当日记录。"
/>
<div v-if="skus.length === 0" class="py-10 text-center text-slate-400">
该商品暂无 SKU,请先在编辑商品中添加
</div>
<template v-else>
<Typography.Title :level="5" class="!mb-2">选择 SKU</Typography.Title>
<div class="mb-4 flex max-h-40 flex-col gap-1 overflow-y-auto">
<button
v-for="sku in skus"
:key="sku.id"
type="button"
class="flex w-full flex-col rounded-lg border px-3 py-2 text-left text-sm transition-colors"
:class="
selectedSkuId === sku.id
? 'border-blue-400 bg-blue-50 dark:border-blue-500 dark:bg-blue-950/40'
: 'border-slate-200 hover:bg-slate-50 dark:border-[hsl(240deg_3.7%_22%)] dark:hover:bg-[hsl(240deg_3.7%_18%)]'
"
@click="selectedSkuId = sku.id"
>
<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>
<span class="mt-0.5 text-xs text-slate-500">
当前 {{ formatMoney(sku.productCost) }} /
{{ formatMoney(sku.shippingCost) }} /
{{ formatMoney(sku.otherCost) }}
<template v-if="sku.costEffectiveFrom">
· 自 {{ sku.costEffectiveFrom }}
</template>
</span>
</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>
<Space>
<Button type="primary" :loading="saving" @click="handleSave">
保存调价
</Button>
<Button @click="handleSyncCurrent">同步当前成本到订单</Button>
</Space>
</Form>
<Typography.Title :level="5" class="!mb-2 !mt-6">成本历史</Typography.Title>
<Table
size="small"
:loading="historyLoading"
:columns="historyColumns"
:data-source="history"
:pagination="false"
row-key="id"
:scroll="{ y: 240 }"
/>
</template>
<ProductCostSyncToOrdersModal ref="costSyncModalRef" />
</Drawer>
</template>
@@ -17,12 +17,14 @@ import { deleteProductApi, getProductPageApi } from '#/api/ec/product';
import ProductDetailModal from './components/ProductDetailModal.vue';
import ProductFormModal from './components/ProductFormModal.vue';
import ProductSkuCostDrawer from './components/ProductSkuCostDrawer.vue';
defineOptions({ name: 'ProductManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const ChartIcon = createIconifyIcon('lucide:line-chart');
const EditIcon = createIconifyIcon('lucide:square-pen');
const CoinsIcon = createIconifyIcon('lucide:coins');
const ImageIcon = createIconifyIcon('lucide:image');
const router = useRouter();
@@ -33,6 +35,9 @@ const productFormModalRef = ref<InstanceType<typeof ProductFormModal> | null>(
const productDetailModalRef = ref<InstanceType<typeof ProductDetailModal> | null>(
null,
);
const productSkuCostDrawerRef = ref<InstanceType<
typeof ProductSkuCostDrawer
> | null>(null);
/** 列表行内最多展示的 SKU 编码标签数 */
const MAX_SKU_CODE_TAGS = 4;
@@ -107,7 +112,7 @@ const gridOptions: VxeGridProps<ProductVO.Info> = {
},
{
title: '操作',
minWidth: 200,
minWidth: 260,
fixed: 'right' as const,
slots: { default: 'action' },
},
@@ -281,6 +286,10 @@ function handleEdit(record: ProductVO.Info) {
productFormModalRef.value?.open(true, record);
}
function handleCost(record: ProductVO.Info) {
productSkuCostDrawerRef.value?.open(record);
}
/** 打开商品详情模态框 */
function openProductDetail(record: ProductVO.Info) {
productDetailModalRef.value?.open(record);
@@ -392,6 +401,10 @@ function handleDetailEdit(record: ProductVO.Info) {
<EditIcon class="mr-0.5 h-3.5 w-3.5" />
编辑
</Button>
<Button type="link" size="small" @click="handleCost(row)">
<CoinsIcon class="mr-0.5 h-3.5 w-3.5" />
成本
</Button>
<Button type="link" size="small" @click="goToOverview(row)">
<ChartIcon class="mr-0.5 h-3.5 w-3.5" />
统计
@@ -412,6 +425,11 @@ function handleDetailEdit(record: ProductVO.Info) {
<ProductDetailModal
ref="productDetailModalRef"
@edit="handleDetailEdit"
@manage-cost="handleCost"
/>
<ProductSkuCostDrawer
ref="productSkuCostDrawerRef"
@success="handleModalSuccess"
/>
</Page>
</template>