feat(ecom-dmb): 优化商品成本同步逻辑

后端:
- UpdateProductResultDTO 改回只返回成本变更的规格ID列表
- ProductServiceImpl 构建 ID 列表而非完整对象
- 新增 BatchSyncCostDTO 批量同步请求DTO
- ProductSpecService 新增 getByIds 批量查询规格方法
- ProductSpecController 新增批量同步接口 batch-sync-costs-to-orders
- ProductSpecController 新增 batch-get-by-ids 接口查询规格详情

前端:
- UpdateProductResult 类型改为返回 costChangedSpecIds: number[]
- 新增 BatchSyncCost 和 getProductSpecsByIdsApi 批量接口
- ProductFormModal 改为批量同步,修复 responseReturn .data 的误用 bug
This commit is contained in:
小蟑螂
2026-04-17 11:40:23 +08:00
parent ac39f5d850
commit 5c4ef6c990
10 changed files with 171 additions and 104 deletions
@@ -13,6 +13,7 @@ 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.ecom.product.model.dto.BatchSyncCostDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductSpecFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.SyncCostDTO;
@@ -78,6 +79,24 @@ public class ProductSpecController {
return ApiResponse.success(result);
}
@Operation(summary = "根据ID列表批量查询商品规格", description = "根据规格ID列表批量查询规格详情,用于同步确认")
@PostMapping("/batch-get-by-ids")
@RequirePermission(value = "ecom:product:read", description = "批量查询商品规格", allowSuper = true)
public ApiResponse<List<ProductSpecVO>> batchGetByIds(@RequestBody List<Long> specIds) {
List<ProductSpecPO> specs = productSpecService.getByIds(specIds);
Long companyId = currentUserContext.getCurrentCompanyId();
// 只返回属于该公司的规格
List<ProductSpecVO> result = specs.stream()
.filter(spec -> spec.getCompanyId().equals(companyId))
.map(spec -> {
ProductSpecVO vo = new ProductSpecVO();
org.springframework.beans.BeanUtils.copyProperties(spec, vo);
return vo;
})
.collect(java.util.stream.Collectors.toList());
return ApiResponse.success(result);
}
@Operation(summary = "根据商品名称和规格编码精准查询商品规格", description = "根据商品名称和规格编码精准查询商品规格信息,用于数据导入")
@GetMapping("/find-by-product-and-spec/{productName}/{specCode}")
@RequirePermission(value = "ecom:product:read", description = "根据商品名称和规格编码查询商品规格", allowSuper = true)
@@ -117,4 +136,36 @@ public class ProductSpecController {
return ApiResponse.success("成本同步成功,共更新" + updatedCount + "条订单", updatedCount);
}
@Operation(summary = "批量同步规格成本到历史订单", description = "批量将多个规格的成本同步到符合时间范围的订单")
@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<ProductSpecPO> specs = productSpecService.getByIds(batchSyncCostDTO.getSpecIds());
if (specs.isEmpty()) {
return ApiResponse.success("没有找到需要同步的规格", 0);
}
// 校验所有规格都属于该公司
for (ProductSpecPO spec : specs) {
if (!spec.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在,规格ID: " + spec.getId());
}
}
// 逐个规格同步成本到订单,累加更新数量
int totalUpdated = 0;
for (ProductSpecPO spec : specs) {
int updated = orderService.syncCostsToOrders(
spec.getId(),
spec.getProductCost(),
spec.getShippingCost(),
spec.getOtherCost(),
batchSyncCostDTO.getStartTime(),
batchSyncCostDTO.getEndTime()
);
totalUpdated += updated;
}
return ApiResponse.success("批量成本同步成功,共更新" + totalUpdated + "条订单", totalUpdated);
}
}
@@ -0,0 +1,38 @@
package top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 批量同步规格成本到订单的请求DTO
*/
@Data
@Schema(description = "批量同步规格成本到订单的请求DTO")
public class BatchSyncCostDTO {
/**
* 规格ID列表
*/
@Schema(description = "规格ID列表", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "规格ID列表不能为空")
private List<Long> specIds;
/**
* 订单开始时间(包含),格式 yyyy-MM-dd HH:mm:ss
*/
@Schema(description = "订单开始时间", example = "2024-01-01 00:00:00")
@NotNull(message = "开始时间不能为空")
private LocalDateTime startTime;
/**
* 订单结束时间(包含),格式 yyyy-MM-dd HH:mm:ss
*/
@Schema(description = "订单结束时间", example = "2024-12-31 23:59:59")
@NotNull(message = "结束时间不能为空")
private LocalDateTime endTime;
}
@@ -13,51 +13,8 @@ import java.util.List;
public class UpdateProductResultDTO {
/**
* 本次更新中成本发生变更的规格列表
* 本次更新中成本发生变更的规格ID列表
*/
@Schema(description = "成本发生变更的规格列表")
private List<CostChangedSpec> costChangedSpecs;
/**
* 成本变更的规格简要信息
*/
@Data
@Schema(description = "成本变更的规格简要信息")
public static class CostChangedSpec {
/**
* 规格ID
*/
@Schema(description = "规格ID", example = "1")
private Long id;
/**
* 规格名称
*/
@Schema(description = "规格名称", example = "128GB 深空黑色")
private String name;
/**
* 规格编码
*/
@Schema(description = "规格编码", example = "IPHONE15PRO-128G-BLACK")
private String specCode;
/**
* 商品成本
*/
@Schema(description = "商品成本", example = "8000.00")
private java.math.BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private java.math.BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private java.math.BigDecimal otherCost;
}
@Schema(description = "成本发生变更的规格ID列表")
private List<Long> costChangedSpecIds;
}
@@ -81,6 +81,14 @@ public interface ProductSpecService extends IService<ProductSpecPO> {
*/
ProductSpecVO createProductSpecForImport(CreateProductSpecDTO createProductSpecDTO, Long companyId, Long userId);
/**
* 根据ID列表批量查询商品规格
*
* @param specIds 规格ID列表
* @return 商品规格PO列表
*/
List<ProductSpecPO> getByIds(List<Long> specIds);
/**
* 商品规格查询DTO
*/
@@ -227,7 +227,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
this.updateById(product);
// 如果提供了规格列表,则更新对应的规格
List<UpdateProductResultDTO.CostChangedSpec> costChangedSpecs = new ArrayList<>();
List<Long> costChangedSpecIds = new ArrayList<>();
if (updateProductDTO.getSpecs() != null && !updateProductDTO.getSpecs().isEmpty()) {
List<UpdateProductDTO.ProductSpecUpdateDTO> specDTOs = updateProductDTO.getSpecs();
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : specDTOs) {
@@ -271,21 +271,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
updateSpecDto.setRemark(specDTO.getRemark());
ProductSpecVO specVO = productSpecService.updateProductSpec(updateSpecDto, specDTO.getId());
if (Boolean.TRUE.equals(specVO.getCostChanged())) {
UpdateProductResultDTO.CostChangedSpec changedSpec = new UpdateProductResultDTO.CostChangedSpec();
changedSpec.setId(specDTO.getId());
changedSpec.setName(specDTO.getName());
changedSpec.setSpecCode(specDTO.getSpecCode());
changedSpec.setProductCost(specDTO.getProductCost());
changedSpec.setShippingCost(specDTO.getShippingCost());
changedSpec.setOtherCost(specDTO.getOtherCost());
costChangedSpecs.add(changedSpec);
costChangedSpecIds.add(specDTO.getId());
}
}
}
// 返回结果
UpdateProductResultDTO result = new UpdateProductResultDTO();
result.setCostChangedSpecs(costChangedSpecs);
result.setCostChangedSpecIds(costChangedSpecIds);
return result;
}
@@ -287,6 +287,14 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
return convertToVO(productSpec);
}
@Override
public List<ProductSpecPO> getByIds(List<Long> specIds) {
if (specIds == null || specIds.isEmpty()) {
return List.of();
}
return this.listByIds(specIds);
}
/**
* 根据商品名称和规格编码列表查询商品规格
* @param queries 商品规格查询DTO列表
@@ -77,8 +77,25 @@ export async function getProductSpecsByProductAndSpecsApi(
}
/**
* 同步规格成本到历史订单
* 根据ID列表批量查询商品规格
*/
export async function getProductSpecsByIdsApi(specIds: number[]) {
return requestClient.post<ProductSpecVO.Info[]>(
'/ec/product-spec/batch-get-by-ids',
specIds,
);
}
/**
* 同步规格成本到历史订单(单个规格)
*/
export async function syncCostsToOrdersApi(data: ProductSpecDTO.SyncCost) {
return requestClient.post<number>('/ec/product-spec/sync-costs-to-orders', data);
}
/**
* 批量同步规格成本到历史订单
*/
export async function batchSyncCostsToOrdersApi(data: ProductSpecDTO.BatchSyncCost) {
return requestClient.post<number>('/ec/product-spec/batch-sync-costs-to-orders', data);
}
@@ -59,7 +59,7 @@ export namespace ProductSpecDTO {
specCode: string;
}
/** 同步规格成本到订单 */
/** 同步规格成本到订单(单个规格) */
export interface SyncCost {
/** 规格ID */
specId: number;
@@ -74,4 +74,14 @@ export namespace ProductSpecDTO {
/** 订单结束时间 */
endTime: string;
}
/** 批量同步规格成本到订单 */
export interface BatchSyncCost {
/** 规格ID列表 */
specIds: number[];
/** 订单开始时间 */
startTime: string;
/** 订单结束时间 */
endTime: string;
}
}
@@ -31,24 +31,8 @@ export namespace ProductVO {
/** 更新商品响应 */
export interface UpdateProductResult {
/** 本次更新中成本发生变更的规格列表 */
costChangedSpecs: CostChangedSpec[];
}
/** 成本变更的规格信息 */
export interface CostChangedSpec {
/** 规格ID */
id: number;
/** 规格名称 */
name: string;
/** 规格编码 */
specCode?: string;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 本次更新中成本发生变更的规格ID列表 */
costChangedSpecIds: number[];
}
/** 商品规格信息 */
@@ -19,7 +19,11 @@ import {
import dayjs from 'dayjs';
import { createProductApi, updateProductApi } from '#/api/ecommerce/product';
import { syncCostsToOrdersApi } from '#/api/ecommerce/product-spec/apis';
import {
batchSyncCostsToOrdersApi,
getProductSpecsByIdsApi,
} from '#/api/ecommerce/product-spec/apis';
import type { ProductSpecVO } from '#/api/ecommerce/product-spec/types';
import { uploadFileToOss } from '#/utils/oss-upload';
interface Emits {
@@ -67,17 +71,24 @@ const [SyncModal, syncModalApi] = useVbenModal({
});
const syncFormData = ref<[string, string] | null>(null);
function openSyncModal(costChangedSpecs: ProductVO.CostChangedSpec[]) {
pendingCostChangedSpecs.value = costChangedSpecs;
selectedSyncSpecIds.value = costChangedSpecs.map((s) => s.id);
syncFormData.value = [
dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
];
syncModalApi.open();
async function openSyncModal(costChangedSpecIds: number[]) {
try {
// 根据ID列表查询规格详情
const specs = await getProductSpecsByIdsApi(costChangedSpecIds);
pendingCostChangedSpecs.value = specs ?? [];
selectedSyncSpecIds.value = costChangedSpecIds;
syncFormData.value = [
dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
];
syncModalApi.open();
} catch (error) {
console.error('获取规格详情失败:', error);
message.error('获取规格详情失败,无法进行成本同步');
}
}
const pendingCostChangedSpecs = ref<ProductVO.CostChangedSpec[]>([]);
const pendingCostChangedSpecs = ref<ProductSpecVO.Info[]>([]);
const selectedSyncSpecIds = ref<number[]>([]);
async function handleSyncConfirm() {
@@ -85,22 +96,12 @@ async function handleSyncConfirm() {
try {
syncModalApi.setState?.({ confirmLoading: true });
const [startDate, endDate] = syncFormData.value;
let totalUpdated = 0;
for (const specId of selectedSyncSpecIds.value) {
const spec = pendingCostChangedSpecs.value.find((s) => s.id === specId);
if (spec) {
const res = await syncCostsToOrdersApi({
specId,
productCost: spec.productCost,
shippingCost: spec.shippingCost ?? 0,
otherCost: spec.otherCost ?? 0,
startTime: startDate,
endTime: endDate,
});
totalUpdated += res.data ?? 0;
}
}
message.success(`成本同步完成,共更新 ${totalUpdated} 条订单`);
const totalUpdated = await batchSyncCostsToOrdersApi({
specIds: selectedSyncSpecIds.value,
startTime: startDate,
endTime: endDate,
});
message.success(`成本同步完成,共更新 ${totalUpdated ?? 0} 条订单`);
syncModalApi.close?.();
} catch (error) {
console.error('成本同步失败:', error);
@@ -242,9 +243,9 @@ async function handleSubmit() {
}),
};
const result = await updateProductApi(currentProductData.value.id, updateData);
if (specs.value.length > 0 && result.costChangedSpecs?.length > 0) {
if (specs.value.length > 0 && result.costChangedSpecIds?.length > 0) {
message.success('商品和规格更新成功');
openSyncModal(result.costChangedSpecs);
openSyncModal(result.costChangedSpecIds);
} else {
message.success('商品和规格更新成功');
}