refactor: 重新设计表

This commit is contained in:
ah--desktop
2025-12-22 23:13:45 +08:00
parent 755a6f6a58
commit 914a9345db
29 changed files with 876 additions and 498 deletions
@@ -16,9 +16,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportMappingVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportMappingService;
/**
* 导入映射管理控制器
* 导入映射模板管理控制器
*/
@Tag(name = "电商-导入映射管理", description = "导入映射的增删改查接口")
@Tag(name = "电商-导入映射模板管理", description = "导入映射模板的增删改查接口")
@RestController
@RequestMapping("/ec/import-mapping")
public class ImportMappingController {
@@ -31,7 +31,7 @@ public class ImportMappingController {
@Operation(summary = "创建导入映射模板", description = "创建新的导入映射模板")
@PostMapping("/create")
@RequireRole(description = "创建导入映射", allowUser = false)
@RequireRole(description = "创建导入映射模板", allowUser = false)
public ApiResponse<ImportMappingVO> createImportMapping(@Valid @RequestBody CreateImportMappingDTO createImportMappingDTO) {
ImportMappingVO importMappingVO = importMappingService.createImportMapping(createImportMappingDTO);
return ApiResponse.success(importMappingVO);
@@ -39,26 +39,26 @@ public class ImportMappingController {
@Operation(summary = "更新导入映射模板", description = "更新现有导入映射模板")
@PutMapping("/update/{id}")
@RequireRole(description = "更新导入映射", allowUser = false)
@RequireRole(description = "更新导入映射模板", allowUser = false)
public ApiResponse<ImportMappingVO> updateImportMapping(
@Valid @RequestBody UpdateImportMappingDTO updateImportMappingDTO,
@Parameter(description = "映射ID") @PathVariable Long id) {
@Parameter(description = "模板ID") @PathVariable Long id) {
ImportMappingVO importMappingVO = importMappingService.updateImportMapping(updateImportMappingDTO, id);
return ApiResponse.success(importMappingVO);
}
@Operation(summary = "删除导入映射", description = "删除指定导入映射")
@Operation(summary = "删除导入映射模板", description = "删除指定导入映射模板")
@DeleteMapping("/delete/{id}")
@RequireRole(description = "删除导入映射", allowUser = false)
@RequireRole(description = "删除导入映射模板", allowUser = false)
public ApiResponse<Void> deleteImportMapping(
@Parameter(description = "映射ID") @PathVariable Long id) {
@Parameter(description = "模板ID") @PathVariable Long id) {
importMappingService.deleteImportMapping(id);
return ApiResponse.success();
}
@Operation(summary = "分页获取导入映射列表", description = "分页获取导入映射列表,支持条件过滤")
@Operation(summary = "分页获取导入映射模板列表", description = "分页获取导入映射模板列表,支持条件过滤")
@PostMapping("/page")
@RequireRole(description = "查询导入映射列表", allowUser = true)
@RequireRole(description = "查询导入映射模板列表", allowUser = true)
public ApiResponse<PageResultVO<ImportMappingVO>> getImportMappingPage(
@Valid @RequestBody PageQueryDTO<ImportMappingFilterDTO> pageQueryDTO) {
PageResultVO<ImportMappingVO> result = importMappingService.getImportMappingPage(pageQueryDTO);
@@ -4,76 +4,71 @@ 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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.UpdateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.UpdateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderStatusVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import java.util.List;
/**
* 订单状态控制器
* 订单状态管理控制器
*/
@Tag(name = "电商-订单状态管理", description = "订单状态的增删改查接口")
@RestController
@RequestMapping("/ec/order-status")
@RequiredArgsConstructor
@Tag(name = "电商-订单状态管理", description = "订单状态相关接口")
public class OrderStatusController {
private final OrderStatusService orderStatusService;
@PostMapping
public OrderStatusController(OrderStatusService orderStatusService) {
this.orderStatusService = orderStatusService;
}
@Operation(summary = "创建订单状态", description = "创建新的订单状态")
public ApiResponse<Long> createOrderStatus(@Valid @RequestBody CreateOrderStatusDTO dto) {
Long id = orderStatusService.createOrderStatus(dto);
return ApiResponse.success(id);
@PostMapping("/create")
@RequireRole(description = "创建订单状态", allowUser = false)
public ApiResponse<OrderStatusVO> createOrderStatus(@Valid @RequestBody CreateOrderStatusDTO createOrderStatusDTO) {
OrderStatusVO orderStatusVO = orderStatusService.createOrderStatus(createOrderStatusDTO);
return ApiResponse.success(orderStatusVO);
}
@PutMapping
@Operation(summary = "更新订单状态", description = "更新订单状态信息")
public ApiResponse<Void> updateOrderStatus(@Valid @RequestBody UpdateOrderStatusDTO dto) {
orderStatusService.updateOrderStatus(dto);
return ApiResponse.success();
@Operation(summary = "更新订单状态", description = "更新现有订单状态信息")
@PutMapping("/update/{id}")
@RequireRole(description = "更新订单状态", allowUser = false)
public ApiResponse<OrderStatusVO> updateOrderStatus(@Valid @RequestBody UpdateOrderStatusDTO updateOrderStatusDTO,
@Parameter(description = "订单状态ID") @PathVariable Long id) {
OrderStatusVO orderStatusVO = orderStatusService.updateOrderStatus(updateOrderStatusDTO, id);
return ApiResponse.success(orderStatusVO);
}
@DeleteMapping("/{id}")
@Operation(summary = "删除订单状态", description = "删除指定的订单状态")
@Operation(summary = "删除订单状态", description = "删除指定订单状态")
@DeleteMapping("/delete/{id}")
@RequireRole(description = "删除订单状态", allowUser = false)
public ApiResponse<Void> deleteOrderStatus(
@Parameter(description = "状态ID", required = true) @PathVariable Long id) {
@Parameter(description = "订单状态ID") @PathVariable Long id) {
orderStatusService.deleteOrderStatus(id);
return ApiResponse.success();
}
@GetMapping("/{id}")
@Operation(summary = "查询订单状态详情", description = "根据ID查询订单状态详情")
@Operation(summary = "获取所有订单状态", description = "获取当前公司的所有订单状态列表")
@GetMapping("/list")
@RequireRole(description = "查询订单状态列表", allowUser = true)
public ApiResponse<List<OrderStatusVO>> getAllOrderStatuses() {
List<OrderStatusVO> result = orderStatusService.getAllOrderStatuses();
return ApiResponse.success(result);
}
@Operation(summary = "获取订单状态详情", description = "根据ID获取订单状态详情")
@GetMapping("/detail/{id}")
@RequireRole(description = "查询订单状态详情", allowUser = true)
public ApiResponse<OrderStatusVO> getOrderStatusById(
@Parameter(description = "状态ID", required = true) @PathVariable Long id) {
OrderStatusVO vo = orderStatusService.getOrderStatusById(id);
return ApiResponse.success(vo);
}
@GetMapping("/active")
@Operation(summary = "查询启用的订单状态列表", description = "查询所有启用的订单状态")
public ApiResponse<List<OrderStatusVO>> getActiveOrderStatusList() {
List<OrderStatusVO> list = orderStatusService.getActiveOrderStatusList();
return ApiResponse.success(list);
}
@GetMapping("/all")
@Operation(summary = "查询所有订单状态列表", description = "查询所有订单状态(包括禁用的)")
public ApiResponse<List<OrderStatusVO>> getAllOrderStatusList() {
List<OrderStatusVO> list = orderStatusService.getAllOrderStatusList();
return ApiResponse.success(list);
}
@PostMapping("/init")
@Operation(summary = "初始化订单状态数据", description = "为当前公司初始化默认的订单状态数据")
public ApiResponse<Void> initOrderStatus() {
// 这里需要从CurrentUserContext获取当前公司ID,但为了保持接口简洁,我们修改服务层方法
orderStatusService.initOrderStatusForCurrentCompany();
return ApiResponse.success();
@Parameter(description = "订单状态ID") @PathVariable Long id) {
OrderStatusVO orderStatusVO = orderStatusService.getOrderStatusById(id);
return ApiResponse.success(orderStatusVO);
}
}
@@ -5,8 +5,9 @@ import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
/**
* 订单状态Mapper
* 订单状态Mapper接口
*/
@Mapper
public interface OrderStatusMapper extends BaseMapper<OrderStatusPO> {
}
@@ -6,32 +6,32 @@ import jakarta.validation.constraints.Pattern;
import lombok.Data;
/**
* 创建导入映射DTO
* 创建导入映射模板DTO
*/
@Data
@Schema(description = "创建导入映射DTO")
@Schema(description = "创建导入映射模板DTO")
public class CreateImportMappingDTO {
/**
* 导入类型(product-商品 order-订单)
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
*/
@Schema(description = "导入类型", example = "product", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"product", "order"})
@Schema(description = "导入类型", example = "PRODUCT", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS"})
@NotBlank(message = "导入类型不能为空")
@Pattern(regexp = "^(product|order)$", message = "导入类型只能是product或order")
@Pattern(regexp = "^(PRODUCT|ORDER|ORDER_STATUS)$", message = "导入类型只能是PRODUCT、ORDER或ORDER_STATUS")
private String type;
/**
* 映射名称
* 模板名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "映射名称不能为空")
@Schema(description = "模板名称", example = "商品导入映射模板", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "模板名称不能为空")
private String name;
/**
* 字段映射(JSON格式)
* 模板JSON
*/
@Schema(description = "字段映射(JSON格式)", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "字段映射不能为空")
@Schema(description = "模板JSON", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "模板JSON不能为空")
private String mapping;
}
@@ -4,22 +4,22 @@ import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 导入映射过滤DTO
* 导入映射模板过滤DTO
*/
@Data
@Schema(description = "导入映射过滤DTO")
@Schema(description = "导入映射模板过滤DTO")
public class ImportMappingFilterDTO {
/**
* 导入类型(product-商品 order-订单)
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
*/
@Schema(description = "导入类型", example = "product", allowableValues = {"product", "order"})
@Schema(description = "导入类型", example = "PRODUCT", allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS"})
private String type;
/**
* 映射名称(模糊查询)
* 模板名称(模糊查询)
*/
@Schema(description = "映射名称(模糊查询)", example = "商品导入")
@Schema(description = "模板名称(模糊查询)", example = "商品导入")
private String name;
}
@@ -5,23 +5,23 @@ import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 更新导入映射DTO
* 更新导入映射模板DTO
*/
@Data
@Schema(description = "更新导入映射DTO")
@Schema(description = "更新导入映射模板DTO")
public class UpdateImportMappingDTO {
/**
* 映射名称
* 模板名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板")
@Schema(description = "模板名称", example = "商品导入映射模板")
private String name;
/**
* 字段映射(JSON格式)
* 模板JSON
*/
@Schema(description = "字段映射(JSON格式)", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "字段映射不能为空")
@Schema(description = "模板JSON", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "模板JSON不能为空")
private String mapping;
}
@@ -47,7 +47,7 @@ public class CreateOrderDTO {
*/
@Schema(description = "下单时间", example = "2024-01-01T10:00:00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "下单时间不能为空")
private LocalDateTime orderDate;
private LocalDateTime orderTime;
/**
* 商品ID
@@ -63,17 +63,17 @@ public class CreateOrderDTO {
private Long productSpecId;
/**
* 商品名称(冗余存储)
* 链接商品名称(冗余存储)
*/
@Schema(description = "商品名称", example = "iPhone 15 Pro", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品名称不能为空")
private String productName;
@Schema(description = "链接商品名称", example = "iPhone 15 Pro", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "链接商品名称不能为空")
private String linkProductName;
/**
* 规格名称(冗余存储)
* 链接规格名称(冗余存储)
*/
@Schema(description = "规格名称", example = "256GB 深空黑色")
private String specName;
@Schema(description = "链接规格名称", example = "256GB 深空黑色")
private String linkSpecName;
/**
* 数量
@@ -47,11 +47,11 @@ public class OrderFilterDTO {
* 下单时间范围-开始时间
*/
@Schema(description = "下单时间范围-开始时间", example = "2024-01-01T00:00:00")
private LocalDateTime startOrderDate;
private LocalDateTime startOrderTime;
/**
* 下单时间范围-结束时间
*/
@Schema(description = "下单时间范围-结束时间", example = "2024-12-31T23:59:59")
private LocalDateTime endOrderDate;
private LocalDateTime endOrderTime;
}
@@ -45,7 +45,7 @@ public class UpdateOrderDTO {
*/
@Schema(description = "下单时间", example = "2024-01-01T10:00:00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "下单时间不能为空")
private LocalDateTime orderDate;
private LocalDateTime orderTime;
/**
* 商品ID
@@ -60,16 +60,16 @@ public class UpdateOrderDTO {
private Long productSpecId;
/**
* 商品名称(冗余存储)
* 链接商品名称(冗余存储)
*/
@Schema(description = "商品名称", example = "iPhone 15 Pro")
private String productName;
@Schema(description = "链接商品名称", example = "iPhone 15 Pro")
private String linkProductName;
/**
* 规格名称(冗余存储)
* 链接规格名称(冗余存储)
*/
@Schema(description = "规格名称", example = "256GB 深空黑色")
private String specName;
@Schema(description = "链接规格名称", example = "256GB 深空黑色")
private String linkSpecName;
/**
* 数量
@@ -1,7 +1,8 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order;
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
@@ -12,7 +13,7 @@ import lombok.Data;
public class CreateOrderStatusDTO {
/**
* 状态名称
* 状态名称(中文)
*/
@Schema(description = "状态名称", example = "待发货", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "状态名称不能为空")
@@ -21,7 +22,7 @@ public class CreateOrderStatusDTO {
/**
* 状态描述
*/
@Schema(description = "状态描述", example = "订单已创建,等待发货")
@Schema(description = "状态描述", example = "订单已创建,等待商家发货")
private String description;
/**
@@ -31,8 +32,10 @@ public class CreateOrderStatusDTO {
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
* 是否默认参与统计 0不参与 1参与
*/
@Schema(description = "是否启用", example = "1", allowableValues = {"0", "1"})
private Integer isActive;
@Schema(description = "是否默认参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否默认参与统计不能为空")
private Integer isDefaultStat;
}
@@ -1,4 +1,4 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order;
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
@@ -13,21 +13,7 @@ import lombok.Data;
public class UpdateOrderStatusDTO {
/**
* 状态ID
*/
@Schema(description = "状态ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "状态ID不能为空")
private Long id;
/**
* 状态码
*/
@Schema(description = "状态码", example = "0", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "状态码不能为空")
private Integer statusCode;
/**
* 状态名称
* 状态名称(中文)
*/
@Schema(description = "状态名称", example = "待发货", requiredMode = Schema.RequiredMode.REQUIRED)
@NotBlank(message = "状态名称不能为空")
@@ -36,7 +22,7 @@ public class UpdateOrderStatusDTO {
/**
* 状态描述
*/
@Schema(description = "状态描述", example = "订单已创建,等待发货")
@Schema(description = "状态描述", example = "订单已创建,等待商家发货")
private String description;
/**
@@ -46,8 +32,10 @@ public class UpdateOrderStatusDTO {
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
* 是否默认参与统计 0不参与 1参与
*/
@Schema(description = "是否启用", example = "1", allowableValues = {"0", "1"})
private Integer isActive;
@Schema(description = "是否默认参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否默认参与统计不能为空")
private Integer isDefaultStat;
}
@@ -0,0 +1,71 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.enums;
import lombok.Getter;
/**
* 订单状态枚举
*/
@Getter
public enum OrderStatus {
/**
* 未知状态
*/
UNKNOWN("未知状态"),
/**
* 待发货
*/
PENDING_SHIPMENT("待发货"),
/**
* 已发货
*/
SHIPPED("已发货"),
/**
* 已完成
*/
COMPLETED("已完成"),
/**
* 已取消
*/
CANCELLED("已取消"),
/**
* 退款中
*/
REFUNDING("退款中"),
/**
* 已退款
*/
REFUNDED("已退款");
/**
* 状态名称(中文)
*/
private final String name;
OrderStatus(String name) {
this.name = name;
}
/**
* 根据中文名称获取枚举
* @param name 中文名称
* @return 订单状态枚举,如果未找到则返回 UNKNOWN
*/
public static OrderStatus fromName(String name) {
if (name == null || name.trim().isEmpty()) {
return UNKNOWN;
}
for (OrderStatus status : values()) {
if (status.getName().equals(name.trim())) {
return status;
}
}
return UNKNOWN;
}
}
@@ -27,19 +27,19 @@ public class ImportMappingPO {
private Long companyId;
/**
* 导入类型(product-商品 order-订单)
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
*/
@TableField("type")
private String type;
/**
* 映射模板名称
* 映射名称
*/
@TableField("name")
private String name;
/**
* 字段映射(JSON格式)
* 映射JSON
*/
@TableField("mapping")
private String mapping;
@@ -58,16 +58,16 @@ public class OrderPO {
private Long productSpecId;
/**
* 商品名称(冗余存储)
* 链接商品名称(冗余存储)
*/
@TableField("product_name")
private String productName;
@TableField("link_product_name")
private String linkProductName;
/**
* 规格名称(冗余存储)
* 链接规格名称(冗余存储)
*/
@TableField("spec_name")
private String specName;
@TableField("link_spec_name")
private String linkSpecName;
/**
* 数量
@@ -96,8 +96,8 @@ public class OrderPO {
/**
* 下单时间
*/
@TableField("order_date")
private LocalDateTime orderDate;
@TableField("order_time")
private LocalDateTime orderTime;
/**
* 创建时间
@@ -15,7 +15,7 @@ import java.time.LocalDateTime;
public class OrderStatusPO {
/**
* 状态ID
* 订单状态ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@@ -27,7 +27,7 @@ public class OrderStatusPO {
private Long companyId;
/**
* 状态名称
* 状态名称(中文)
*/
@TableField("status_name")
private String statusName;
@@ -45,10 +45,10 @@ public class OrderStatusPO {
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
* 是否默认参与统计 0不参与 1参与
*/
@TableField("is_active")
private Integer isActive;
@TableField("is_default_stat")
private Integer isDefaultStat;
/**
* 创建时间
@@ -74,3 +74,4 @@ public class OrderStatusPO {
@TableField("update_by")
private Long updateBy;
}
@@ -6,16 +6,16 @@ import lombok.Data;
import java.time.LocalDateTime;
/**
* 导入映射VO
* 导入映射模板VO
*/
@Data
@Schema(description = "导入映射VO")
@Schema(description = "导入映射模板VO")
public class ImportMappingVO {
/**
* 映射ID
* 模板ID
*/
@Schema(description = "映射ID", example = "1")
@Schema(description = "模板ID", example = "1")
private Long id;
/**
@@ -25,21 +25,21 @@ public class ImportMappingVO {
private Long companyId;
/**
* 导入类型(product-商品 order-订单)
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
*/
@Schema(description = "导入类型", example = "product")
@Schema(description = "导入类型", example = "PRODUCT")
private String type;
/**
* 映射名称
* 模板名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板")
@Schema(description = "模板名称", example = "商品导入映射模板")
private String name;
/**
* 字段映射(JSON格式)
* 模板JSON
*/
@Schema(description = "字段映射(JSON格式)", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}")
@Schema(description = "模板JSON", example = "{\"商品名称\":\"name\",\"价格(元)\":\"price\"}")
private String mapping;
/**
@@ -13,9 +13,9 @@ import java.time.LocalDateTime;
public class OrderStatusVO {
/**
* 状态ID
* 订单状态ID
*/
@Schema(description = "状态ID", example = "1")
@Schema(description = "订单状态ID", example = "1")
private Long id;
/**
@@ -25,13 +25,7 @@ public class OrderStatusVO {
private Long companyId;
/**
* 状态码
*/
@Schema(description = "状态码", example = "0")
private Integer statusCode;
/**
* 状态名称
* 状态名称(中文)
*/
@Schema(description = "状态名称", example = "待发货")
private String statusName;
@@ -39,7 +33,7 @@ public class OrderStatusVO {
/**
* 状态描述
*/
@Schema(description = "状态描述", example = "订单已创建,等待发货")
@Schema(description = "状态描述", example = "订单已创建,等待商家发货")
private String description;
/**
@@ -49,10 +43,10 @@ public class OrderStatusVO {
private Integer sortOrder;
/**
* 是否启用 0禁用 1启用
* 是否默认参与统计 0不参与 1参与
*/
@Schema(description = "是否启用", example = "1")
private Integer isActive;
@Schema(description = "是否默认参与统计", example = "1")
private Integer isDefaultStat;
/**
* 创建时间
@@ -78,3 +72,4 @@ public class OrderStatusVO {
@Schema(description = "更新人ID", example = "1")
private Long updateBy;
}
@@ -50,7 +50,7 @@ public class OrderVO {
private Long statusId;
/**
* 订单状态名称
* 订单状态名称(中文)
*/
@Schema(description = "订单状态名称", example = "待发货")
private String statusName;
@@ -65,7 +65,7 @@ public class OrderVO {
* 下单时间
*/
@Schema(description = "下单时间", example = "2024-01-01T10:00:00")
private LocalDateTime orderDate;
private LocalDateTime orderTime;
/**
* 创建时间
@@ -104,16 +104,16 @@ public class OrderVO {
private Long productSpecId;
/**
* 商品名称(冗余存储)
* 链接商品名称(冗余存储)
*/
@Schema(description = "商品名称", example = "iPhone 15 Pro")
private String productName;
@Schema(description = "链接商品名称", example = "iPhone 15 Pro")
private String linkProductName;
/**
* 规格名称(冗余存储)
* 链接规格名称(冗余存储)
*/
@Schema(description = "规格名称", example = "256GB 深空黑色")
private String specName;
@Schema(description = "链接规格名称", example = "256GB 深空黑色")
private String linkSpecName;
/**
* 数量
@@ -10,36 +10,36 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportMappingPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportMappingVO;
/**
* 导入映射服务接口
* 导入映射模板服务接口
*/
public interface ImportMappingService extends IService<ImportMappingPO> {
/**
* 创建导入映射模板
*
* @param createImportMappingDTO 创建导入映射DTO
* @return 导入映射VO
* @param createImportMappingDTO 创建导入映射模板DTO
* @return 导入映射模板VO
*/
ImportMappingVO createImportMapping(CreateImportMappingDTO createImportMappingDTO);
/**
* 更新导入映射模板
*
* @param updateImportMappingDTO 更新导入映射DTO
* @param id 映射ID
* @return 导入映射VO
* @param updateImportMappingDTO 更新导入映射模板DTO
* @param id 模板ID
* @return 导入映射模板VO
*/
ImportMappingVO updateImportMapping(UpdateImportMappingDTO updateImportMappingDTO, Long id);
/**
* 删除导入映射
* 删除导入映射模板
*
* @param id 映射ID
* @param id 模板ID
*/
void deleteImportMapping(Long id);
/**
* 分页获取导入映射列表
* 分页获取导入映射模板列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果
@@ -1,7 +1,9 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.UpdateOrderStatusDTO;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.UpdateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderStatusVO;
import java.util.List;
@@ -9,45 +11,45 @@ import java.util.List;
/**
* 订单状态服务接口
*/
public interface OrderStatusService {
public interface OrderStatusService extends IService<OrderStatusPO> {
/**
* 创建订单状态
*
* @param createOrderStatusDTO 创建订单状态DTO
* @return 订单状态VO
*/
Long createOrderStatus(CreateOrderStatusDTO dto);
OrderStatusVO createOrderStatus(CreateOrderStatusDTO createOrderStatusDTO);
/**
* 更新订单状态
*
* @param updateOrderStatusDTO 更新订单状态DTO
* @param id 订单状态ID
* @return 订单状态VO
*/
void updateOrderStatus(UpdateOrderStatusDTO dto);
OrderStatusVO updateOrderStatus(UpdateOrderStatusDTO updateOrderStatusDTO, Long id);
/**
* 删除订单状态
*
* @param id 订单状态ID
*/
void deleteOrderStatus(Long id);
/**
* 根据ID查询订单状态
* 获取所有订单状态(当前公司)
*
* @return 订单状态列表
*/
List<OrderStatusVO> getAllOrderStatuses();
/**
* 根据ID获取订单状态
*
* @param id 订单状态ID
* @return 订单状态VO
*/
OrderStatusVO getOrderStatusById(Long id);
/**
* 查询启用的订单状态列表
*/
List<OrderStatusVO> getActiveOrderStatusList();
/**
* 查询所有订单状态列表
*/
List<OrderStatusVO> getAllOrderStatusList();
/**
* 初始化公司订单状态数据
*/
void initOrderStatusForCompany(Long companyId);
/**
* 初始化当前公司订单状态数据
*/
void initOrderStatusForCurrentCompany();
}
@@ -24,7 +24,7 @@ import java.util.List;
import java.util.stream.Collectors;
/**
* 导入映射服务实现类
* 导入映射模板服务实现类
*/
@Service
public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, ImportMappingPO> implements ImportMappingService {
@@ -47,16 +47,16 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证同一公司、同一类型、同一名称是否已存在映射(根据唯一索引)
// 验证同一公司、同一类型、同一名称是否已存在模板(根据唯一索引)
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ImportMappingPO::getCompanyId, companyId)
.eq(ImportMappingPO::getType, createImportMappingDTO.getType())
.eq(ImportMappingPO::getName, createImportMappingDTO.getName());
if (this.count(wrapper) > 0) {
throw new BusinessException("该类型的导入映射名称已存在,请使用其他名称或更新接口");
throw new BusinessException("该类型的导入映射模板名称已存在,请使用其他名称或更新接口");
}
// 创建导入映射
// 创建导入映射模板
ImportMappingPO importMappingPO = new ImportMappingPO();
BeanUtils.copyProperties(createImportMappingDTO, importMappingPO);
importMappingPO.setCompanyId(companyId);
@@ -78,19 +78,19 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
@Override
@Transactional
public ImportMappingVO updateImportMapping(UpdateImportMappingDTO updateImportMappingDTO, Long id) {
// 验证映射是否存在
// 验证模板是否存在
ImportMappingPO existingMapping = this.getById(id);
if (existingMapping == null) {
throw new BusinessException("导入映射不存在");
throw new BusinessException("导入映射模板不存在");
}
// 验证公司权限
Long companyId = currentUserContext.getCurrentCompanyId();
if (!existingMapping.getCompanyId().equals(companyId)) {
throw new BusinessException("无权限操作此映射");
throw new BusinessException("无权限操作此模板");
}
// 如果更新了名称,验证新名称是否与同一公司、同一类型的其他映射冲突
// 如果更新了名称,验证新名称是否与同一公司、同一类型的其他模板冲突
if (updateImportMappingDTO.getName() != null &&
!updateImportMappingDTO.getName().equals(existingMapping.getName())) {
LambdaQueryWrapper<ImportMappingPO> nameCheckWrapper = new LambdaQueryWrapper<>();
@@ -99,11 +99,11 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
.eq(ImportMappingPO::getName, updateImportMappingDTO.getName())
.ne(ImportMappingPO::getId, id);
if (this.count(nameCheckWrapper) > 0) {
throw new BusinessException("该类型的导入映射名称已存在,请使用其他名称");
throw new BusinessException("该类型的导入映射模板名称已存在,请使用其他名称");
}
}
// 更新映射
// 更新模板
ImportMappingPO importMappingPO = new ImportMappingPO();
BeanUtils.copyProperties(updateImportMappingDTO, importMappingPO);
importMappingPO.setId(id);
@@ -123,24 +123,24 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
@Override
@Transactional
public void deleteImportMapping(Long id) {
// 验证映射是否存在
// 验证模板是否存在
ImportMappingPO existingMapping = this.getById(id);
if (existingMapping == null) {
throw new BusinessException("导入映射不存在");
throw new BusinessException("导入映射模板不存在");
}
// 验证公司权限
Long companyId = currentUserContext.getCurrentCompanyId();
if (!existingMapping.getCompanyId().equals(companyId)) {
throw new BusinessException("无权限操作此映射");
throw new BusinessException("无权限操作此模板");
}
// 删除映射
// 删除模板
this.removeById(id);
}
/**
* 分页获取导入映射列表
* 分页获取导入映射模板列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果VO
@@ -1,7 +1,6 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
@@ -11,12 +10,10 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ShopProductRelationMapper;
import org.springframework.beans.BeanUtils;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.CreateOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportTaskPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopProductRelationPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
@@ -29,6 +26,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
@@ -60,6 +58,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private String fieldLabel;
private String fileFieldName;
// 无参构造函数(Jackson需要)
public MappingField() {
}
public Boolean getRequired() {
return required;
}
@@ -93,39 +95,94 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
/**
* 状态映射定义
*/
private static class StatusMapping {
private String csvStatus;
private String mappedStatus;
// 无参构造函数(Jackson需要)
public StatusMapping() {
}
public String getCsvStatus() {
return csvStatus;
}
public void setCsvStatus(String csvStatus) {
this.csvStatus = csvStatus;
}
public String getMappedStatus() {
return mappedStatus;
}
public void setMappedStatus(String mappedStatus) {
this.mappedStatus = mappedStatus;
}
}
/**
* 映射配置(包含字段映射和状态映射)
*/
private static class MappingConfig {
private List<MappingField> fieldMapping;
private List<StatusMapping> statusMapping;
// 无参构造函数(Jackson需要)
public MappingConfig() {
}
public List<MappingField> getFieldMapping() {
return fieldMapping;
}
public void setFieldMapping(List<MappingField> fieldMapping) {
this.fieldMapping = fieldMapping;
}
public List<StatusMapping> getStatusMapping() {
return statusMapping;
}
public void setStatusMapping(List<StatusMapping> statusMapping) {
this.statusMapping = statusMapping;
}
}
private static final Logger logger = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
private final ImportTaskService importTaskService;
private final ProductSpecService productSpecService;
private final OrderStatusMapper orderStatusMapper;
private final OrderMapper orderMapper;
private final ProductMapper productMapper;
private final ShopService shopService;
private final ShopProductRelationMapper shopProductRelationMapper;
private final SseNotificationService sseNotificationService;
private final ObjectMapper objectMapper;
private final OrderStatusService orderStatusService;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
OrderService orderService,
ProductService productService,
ProductSpecService productSpecService,
OrderStatusService orderStatusService,
OrderStatusMapper orderStatusMapper,
OrderMapper orderMapper,
ProductMapper productMapper,
ShopService shopService,
ShopProductRelationMapper shopProductRelationMapper,
SseNotificationService sseNotificationService,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
OrderStatusService orderStatusService) {
this.importTaskService = importTaskService;
this.productSpecService = productSpecService;
this.orderStatusMapper = orderStatusMapper;
this.orderMapper = orderMapper;
this.productMapper = productMapper;
this.shopService = shopService;
this.shopProductRelationMapper = shopProductRelationMapper;
this.sseNotificationService = sseNotificationService;
this.objectMapper = objectMapper;
this.orderStatusService = orderStatusService;
}
/**
@@ -178,8 +235,17 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param task 导入任务
*/
private void processOrderImport(ImportTaskPO task) throws IOException {
// 解析字段映射
Map<String, MappingField> mapping = parseMapping(task.getMapping());
// 解析映射配置(包含字段映射和状态映射)
MappingConfig mappingConfig = parseMappingConfig(task.getMapping());
Map<String, MappingField> fieldMapping = mappingConfig.getFieldMapping().stream()
.collect(Collectors.toMap(MappingField::getFieldName, field -> field, (v1, v2) -> v1));
Map<String, String> statusMapping = mappingConfig.getStatusMapping() != null
? mappingConfig.getStatusMapping().stream()
.collect(Collectors.toMap(
sm -> sm.getCsvStatus() != null ? sm.getCsvStatus().trim() : "",
StatusMapping::getMappedStatus,
(v1, v2) -> v1))
: java.util.Collections.emptyMap();
Long companyId = task.getCompanyId();
// 读取CSV文件
@@ -203,19 +269,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
throw new BusinessException("CSV文件不存在: " + task.getFilePath() + " (实际查找路径: " + csvFile.getAbsolutePath() + ")");
}
// 获取默认订单状态(使用第一个启用的状态)
// 注意:在消费者线程中,不能使用CurrentUserContext,所以直接使用Mapper查询
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> statusWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
statusWrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getIsActive, 1)
.orderByAsc(OrderStatusPO::getSortOrder)
.last("LIMIT 1");
OrderStatusPO defaultStatus = orderStatusMapper.selectOne(statusWrapper);
if (defaultStatus == null) {
throw new BusinessException("没有可用的订单状态,请先创建订单状态");
}
Long defaultStatusId = defaultStatus.getId();
// 获取默认订单状态ID(尝试查找"未知状态",如果不存在则使用第一个状态)
Long defaultStatusId = getDefaultOrderStatusId(companyId);
int totalCount = 0;
int successCount = 0;
@@ -238,7 +293,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 记录CSV表头,用于调试
Map<String, Integer> headerMap = csvParser.getHeaderMap();
logger.info("CSV表头信息: {}", headerMap);
logger.info("字段映射信息: {}", mapping);
logger.info("字段映射信息: {}", fieldMapping);
logger.info("状态映射信息: {}", statusMapping);
List<CSVRecord> records = csvParser.getRecords();
totalCount = records.size();
@@ -252,7 +308,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
try {
// 解析CSV行数据
CreateOrderDTO orderDTO = parseOrderFromCSV(record, mapping, task.getShopId(), defaultStatusId, companyId, task.getCreateBy());
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(), defaultStatusId, companyId, task.getCreateBy());
// 创建订单(复用OrderService.createOrder的业务逻辑,但不依赖CurrentUserContext)
createOrderWithoutContext(orderDTO, companyId, task.getCreateBy());
@@ -284,29 +340,78 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
/**
* 解析字段映射
* 解析映射配置(包含字段映射和状态映射)
*
* @param mappingJson 映射JSON字符串
* @return 字段映射Map(实体字段名 -> 映射字段定义)
* @return 映射配置对象
*/
private Map<String, MappingField> parseMapping(String mappingJson) {
private MappingConfig parseMappingConfig(String mappingJson) {
try {
if (mappingJson == null || mappingJson.trim().isEmpty()) {
throw new BusinessException("字段映射不能为空");
throw new BusinessException("映射配置不能为空");
}
// 解析JSON数组,格式:[{"required": false, "fieldName": "productName", "fieldLabel": "商品名称", "fileFieldName": "商品"}, ...]
List<MappingField> mappingFields = objectMapper.readValue(mappingJson,
new TypeReference<List<MappingField>>() {});
if (mappingFields == null || mappingFields.isEmpty()) {
// 解析新的JSON结构,格式:
// {
// "fieldMapping": [...],
// "statusMapping": [...]
// }
// 使用JsonNode先解析,然后手动构建对象,避免内部类反序列化问题
com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(mappingJson);
MappingConfig config = new MappingConfig();
// 解析字段映射
com.fasterxml.jackson.databind.JsonNode fieldMappingNode = rootNode.get("fieldMapping");
if (fieldMappingNode != null && fieldMappingNode.isArray()) {
List<MappingField> mappingFields = new java.util.ArrayList<>();
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
MappingField field = new MappingField();
if (fieldNode.has("required")) {
field.setRequired(fieldNode.get("required").asBoolean());
}
if (fieldNode.has("fieldName")) {
field.setFieldName(fieldNode.get("fieldName").asText());
}
if (fieldNode.has("fieldLabel")) {
field.setFieldLabel(fieldNode.get("fieldLabel").asText());
}
if (fieldNode.has("fileFieldName")) {
field.setFileFieldName(fieldNode.get("fileFieldName").asText());
}
mappingFields.add(field);
}
config.setFieldMapping(mappingFields);
}
// 解析状态映射
com.fasterxml.jackson.databind.JsonNode statusMappingNode = rootNode.get("statusMapping");
if (statusMappingNode != null && statusMappingNode.isArray()) {
List<StatusMapping> statusMappings = new java.util.ArrayList<>();
for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) {
StatusMapping statusMapping = new StatusMapping();
if (statusNode.has("csvStatus")) {
statusMapping.setCsvStatus(statusNode.get("csvStatus").asText());
}
if (statusNode.has("mappedStatus")) {
statusMapping.setMappedStatus(statusNode.get("mappedStatus").asText());
}
statusMappings.add(statusMapping);
}
config.setStatusMapping(statusMappings);
}
if (config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) {
throw new BusinessException("字段映射不能为空");
}
// 转换为Map,key为fieldName,value为MappingField对象
return mappingFields.stream()
.collect(Collectors.toMap(MappingField::getFieldName, field -> field, (v1, v2) -> v1));
return config;
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
logger.error("解析映射配置失败(JSON格式错误),JSON: {}", mappingJson, e);
throw new BusinessException("解析映射配置失败: JSON格式错误 - " + e.getMessage());
} catch (Exception e) {
throw new BusinessException("解析字段映射失败: " + e.getMessage());
logger.error("解析映射配置失败,JSON: {}", mappingJson, e);
throw new BusinessException("解析映射配置失败: " + e.getMessage());
}
}
@@ -314,33 +419,35 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* 从CSV记录解析订单数据
*
* @param record CSV记录
* @param mapping 字段映射(fieldName -> MappingField)
* @param fieldMapping 字段映射(fieldName -> MappingField)
* @param statusMapping 状态映射(CSV状态文本 -> 状态名称)
* @param shopId 店铺ID
* @param defaultStatusId 默认订单状态ID
* @param companyId 公司ID
* @param createBy 创建人ID
* @return 创建订单DTO
*/
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, MappingField> mapping,
Long shopId, Long defaultStatusId, Long companyId, Long createBy) {
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, MappingField> fieldMapping,
Map<String, String> statusMapping, Long shopId, Long defaultStatusId,
Long companyId, Long createBy) {
CreateOrderDTO orderDTO = new CreateOrderDTO();
orderDTO.setShopId(shopId);
orderDTO.setStatusId(defaultStatusId);
// 获取映射字段定义
MappingField specCodeField = mapping.get("specCode"); // 规格编码
MappingField receivedAmountField = mapping.get("receivedAmount"); // 商家实收金额
MappingField productQuantityField = mapping.get("productQuantity"); // 商品数量
MappingField orderStatusField = mapping.get("orderStatus"); // 订单状态
MappingField productNameField = mapping.get("productName"); // 商品名称
MappingField productCodeField = mapping.get("productCode"); // 商品编码
MappingField specNameField = mapping.get("specName"); // 规格名称
MappingField platformOrderNoField = mapping.get("platformOrderNo"); // 平台订单号
MappingField orderDateField = mapping.get("orderDate"); // 下单时间
// 获取映射字段定义(使用下划线命名)
MappingField specCodeField = fieldMapping.get("spec_code"); // 规格编码
MappingField receivedAmountField = fieldMapping.get("received_amount"); // 商家实收金额
MappingField productQuantityField = fieldMapping.get("product_quantity"); // 商品数量
MappingField orderStatusField = fieldMapping.get("status"); // 订单状态
MappingField linkProductNameField = fieldMapping.get("link_product_name"); // 链接商品名称
MappingField productCodeField = fieldMapping.get("product_code"); // 商品编码(可选字段)
MappingField linkSpecNameField = fieldMapping.get("link_spec_name"); // 链接规格名称
MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); // 平台订单号
MappingField orderDateField = fieldMapping.get("order_time"); // 下单时间
// 调试日志:记录字段映射
if (logger.isDebugEnabled()) {
logger.debug("字段映射 - specCode: {}, receivedAmount: {}, productQuantity: {}",
logger.debug("字段映射 - spec_code: {}, received_amount: {}, product_quantity: {}",
specCodeField != null ? specCodeField.getFileFieldName() : null,
receivedAmountField != null ? receivedAmountField.getFileFieldName() : null,
productQuantityField != null ? productQuantityField.getFileFieldName() : null);
@@ -401,13 +508,13 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
// 解析可选字段(先解析,用于后续创建商品和规格)
String productName = getValue(record, productNameField);
String productName = getValue(record, linkProductNameField);
productName = productName != null ? productName.trim() : null;
String productCode = getValue(record, productCodeField);
productCode = productCode != null ? productCode.trim() : null;
String specName = getValue(record, specNameField);
String specName = getValue(record, linkSpecNameField);
specName = specName != null ? specName.trim() : null;
// 首先通过规格编码查找商品规格
@@ -463,19 +570,19 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
orderDTO.setProductSpecId(productSpec.getId());
orderDTO.setCostPrice(productSpec.getCostPrice());
// 设置商品名称和规格名称
// 设置链接商品名称和链接规格名称
if (productName != null && !productName.isEmpty()) {
orderDTO.setProductName(productName);
orderDTO.setLinkProductName(productName);
} else {
// 如果CSV中没有商品名称,从商品规格关联的商品中获取
ProductPO product = productMapper.selectById(productSpec.getProductId());
orderDTO.setProductName(product != null ? product.getName() : "");
orderDTO.setLinkProductName(product != null ? product.getName() : "");
}
if (specName != null && !specName.isEmpty()) {
orderDTO.setSpecName(specName);
orderDTO.setLinkSpecName(specName);
} else {
orderDTO.setSpecName(productSpec.getName());
orderDTO.setLinkSpecName(productSpec.getName());
}
String platformOrderNo = getValue(record, platformOrderNoField);
@@ -492,27 +599,55 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 解析订单状态(如果提供了映射)
String orderStatusName = getValue(record, orderStatusField);
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
String trimmedStatus = orderStatusName.trim();
Long statusId = null;
// 首先尝试通过状态映射转换(statusMapping中存储的是状态名称)
if (statusMapping != null && !statusMapping.isEmpty()) {
String mappedStatusName = statusMapping.get(trimmedStatus);
if (mappedStatusName != null) {
// 根据状态名称查找状态ID
statusId = findOrderStatusIdByName(companyId, mappedStatusName);
if (statusId != null) {
logger.debug("通过状态映射转换: '{}' -> '{}' -> ID: {}", trimmedStatus, mappedStatusName, statusId);
} else {
logger.warn("状态映射值 '{}' 对应的状态名称 '{}' 未找到", trimmedStatus, mappedStatusName);
}
}
}
// 如果状态映射没有找到,尝试直接通过状态名称查找
if (statusId == null) {
statusId = findOrderStatusIdByName(companyId, trimmedStatus);
if (statusId != null) {
logger.debug("通过状态名称匹配订单状态: '{}' -> ID: {}", trimmedStatus, statusId);
}
}
// 如果找到了有效的状态,则使用;否则使用默认状态
if (statusId != null) {
orderDTO.setStatusId(statusId);
} else {
logger.warn("无法识别订单状态: '{}',使用默认状态ID: {}", trimmedStatus, defaultStatusId);
orderDTO.setStatusId(defaultStatusId);
}
}
// 解析下单时间(支持多种格式)
String orderDateStr = getValue(record, orderDateField);
if (orderDateStr != null && !orderDateStr.trim().isEmpty()) {
LocalDateTime orderDate = parseDateTime(orderDateStr.trim());
if (orderDate != null) {
orderDTO.setOrderDate(orderDate);
logger.info("成功解析下单时间: '{}' -> {}", orderDateStr.trim(), orderDate);
LocalDateTime orderTime = parseDateTime(orderDateStr.trim());
if (orderTime != null) {
orderDTO.setOrderTime(orderTime);
logger.info("成功解析下单时间: '{}' -> {}", orderDateStr.trim(), orderTime);
} else {
logger.warn("无法解析下单时间: '{}' (可能格式不支持),使用当前时间", orderDateStr);
orderDTO.setOrderDate(LocalDateTime.now());
orderDTO.setOrderTime(LocalDateTime.now());
}
} else {
// 如果没有提供下单时间,使用当前时间
logger.debug("未提供下单时间字段,使用当前时间");
orderDTO.setOrderDate(LocalDateTime.now());
orderDTO.setOrderTime(LocalDateTime.now());
}
return orderDTO;
@@ -873,13 +1008,13 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
order.setStatusId(createOrderDTO.getStatusId());
order.setProductId(createOrderDTO.getProductId());
order.setProductSpecId(createOrderDTO.getProductSpecId());
order.setProductName(createOrderDTO.getProductName());
order.setSpecName(createOrderDTO.getSpecName());
order.setLinkProductName(createOrderDTO.getLinkProductName());
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setCostPrice(createOrderDTO.getCostPrice());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setOrderDate(createOrderDTO.getOrderDate());
order.setOrderTime(createOrderDTO.getOrderTime());
order.setCreateBy(createBy);
// 保存订单
@@ -934,23 +1069,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
/**
* 通过订单状态名称查找订单状态ID
*
* @param statusName 状态名称
* @param companyId 公司ID
* @return 状态ID
*/
private Long findOrderStatusByName(String statusName, Long companyId) {
// 根据公司ID和状态名称查询订单状态
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, statusName)
.eq(OrderStatusPO::getIsActive, 1);
OrderStatusPO status = orderStatusMapper.selectOne(wrapper);
return status != null ? status.getId() : null;
}
/**
* 更新任务状态
@@ -1052,5 +1170,53 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
logger.warn("无法确定文件编码,使用默认GBK");
return java.nio.charset.Charset.forName("GBK");
}
/**
* 获取默认订单状态ID(尝试查找"未知状态",如果不存在则使用第一个状态)
*
* @param companyId 公司ID
* @return 默认订单状态ID
*/
private Long getDefaultOrderStatusId(Long companyId) {
// 首先尝试查找"未知状态"
Long statusId = findOrderStatusIdByName(companyId, "未知状态");
if (statusId != null) {
return statusId;
}
// 如果找不到"未知状态",则使用第一个状态(按排序顺序)
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.orderByAsc(OrderStatusPO::getSortOrder)
.orderByDesc(OrderStatusPO::getCreateTime)
.last("LIMIT 1");
OrderStatusPO firstStatus = orderStatusService.getOne(wrapper);
if (firstStatus != null) {
logger.info("未找到'未知状态',使用第一个状态: {} (ID: {})", firstStatus.getStatusName(), firstStatus.getId());
return firstStatus.getId();
}
throw new BusinessException("公司中没有可用的订单状态,请先创建订单状态");
}
/**
* 根据状态名称查找订单状态ID
*
* @param companyId 公司ID
* @param statusName 状态名称
* @return 订单状态ID,如果不存在则返回null
*/
private Long findOrderStatusIdByName(Long companyId, String statusName) {
if (statusName == null || statusName.trim().isEmpty()) {
return null;
}
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, statusName.trim());
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
}
@@ -21,7 +21,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.BatchImportResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
@@ -41,13 +43,16 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
private final ShopService shopService;
private final ProductService productService;
private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService;
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService) {
ProductService productService, ProductSpecService productSpecService,
OrderStatusService orderStatusService) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService;
}
/**
@@ -83,6 +88,12 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
}
}
// 验证订单状态是否存在且属于当前公司
OrderStatusPO orderStatus = orderStatusService.getById(createOrderDTO.getStatusId());
if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) {
throw new BusinessException("订单状态不存在");
}
// 验证平台订单号是否重复(如果提供了的话)
if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) {
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
@@ -101,13 +112,13 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
order.setStatusId(createOrderDTO.getStatusId());
order.setProductId(createOrderDTO.getProductId());
order.setProductSpecId(createOrderDTO.getProductSpecId());
order.setProductName(createOrderDTO.getProductName());
order.setSpecName(createOrderDTO.getSpecName());
order.setLinkProductName(createOrderDTO.getLinkProductName());
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setCostPrice(createOrderDTO.getCostPrice());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setOrderDate(createOrderDTO.getOrderDate());
order.setOrderTime(createOrderDTO.getOrderTime());
order.setCreateBy(currentUserContext.getCurrentUserId());
// 保存订单
@@ -223,16 +234,16 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
if (filter.getMaxReceivedAmount() != null) {
wrapper.le(OrderPO::getReceivedAmount, filter.getMaxReceivedAmount());
}
if (filter.getStartOrderDate() != null) {
wrapper.ge(OrderPO::getOrderDate, filter.getStartOrderDate());
if (filter.getStartOrderTime() != null) {
wrapper.ge(OrderPO::getOrderTime, filter.getStartOrderTime());
}
if (filter.getEndOrderDate() != null) {
wrapper.le(OrderPO::getOrderDate, filter.getEndOrderDate());
if (filter.getEndOrderTime() != null) {
wrapper.le(OrderPO::getOrderTime, filter.getEndOrderTime());
}
}
// 排序
wrapper.orderByDesc(OrderPO::getOrderDate)
wrapper.orderByDesc(OrderPO::getOrderTime)
.orderByDesc(OrderPO::getCreateTime);
// 执行分页查询
@@ -321,9 +332,13 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
OrderVO orderVO = new OrderVO();
BeanUtils.copyProperties(order, orderVO);
// 设置状态名称(这里需要根据statusId查询订单状态表获取状态名称)
// 暂时设置为状态ID,实际应该查询订单状态表
orderVO.setStatusName("状态ID: " + order.getStatusId());
// 设置状态名称
if (order.getStatusId() != null) {
OrderStatusPO orderStatus = orderStatusService.getById(order.getStatusId());
if (orderStatus != null) {
orderVO.setStatusName(orderStatus.getStatusName());
}
}
// 设置店铺名称
ShopPO shop = shopService.getById(order.getShopId());
@@ -1,13 +1,14 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.UpdateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.orderstatus.UpdateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderStatusVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
@@ -20,181 +21,177 @@ import java.util.stream.Collectors;
* 订单状态服务实现类
*/
@Service
@RequiredArgsConstructor
public class OrderStatusServiceImpl implements OrderStatusService {
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusPO> implements OrderStatusService {
private final OrderStatusMapper orderStatusMapper;
private final CurrentUserContext currentUserContext;
public OrderStatusServiceImpl(CurrentUserContext currentUserContext) {
this.currentUserContext = currentUserContext;
}
/**
* 创建订单状态
* @param dto 创建订单状态DTO
* @return 订单状态ID
*
* @param createOrderStatusDTO 创建订单状态DTO
* @return 订单状态VO
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Long createOrderStatus(CreateOrderStatusDTO dto) {
// 检查状态名称是否重复
@Transactional
public OrderStatusVO createOrderStatus(CreateOrderStatusDTO createOrderStatusDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证状态名称是否重复(同一公司内)
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, currentUserContext.getCurrentCompanyId())
.eq(OrderStatusPO::getStatusName, dto.getStatusName());
if (orderStatusMapper.selectCount(wrapper) > 0) {
throw new RuntimeException("该状态名称已存在");
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, createOrderStatusDTO.getStatusName());
if (this.count(wrapper) > 0) {
throw new BusinessException("状态名称已存在");
}
OrderStatusPO po = new OrderStatusPO();
BeanUtils.copyProperties(dto, po);
po.setCompanyId(currentUserContext.getCurrentCompanyId());
po.setCreateBy(currentUserContext.getCurrentUserId());
po.setUpdateBy(currentUserContext.getCurrentUserId());
orderStatusMapper.insert(po);
return po.getId();
// 创建订单状态
OrderStatusPO orderStatus = new OrderStatusPO();
BeanUtils.copyProperties(createOrderStatusDTO, orderStatus);
orderStatus.setCompanyId(companyId);
// 设置默认值
if (orderStatus.getSortOrder() == null) {
orderStatus.setSortOrder(0);
}
if (orderStatus.getIsDefaultStat() == null) {
orderStatus.setIsDefaultStat(1);
}
// 设置创建人ID
orderStatus.setCreateBy(currentUserContext.getCurrentUserId());
// 保存订单状态
this.save(orderStatus);
// 转换为VO并返回
return convertToVO(orderStatus);
}
/**
* 更新订单状态
* @param dto 更新订单状态DTO
*
* @param updateOrderStatusDTO 更新订单状态DTO
* @param id 订单状态ID
* @return 订单状态VO
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void updateOrderStatus(UpdateOrderStatusDTO dto) {
OrderStatusPO po = new OrderStatusPO();
BeanUtils.copyProperties(dto, po);
po.setUpdateBy(currentUserContext.getCurrentUserId());
orderStatusMapper.updateById(po);
@Transactional
public OrderStatusVO updateOrderStatus(UpdateOrderStatusDTO updateOrderStatusDTO, Long id) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证订单状态是否存在
OrderStatusPO existingStatus = this.getById(id);
if (existingStatus == null || !existingStatus.getCompanyId().equals(companyId)) {
throw new BusinessException("订单状态不存在");
}
// 验证状态名称是否重复(排除当前记录)
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, updateOrderStatusDTO.getStatusName())
.ne(OrderStatusPO::getId, id);
if (this.count(wrapper) > 0) {
throw new BusinessException("状态名称已存在");
}
// 更新订单状态
OrderStatusPO orderStatus = new OrderStatusPO();
BeanUtils.copyProperties(updateOrderStatusDTO, orderStatus);
orderStatus.setId(id);
orderStatus.setCompanyId(companyId);
// 设置更新人ID
orderStatus.setUpdateBy(currentUserContext.getCurrentUserId());
// 更新订单状态
this.updateById(orderStatus);
// 转换为VO并返回
return convertToVO(orderStatus);
}
/**
* 删除订单状态
*
* @param id 订单状态ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
@Transactional
public void deleteOrderStatus(Long id) {
// 硬删除订单状态(外键约束会自动处理相关数据)
orderStatusMapper.deleteById(id);
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证订单状态是否存在
OrderStatusPO existingStatus = this.getById(id);
if (existingStatus == null || !existingStatus.getCompanyId().equals(companyId)) {
throw new BusinessException("订单状态不存在");
}
// 检查是否有订单使用此状态
// TODO: 这里可以添加检查逻辑,如果有订单使用此状态,可以阻止删除或提示
// 删除订单状态
this.removeById(id);
}
/**
* 根据ID查询订单状态
* 获取所有订单状态(当前公司)
*
* @return 订单状态列表
*/
@Override
public List<OrderStatusVO> getAllOrderStatuses() {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 查询当前公司的所有订单状态
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.orderByAsc(OrderStatusPO::getSortOrder)
.orderByDesc(OrderStatusPO::getCreateTime);
List<OrderStatusPO> statusList = this.list(wrapper);
// 转换为VO列表
return statusList.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
/**
* 根据ID获取订单状态
*
* @param id 订单状态ID
* @return 订单状态VO
*/
@Override
public OrderStatusVO getOrderStatusById(Long id) {
OrderStatusPO po = orderStatusMapper.selectById(id);
if (po == null) {
return null;
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证订单状态是否存在
OrderStatusPO orderStatus = this.getById(id);
if (orderStatus == null || !orderStatus.getCompanyId().equals(companyId)) {
throw new BusinessException("订单状态不存在");
}
// 转换为VO并返回
return convertToVO(orderStatus);
}
/**
* 转换为VO
*/
private OrderStatusVO convertToVO(OrderStatusPO orderStatus) {
OrderStatusVO vo = new OrderStatusVO();
BeanUtils.copyProperties(po, vo);
BeanUtils.copyProperties(orderStatus, vo);
return vo;
}
/**
* 获取所有启用的订单状态列表
* @return 订单状态VO列表
*/
@Override
public List<OrderStatusVO> getActiveOrderStatusList() {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, currentUserContext.getCurrentCompanyId())
.eq(OrderStatusPO::getIsActive, 1) // 1表示启用状态
.orderByAsc(OrderStatusPO::getSortOrder);
List<OrderStatusPO> poList = orderStatusMapper.selectList(wrapper);
return poList.stream()
.map(po -> {
OrderStatusVO vo = new OrderStatusVO();
BeanUtils.copyProperties(po, vo);
return vo;
})
.collect(Collectors.toList());
}
/**
* 获取所有订单状态列表
* @return 订单状态VO列表
*/
@Override
public List<OrderStatusVO> getAllOrderStatusList() {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, currentUserContext.getCurrentCompanyId())
.orderByAsc(OrderStatusPO::getSortOrder);
List<OrderStatusPO> poList = orderStatusMapper.selectList(wrapper);
return poList.stream()
.map(po -> {
OrderStatusVO vo = new OrderStatusVO();
BeanUtils.copyProperties(po, vo);
return vo;
})
.collect(Collectors.toList());
}
/**
* 初始化公司订单状态数据
* @param companyId 公司ID
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void initOrderStatusForCompany(Long companyId) {
// 检查是否已经初始化过
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId);
if (orderStatusMapper.selectCount(wrapper) > 0) {
return; // 已经初始化过,直接返回
}
// 初始化订单状态数据
List<OrderStatusPO> initialStatuses = List.of(
createOrderStatusPO(companyId, "待发货", "订单已创建,等待发货", 1),
createOrderStatusPO(companyId, "已发货", "商品已发出,运输中", 2),
createOrderStatusPO(companyId, "已完成", "订单已完成,交易成功", 3),
createOrderStatusPO(companyId, "已取消", "订单已取消", 4),
createOrderStatusPO(companyId, "退款中", "正在处理退款", 5),
createOrderStatusPO(companyId, "已退款", "退款已完成", 6)
);
// 批量插入
for (OrderStatusPO status : initialStatuses) {
orderStatusMapper.insert(status);
}
}
/**
* 初始化当前公司订单状态数据
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void initOrderStatusForCurrentCompany() {
Long companyId = currentUserContext.getCurrentCompanyId();
if (companyId == null) {
throw new RuntimeException("用户未关联公司");
}
initOrderStatusForCompany(companyId);
}
/**
* 创建订单状态PO对象
* @param companyId 公司ID
* @param statusName 状态名称
* @param description 描述
* @param sortOrder 排序
* @return 订单状态PO对象
*/
private OrderStatusPO createOrderStatusPO(Long companyId, String statusName, String description, Integer sortOrder) {
OrderStatusPO po = new OrderStatusPO();
po.setCompanyId(companyId);
po.setStatusName(statusName);
po.setDescription(description);
po.setSortOrder(sortOrder);
po.setIsActive(1);
po.setCreateBy(1L); // 系统初始化
po.setUpdateBy(1L);
return po;
}
}
@@ -11,7 +11,6 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ShopMapper;
@@ -22,7 +21,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.ShopProductPageFilt
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.ShopStatisticsQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shop.UpdateShopDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.PromotionFeePO;
@@ -32,6 +30,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
@@ -59,23 +59,24 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
private final MediaImageService mediaImageService;
private final OrderMapper orderMapper;
private final PromotionFeeMapper promotionFeeMapper;
private final OrderStatusMapper orderStatusMapper;
private final ProductMapper productMapper;
private final ShopProductRelationMapper shopProductRelationMapper;
private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService;
public ShopServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService,
OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper,
OrderStatusMapper orderStatusMapper, ProductMapper productMapper,
ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService) {
ProductMapper productMapper,
ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService,
OrderStatusService orderStatusService) {
this.currentUserContext = currentUserContext;
this.mediaImageService = mediaImageService;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.orderStatusMapper = orderStatusMapper;
this.productMapper = productMapper;
this.shopProductRelationMapper = shopProductRelationMapper;
this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService;
}
/**
@@ -250,14 +251,14 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
}
/**
* 获取退款状态ID
* 获取退款状态ID(根据状态名称"已退款"查找)
*/
private Long getRefundStatusId(Long companyId) {
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, "已退款")
.eq(OrderStatusPO::getIsActive, 1);
OrderStatusPO status = orderStatusMapper.selectOne(wrapper);
.eq(OrderStatusPO::getStatusName, "已退款");
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
@@ -289,7 +290,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
throw new BusinessException("开始日期不能晚于结束日期");
}
// 查询时间范围(订单使用orderDate,推广费使用feeDate)
// 查询时间范围(订单使用orderTime,推广费使用feeDate)
LocalDateTime startDateTime = queryDTO.getStartDate().atStartOfDay();
LocalDateTime endDateTime = queryDTO.getEndDate().atTime(23, 59, 59);
@@ -297,8 +298,8 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.eq(OrderPO::getShopId, queryDTO.getShopId())
.ge(OrderPO::getOrderDate, startDateTime)
.le(OrderPO::getOrderDate, endDateTime);
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据
@@ -309,12 +310,12 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
.le(PromotionFeePO::getFeeDate, queryDTO.getEndDate());
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promotionWrapper);
// 获取退款状态ID(状态名称为"已退款")
Long refundStatusId = getRefundStatusId(companyId);
// 获取退款状态ID
Long refundStatusId = getRefundStatusId();
// 按日期分组订单数据
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
.collect(Collectors.groupingBy(order -> order.getOrderDate().toLocalDate()));
.collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate()));
// 按日期分组推广费数据
Map<LocalDate, List<PromotionFeePO>> promotionFeesByDate = promotionFees.stream()
@@ -19,7 +19,6 @@ import top.xyquan.ecomdmbbackend.modules.org.model.vo.CompanyVO;
import top.xyquan.ecomdmbbackend.modules.org.service.CompanyService;
import top.xyquan.ecomdmbbackend.modules.media.service.MediaImageService;
import top.xyquan.ecomdmbbackend.modules.media.model.vo.MediaImageVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.PromotionFeeTypeService;
import top.xyquan.ecomdmbbackend.modules.org.service.CompanyMenuService;
import top.xyquan.ecomdmbbackend.modules.org.service.DepartmentService;
@@ -50,7 +49,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
private final CurrentUserContext currentUserContext;
private final MediaImageService mediaImageService;
private final OrderStatusService orderStatusService;
private final PromotionFeeTypeService promotionFeeTypeService;
private final CompanyMenuService companyMenuService;
private final DepartmentService departmentService;
@@ -58,12 +56,11 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
private final MenuService menuService;
public CompanyServiceImpl(CurrentUserContext currentUserContext, MediaImageService mediaImageService,
OrderStatusService orderStatusService, PromotionFeeTypeService promotionFeeTypeService,
PromotionFeeTypeService promotionFeeTypeService,
CompanyMenuService companyMenuService, DepartmentService departmentService,
PositionService positionService, MenuService menuService) {
this.currentUserContext = currentUserContext;
this.mediaImageService = mediaImageService;
this.orderStatusService = orderStatusService;
this.promotionFeeTypeService = promotionFeeTypeService;
this.companyMenuService = companyMenuService;
this.departmentService = departmentService;
@@ -110,9 +107,6 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
// 保存公司
this.save(company);
// 初始化订单状态数据
orderStatusService.initOrderStatusForCompany(company.getId());
// 初始化推广费类型数据
promotionFeeTypeService.initPromotionFeeTypeForCompany(company.getId());
@@ -71,12 +71,12 @@ CREATE TABLE `ec_product_spec` (
-- 订单状态表
CREATE TABLE `ec_order_status` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '状态ID',
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单状态ID',
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
`status_name` VARCHAR(50) NOT NULL COMMENT '状态名称',
`status_name` VARCHAR(100) NOT NULL COMMENT '状态名称(中文)',
`description` VARCHAR(200) DEFAULT NULL COMMENT '状态描述',
`sort_order` INT NOT NULL DEFAULT 0 COMMENT '排序',
`is_active` TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用 0禁用 1启用',
`is_default_stat` TINYINT NOT NULL DEFAULT 1 COMMENT '是否默认参与统计 0不参与 1参与',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '创建人ID',
@@ -85,7 +85,7 @@ CREATE TABLE `ec_order_status` (
KEY `idx_company_id` (`company_id`),
UNIQUE KEY `uk_company_status_name` (`company_id`, `status_name`),
KEY `idx_sort_order` (`sort_order`),
KEY `idx_is_active` (`is_active`),
KEY `idx_is_default_stat` (`is_default_stat`),
KEY `fk_ec_order_status_creator` (`create_by`),
KEY `fk_ec_order_status_updater` (`update_by`),
CONSTRAINT `fk_ec_order_status_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
@@ -102,19 +102,19 @@ CREATE TABLE `ec_order` (
`product_spec_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商品规格ID',
`status_id` BIGINT UNSIGNED NOT NULL COMMENT '订单状态ID',
`platform_order_no` VARCHAR(100) DEFAULT NULL COMMENT '平台订单号',
`product_name` VARCHAR(255) NOT NULL COMMENT '商品名称(冗余存储)',
`spec_name` VARCHAR(200) DEFAULT NULL COMMENT '规格名称(冗余存储)',
`link_product_name` VARCHAR(255) NOT NULL COMMENT '链接商品名称',
`link_spec_name` VARCHAR(200) DEFAULT NULL COMMENT '链接规格名称',
`received_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '商家实收金额',
`quantity` INT NOT NULL DEFAULT 1 COMMENT '数量',
`unit_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '销售单价',
`cost_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '成本价(下单时快照)',
`order_date` TIMESTAMP NOT NULL COMMENT '下单时间',
`order_time` TIMESTAMP NOT NULL COMMENT '下单时间',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '创建人ID',
`update_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`),
KEY `idx_company_shop_date` (`company_id`, `shop_id`, `order_date`),
KEY `idx_company_shop_time` (`company_id`, `shop_id`, `order_time`),
KEY `idx_status_id` (`status_id`),
KEY `idx_platform_order_no` (`platform_order_no`),
KEY `idx_product_id` (`product_id`),
@@ -123,14 +123,13 @@ CREATE TABLE `ec_order` (
KEY `fk_ec_order_updater` (`update_by`),
CONSTRAINT `fk_ec_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_status` FOREIGN KEY (`status_id`) REFERENCES `ec_order_status` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_product_spec` FOREIGN KEY (`product_spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_status` FOREIGN KEY (`status_id`) REFERENCES `ec_order_status` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_order_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电商-订单表(含商品明细)';
-- 推广费类型表
CREATE TABLE `ec_promotion_fee_type` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '推广费类型ID',
@@ -226,9 +225,9 @@ CREATE TABLE `ec_import_tasks` (
CREATE TABLE `ec_import_mappings` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '映射ID',
`company_id` bigint unsigned NOT NULL COMMENT '所属公司ID',
`type` enum('product','order') NOT NULL COMMENT '导入类型(product-商品 order-订单)',
`name` varchar(20) NOT NULL COMMENT '映射模板名称',
`mapping` json NOT NULL COMMENT '映射模板JSON',
`type` enum('PRODUCT','ORDER','ORDER_STATUS') NOT NULL COMMENT '导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)',
`name` varchar(20) NOT NULL COMMENT '映射名称',
`mapping` json NOT NULL COMMENT '映射JSON',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',