feat: 成本同步功能完整实现

- ProductSpecController 新增 POST /ec/product-spec/sync-costs-to-orders 接口
- OrderMapper.updateCostFields() 批量更新订单成本字段
- OrderService 新增 syncCostsToOrders 方法
- UpdateProductResultDTO 返回完整成本变更规格列表(含 id/name/specCode/成本字段)
- 前端 ProductFormModal 同步弹窗:勾选规格 + 选择时间范围 + 显示更新条数
This commit is contained in:
小蟑螂
2026-04-14 22:04:38 +08:00
parent 26cb1a9a41
commit 83ed7478d2
11 changed files with 341 additions and 13 deletions
@@ -2,11 +2,36 @@ package top.xyquan.ecomdmbbackend.modules.ecom.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 订单Mapper接口
*/
@Mapper
public interface OrderMapper extends BaseMapper<OrderPO> {
/**
* 批量更新订单的成本字段
* @param productCost 商品成本
* @param shippingCost 运费成本
* @param otherCost 其他成本
* @param productSpecId 规格ID
* @param startTime 开始时间
* @param endTime 结束时间
* @return 更新行数
*/
@Update("UPDATE ec_order SET product_cost = #{productCost}, shipping_cost = #{shippingCost}, " +
"other_cost = #{otherCost}, update_time = NOW() " +
"WHERE product_spec_id = #{productSpecId} AND order_time >= #{startTime} AND order_time <= #{endTime}")
int updateCostFields(@Param("productCost") BigDecimal productCost,
@Param("shippingCost") BigDecimal shippingCost,
@Param("otherCost") BigDecimal otherCost,
@Param("productSpecId") Long productSpecId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
}
@@ -73,4 +73,18 @@ public interface OrderService extends IService<OrderPO> {
* @return 订单VO
*/
OrderVO createOrderForImport(CreateOrderDTO createOrderDTO, Long companyId, Long userId);
/**
* 同步规格成本到历史订单
* @param specId 规格ID
* @param productCost 商品成本
* @param shippingCost 运费成本
* @param otherCost 其他成本
* @param startTime 开始时间
* @param endTime 结束时间
* @return 更新行数
*/
int syncCostsToOrders(Long specId, java.math.BigDecimal productCost,
java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost,
java.time.LocalDateTime startTime, java.time.LocalDateTime endTime);
}
@@ -453,4 +453,11 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
return orderVO;
}
@Override
public int syncCostsToOrders(Long specId, java.math.BigDecimal productCost,
java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost,
java.time.LocalDateTime startTime, java.time.LocalDateTime endTime) {
return baseMapper.updateCostFields(productCost, shippingCost, otherCost, specId, startTime, endTime);
}
}
@@ -8,13 +8,18 @@ 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.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;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService.ProductSpecQueryDTO;
@@ -28,9 +33,14 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService
public class ProductSpecController {
private final ProductSpecService productSpecService;
private final OrderService orderService;
private final CurrentUserContext currentUserContext;
public ProductSpecController(ProductSpecService productSpecService) {
public ProductSpecController(ProductSpecService productSpecService, OrderService orderService,
CurrentUserContext currentUserContext) {
this.productSpecService = productSpecService;
this.orderService = orderService;
this.currentUserContext = currentUserContext;
}
@Operation(summary = "创建商品规格", description = "创建新的商品规格")
@@ -86,4 +96,25 @@ public class ProductSpecController {
return ApiResponse.success(productVOs);
}
@Operation(summary = "同步规格成本到历史订单", description = "将指定规格的成本批量更新到符合时间范围的订单")
@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();
// 验证规格是否存在且属于该公司
ProductSpecPO spec = productSpecService.getById(syncCostDTO.getSpecId());
if (spec == null || !spec.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在");
}
int updatedCount = orderService.syncCostsToOrders(
syncCostDTO.getSpecId(),
syncCostDTO.getProductCost(),
syncCostDTO.getShippingCost(),
syncCostDTO.getOtherCost(),
syncCostDTO.getStartTime(),
syncCostDTO.getEndTime()
);
return ApiResponse.success("成本同步成功,共更新" + updatedCount + "条订单", updatedCount);
}
}
@@ -0,0 +1,57 @@
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.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
/**
* 同步规格成本到订单的请求DTO
*/
@Data
@Schema(description = "同步规格成本到订单的请求DTO")
public class SyncCostDTO {
/**
* 规格ID
*/
@Schema(description = "规格ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "规格ID不能为空")
private Long specId;
/**
* 商品成本
*/
@Schema(description = "商品成本", example = "100.00")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 订单开始时间(包含),格式 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,8 +13,51 @@ import java.util.List;
public class UpdateProductResultDTO {
/**
* 本次更新中成本发生变更的规格ID列表
* 本次更新中成本发生变更的规格列表
*/
@Schema(description = "成本发生变更的规格ID列表")
private List<Long> costChangedSpecIds;
}
@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;
}
}
@@ -16,6 +16,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductDTO
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductResultDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductResultDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
@@ -226,7 +227,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
this.updateById(product);
// 如果提供了规格列表,则更新对应的规格
List<Long> costChangedSpecIds = new ArrayList<>();
List<UpdateProductResultDTO.CostChangedSpec> costChangedSpecs = new ArrayList<>();
if (updateProductDTO.getSpecs() != null && !updateProductDTO.getSpecs().isEmpty()) {
List<UpdateProductDTO.ProductSpecUpdateDTO> specDTOs = updateProductDTO.getSpecs();
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : specDTOs) {
@@ -270,14 +271,21 @@ 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())) {
costChangedSpecIds.add(specDTO.getId());
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);
}
}
}
// 返回结果
UpdateProductResultDTO result = new UpdateProductResultDTO();
result.setCostChangedSpecIds(costChangedSpecIds);
result.setCostChangedSpecs(costChangedSpecs);
return result;
}
@@ -75,3 +75,10 @@ export async function getProductSpecsByProductAndSpecsApi(
queries,
);
}
/**
* 同步规格成本到历史订单
*/
export async function syncCostsToOrdersApi(data: ProductSpecDTO.SyncCost) {
return requestClient.post<number>('/ec/product-spec/sync-costs-to-orders', data);
}
@@ -58,4 +58,20 @@ export namespace ProductSpecDTO {
/** 规格编码 */
specCode: string;
}
/** 同步规格成本到订单 */
export interface SyncCost {
/** 规格ID */
specId: number;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 订单开始时间 */
startTime: string;
/** 订单结束时间 */
endTime: string;
}
}
@@ -29,8 +29,24 @@ export namespace ProductVO {
/** 更新商品响应 */
export interface UpdateProductResult {
/** 本次更新中成本发生变更的规格ID列表 */
costChangedSpecIds: number[];
/** 本次更新中成本发生变更的规格列表 */
costChangedSpecs: CostChangedSpec[];
}
/** 成本变更的规格信息 */
export interface CostChangedSpec {
/** 规格ID */
id: number;
/** 规格名称 */
name: string;
/** 规格编码 */
specCode?: string;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
}
/** 商品规格信息 */
@@ -8,6 +8,7 @@ import { createIconifyIcon } from '@vben/icons';
import {
Button,
DatePicker,
Form,
Input,
InputNumber,
@@ -15,8 +16,10 @@ import {
Space,
Table,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { createProductApi, updateProductApi } from '#/api/ecommerce/product';
import { syncCostsToOrdersApi } from '#/api/ecommerce/product-spec/apis';
import { uploadFileToOss } from '#/utils/oss-upload';
interface Emits {
@@ -51,6 +54,62 @@ const DownIcon = createIconifyIcon('lucide:chevron-down');
const PlusIcon = createIconifyIcon('lucide:plus');
const TrashIcon = createIconifyIcon('lucide:trash-2');
// 成本同步弹窗
const [SyncModal, syncModalApi] = useVbenModal({
title: '成本变更确认',
class: 'w-[500px]',
draggable: true,
contentClass: 'px-5 py-4',
onConfirm: handleSyncConfirm,
onCancel: () => {
syncModalApi.close();
},
});
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();
}
const pendingCostChangedSpecs = ref<ProductVO.CostChangedSpec[]>([]);
const selectedSyncSpecIds = ref<number[]>([]);
async function handleSyncConfirm() {
if (selectedSyncSpecIds.value.length === 0 || !syncFormData.value) return;
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} 条订单`);
syncModalApi.close?.();
} catch (error) {
console.error('成本同步失败:', error);
message.error('成本同步失败');
} finally {
syncModalApi.setState?.({ confirmLoading: false });
}
}
// 内部状态管理
const isEdit = ref(false);
const currentProductData = ref<null | Partial<ProductVO.Info> | ProductVO.Info>(
@@ -182,11 +241,12 @@ async function handleSubmit() {
specs: specs.value as ProductDTO.UpdateSpec[],
}),
};
await updateProductApi(currentProductData.value.id, updateData);
if (specs.value.length > 0) {
const result = await updateProductApi(currentProductData.value.id, updateData);
if (specs.value.length > 0 && result.costChangedSpecs?.length > 0) {
message.success('商品和规格更新成功');
openSyncModal(result.costChangedSpecs);
} else {
message.success('更新成功');
message.success('商品和规格更新成功');
}
} else {
// 创建模式:统一使用创建接口,规格信息作为可选字段
@@ -654,4 +714,48 @@ onUnmounted(() => {
</Form.Item>
</Form>
</Modal>
<!-- 成本同步确认弹窗 -->
<SyncModal>
<div class="py-4">
<p class="mb-4 text-gray-600">
检测到 <strong>{{ pendingCostChangedSpecs.length }}</strong> 个规格的成本已更新,
请勾选需要同步的规格:
</p>
<div class="mb-4 max-h-48 overflow-y-auto border border-gray-200 rounded">
<div
v-for="spec in pendingCostChangedSpecs"
:key="spec.id"
class="flex items-center gap-3 px-3 py-2 border-b border-gray-100 last:border-b-0"
>
<input
type="checkbox"
:value="spec.id"
v-model="selectedSyncSpecIds"
class="w-4 h-4 rounded border-gray-300 text-blue-500 focus:ring-blue-500"
/>
<div class="flex-1 min-w-0">
<div class="text-sm font-medium text-gray-800 truncate">{{ spec.name }}</div>
<div class="text-xs text-gray-400">{{ spec.specCode || '无编码' }}</div>
</div>
<div class="text-xs text-gray-500 text-right shrink-0">
<div>商品成本: <span class="text-orange-500 font-medium">{{ spec.productCost }}</span></div>
<div v-if="spec.shippingCost">运费: {{ spec.shippingCost }}</div>
<div v-if="spec.otherCost">其他: {{ spec.otherCost }}</div>
</div>
</div>
</div>
<Form layout="vertical" class="mt-4">
<Form.Item label="同步时间范围">
<DatePicker.RangePicker
v-model:value="syncFormData"
class="w-full"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
show-time
/>
</Form.Item>
</Form>
</div>
</SyncModal>
</template>