This commit is contained in:
ah--desktop
2026-01-12 00:14:47 +08:00
parent e1f39c1815
commit 59a649f002
65 changed files with 5097 additions and 369 deletions
@@ -0,0 +1,76 @@
package top.xyquan.ecomdmbbackend.modules.ecom.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.BrushOrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.CreateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.UpdateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.BrushOrderVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.BrushOrderService;
/**
* 刷单记录管理控制器
*/
@Tag(name = "电商-刷单记录管理", description = "刷单记录的增删改查接口")
@RestController
@RequestMapping("/ec/brush-order")
public class BrushOrderController {
private final BrushOrderService brushOrderService;
public BrushOrderController(BrushOrderService brushOrderService) {
this.brushOrderService = brushOrderService;
}
@Operation(summary = "创建刷单记录", description = "创建新的刷单记录")
@PostMapping("/create")
@RequireRole(description = "创建刷单记录", allowUser = false)
public ApiResponse<BrushOrderVO> createBrushOrder(@Valid @RequestBody CreateBrushOrderDTO createBrushOrderDTO) {
BrushOrderVO brushOrderVO = brushOrderService.createBrushOrder(createBrushOrderDTO);
return ApiResponse.success(brushOrderVO);
}
@Operation(summary = "更新刷单记录", description = "更新现有刷单记录信息")
@PutMapping("/update/{id}")
@RequireRole(description = "更新刷单记录", allowUser = false)
public ApiResponse<BrushOrderVO> updateBrushOrder(@Valid @RequestBody UpdateBrushOrderDTO updateBrushOrderDTO,
@Parameter(description = "刷单记录ID") @PathVariable Long id) {
BrushOrderVO brushOrderVO = brushOrderService.updateBrushOrder(updateBrushOrderDTO, id);
return ApiResponse.success(brushOrderVO);
}
@Operation(summary = "删除刷单记录", description = "删除指定刷单记录")
@DeleteMapping("/delete/{id}")
@RequireRole(description = "删除刷单记录", allowUser = false)
public ApiResponse<Void> deleteBrushOrder(
@Parameter(description = "刷单记录ID") @PathVariable Long id) {
brushOrderService.deleteBrushOrder(id);
return ApiResponse.success();
}
@Operation(summary = "分页获取刷单记录列表", description = "分页获取刷单记录列表,支持条件过滤")
@PostMapping("/page")
@RequireRole(description = "查询刷单记录列表", allowUser = true)
public ApiResponse<PageResultVO<BrushOrderVO>> getBrushOrderPage(
@Valid @RequestBody PageQueryDTO<BrushOrderFilterDTO> pageQueryDTO) {
PageResultVO<BrushOrderVO> result = brushOrderService.getBrushOrderPage(pageQueryDTO);
return ApiResponse.success(result);
}
@Operation(summary = "获取刷单记录详情", description = "根据ID获取刷单记录详情")
@GetMapping("/detail/{id}")
@RequireRole(description = "查询刷单记录详情", allowUser = true)
public ApiResponse<BrushOrderVO> getBrushOrderById(
@Parameter(description = "刷单记录ID") @PathVariable Long id) {
BrushOrderVO brushOrderVO = brushOrderService.getBrushOrderById(id);
return ApiResponse.success(brushOrderVO);
}
}
@@ -0,0 +1,35 @@
package top.xyquan.ecomdmbbackend.modules.ecom.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
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.overview.CompanyOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.CompanyOverviewService;
/**
* 全店铺概览控制器
*/
@Tag(name = "电商-全店铺概览", description = "全店铺概览统计接口")
@RestController
@RequestMapping("/ec/company-overview")
public class CompanyOverviewController {
private final CompanyOverviewService companyOverviewService;
public CompanyOverviewController(CompanyOverviewService companyOverviewService) {
this.companyOverviewService = companyOverviewService;
}
@Operation(summary = "获取全店铺概览统计数据", description = "获取当前公司所有店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等")
@PostMapping("/statistics")
@RequireRole(description = "查询全店铺概览", allowUser = true)
public ApiResponse<CompanyOverviewVO> getCompanyOverview(@Valid @RequestBody CompanyOverviewQueryDTO queryDTO) {
CompanyOverviewVO overviewVO = companyOverviewService.getCompanyOverview(queryDTO);
return ApiResponse.success(overviewVO);
}
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.ecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.BrushOrderPO;
/**
* 刷单记录Mapper接口
*/
@Mapper
public interface BrushOrderMapper extends BaseMapper<BrushOrderPO> {
}
@@ -0,0 +1,58 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 刷单记录分页查询过滤DTO
*/
@Data
@Schema(description = "刷单记录分页查询过滤DTO")
public class BrushOrderFilterDTO {
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1")
private Long shopId;
/**
* 商品ID
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/**
* 平台订单号(模糊查询)
*/
@Schema(description = "平台订单号(模糊查询)", example = "TB2024")
private String platformOrderNo;
/**
* 刷单金额范围-最小值
*/
@Schema(description = "刷单金额范围-最小值", example = "100.00")
private BigDecimal minBrushAmount;
/**
* 刷单金额范围-最大值
*/
@Schema(description = "刷单金额范围-最大值", example = "10000.00")
private BigDecimal maxBrushAmount;
/**
* 刷单时间范围-开始时间
*/
@Schema(description = "刷单时间范围-开始时间", example = "2024-01-01T00:00:00")
private LocalDateTime startBrushTime;
/**
* 刷单时间范围-结束时间
*/
@Schema(description = "刷单时间范围-结束时间", example = "2024-12-31T23:59:59")
private LocalDateTime endBrushTime;
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 创建刷单记录DTO
*/
@Data
@Schema(description = "创建刷单记录DTO")
public class CreateBrushOrderDTO {
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
private Long shopId;
/**
* 商品ID(可选)
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/**
* 商品规格ID(可选)
*/
@Schema(description = "商品规格ID", example = "1")
private Long productSpecId;
/**
* 刷单金额
*/
@Schema(description = "刷单金额", example = "9999.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "刷单金额不能为空")
private BigDecimal brushAmount;
/**
* 刷单时间
*/
@Schema(description = "刷单时间", example = "2024-01-01T10:00:00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "刷单时间不能为空")
private LocalDateTime brushTime;
/**
* 平台订单号(可选)
*/
@Schema(description = "平台订单号", example = "TB202401010001")
private String platformOrderNo;
/**
* 刷单数量
*/
@Schema(description = "刷单数量", example = "1")
@Positive(message = "刷单数量必须大于0")
private Integer quantity;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
@@ -0,0 +1,70 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 更新刷单记录DTO
*/
@Data
@Schema(description = "更新刷单记录DTO")
public class UpdateBrushOrderDTO {
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
private Long shopId;
/**
* 商品ID(可选)
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/**
* 商品规格ID(可选)
*/
@Schema(description = "商品规格ID", example = "1")
private Long productSpecId;
/**
* 刷单金额
*/
@Schema(description = "刷单金额", example = "9999.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "刷单金额不能为空")
private BigDecimal brushAmount;
/**
* 刷单时间
*/
@Schema(description = "刷单时间", example = "2024-01-01T10:00:00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "刷单时间不能为空")
private LocalDateTime brushTime;
/**
* 平台订单号(可选)
*/
@Schema(description = "平台订单号", example = "TB202401010001")
private String platformOrderNo;
/**
* 刷单数量
*/
@Schema(description = "刷单数量", example = "1")
@Positive(message = "刷单数量必须大于0")
private Integer quantity;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
@@ -91,9 +91,39 @@ public class CreateOrderDTO {
private BigDecimal unitPrice;
/**
* 成本价(下单时快照)
* 单件商品成本(下单时快照)
*/
@Schema(description = "成本价", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
@Schema(description = "单件商品成本", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "单件商品成本不能为空")
private BigDecimal productCost;
/**
* 单件运费成本(下单时快照)
*/
@Schema(description = "单件运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 单件其他成本(下单时快照)
*/
@Schema(description = "单件其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
/**
* 导入任务ID
*/
@Schema(description = "导入任务ID", example = "1")
private Long importTaskId;
/**
* 确认(0-否 1-是)
*/
@Schema(description = "确认", example = "1")
private Integer confirm;
}
@@ -54,4 +54,16 @@ public class OrderFilterDTO {
*/
@Schema(description = "下单时间范围-结束时间", example = "2024-12-31T23:59:59")
private LocalDateTime endOrderTime;
/**
* 导入任务ID
*/
@Schema(description = "导入任务ID", example = "1")
private Long importTaskId;
/**
* 确认(0-否 1-是)
*/
@Schema(description = "确认", example = "1")
private Integer confirm;
}
@@ -84,8 +84,32 @@ public class UpdateOrderDTO {
private BigDecimal unitPrice;
/**
* 成本价(下单时快照)
* 单件商品成本(下单时快照)
*/
@Schema(description = "成本价", example = "8000.00")
private BigDecimal costPrice;
@Schema(description = "单件商品成本", example = "8000.00")
private BigDecimal productCost;
/**
* 单件运费成本(下单时快照)
*/
@Schema(description = "单件运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 单件其他成本(下单时快照)
*/
@Schema(description = "单件其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
/**
* 确认(0-否 1-是)
*/
@Schema(description = "确认", example = "1")
private Integer confirm;
}
@@ -32,10 +32,10 @@ public class CreateOrderStatusDTO {
private Integer sortOrder;
/**
* 是否默认参与统计 0不参与 1参与
* 是否自动参与统计 0不参与 1参与
*/
@Schema(description = "是否默认参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否默认参与统计不能为空")
private Integer isDefaultStat;
@Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否自动参与统计不能为空")
private Integer autoStatistics;
}
@@ -32,10 +32,10 @@ public class UpdateOrderStatusDTO {
private Integer sortOrder;
/**
* 是否默认参与统计 0不参与 1参与
* 是否自动参与统计 0不参与 1参与
*/
@Schema(description = "是否默认参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否默认参与统计不能为空")
private Integer isDefaultStat;
@Schema(description = "是否自动参与统计", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "是否自动参与统计不能为空")
private Integer autoStatistics;
}
@@ -0,0 +1,26 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.time.LocalDate;
import java.util.List;
/**
* 全店铺概览查询DTO
*/
@Data
@Schema(description = "全店铺概览查询DTO")
public class CompanyOverviewQueryDTO {
/**
* 日期范围数组(第一个是开始日期,第二个是结束日期,只有一个日期则返回当天数据)
*/
@Schema(description = "日期范围数组", example = "[\"2024-01-01\", \"2024-01-31\"]", requiredMode = Schema.RequiredMode.REQUIRED)
@NotEmpty(message = "日期范围不能为空")
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
private List<LocalDate> dateRange;
}
@@ -63,10 +63,28 @@ public class CreateProductDTO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@Schema(description = "成本价", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
@Schema(description = "商品成本", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品成本不能为空")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
}
@@ -35,9 +35,27 @@ public class CreateProductSpecDTO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@Schema(description = "成本价", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
@Schema(description = "商品成本", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品成本不能为空")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
@@ -70,10 +70,28 @@ public class UpdateProductDTO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@Schema(description = "成本价", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
@Schema(description = "商品成本", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品成本不能为空")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
}
@@ -35,9 +35,27 @@ public class UpdateProductSpecDTO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@Schema(description = "成本价", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
@Schema(description = "商品成本", example = "8000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "商品成本不能为空")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
}
@@ -0,0 +1,102 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 电商-刷单记录实体
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ec_brush_order")
public class BrushOrderPO {
/**
* 刷单记录ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公司ID
*/
@TableField("company_id")
private Long companyId;
/**
* 店铺ID
*/
@TableField("shop_id")
private Long shopId;
/**
* 商品ID(可选)
*/
@TableField("product_id")
private Long productId;
/**
* 商品规格ID(可选)
*/
@TableField("product_spec_id")
private Long productSpecId;
/**
* 刷单金额
*/
@TableField("brush_amount")
private BigDecimal brushAmount;
/**
* 刷单时间
*/
@TableField("brush_time")
private LocalDateTime brushTime;
/**
* 平台订单号(可选)
*/
@TableField("platform_order_no")
private String platformOrderNo;
/**
* 刷单数量
*/
@TableField("quantity")
private Integer quantity;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 创建时间
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/**
* 创建人ID
*/
@TableField("create_by")
private Long createBy;
/**
* 更新人ID
*/
@TableField("update_by")
private Long updateBy;
}
@@ -82,10 +82,40 @@ public class OrderPO {
private BigDecimal unitPrice;
/**
* 成本价(下单时快照)
* 单件商品成本(下单时快照)
*/
@TableField("cost_price")
private BigDecimal costPrice;
@TableField("product_cost")
private BigDecimal productCost;
/**
* 单件运费成本(下单时快照)
*/
@TableField("shipping_cost")
private BigDecimal shippingCost;
/**
* 单件其他成本(下单时快照)
*/
@TableField("other_cost")
private BigDecimal otherCost;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 导入任务ID
*/
@TableField("import_task_id")
private Long importTaskId;
/**
* 确认(0-否 1-是)
*/
@TableField("confirm")
private Integer confirm;
/**
* 商家实收金额
@@ -45,10 +45,10 @@ public class OrderStatusPO {
private Integer sortOrder;
/**
* 是否默认参与统计 0不参与 1参与
* 是否自动参与统计 0不参与 1参与
*/
@TableField("is_default_stat")
private Integer isDefaultStat;
@TableField("auto_statistics")
private Integer autoStatistics;
/**
* 创建时间
@@ -46,10 +46,28 @@ public class ProductSpecPO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@TableField("cost_price")
private BigDecimal costPrice;
@TableField("product_cost")
private BigDecimal productCost;
/**
* 运费成本
*/
@TableField("shipping_cost")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@TableField("other_cost")
private BigDecimal otherCost;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 创建时间
@@ -0,0 +1,118 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 刷单记录VO
*/
@Data
@Schema(description = "刷单记录VO")
public class BrushOrderVO {
/**
* 刷单记录ID
*/
@Schema(description = "刷单记录ID", example = "1")
private Long id;
/**
* 公司ID
*/
@Schema(description = "公司ID", example = "1")
private Long companyId;
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1")
private Long shopId;
/**
* 店铺名称
*/
@Schema(description = "店铺名称", example = "旗舰店")
private String shopName;
/**
* 商品ID
*/
@Schema(description = "商品ID", example = "1")
private Long productId;
/**
* 商品名称
*/
@Schema(description = "商品名称", example = "iPhone 15 Pro")
private String productName;
/**
* 商品规格ID
*/
@Schema(description = "商品规格ID", example = "1")
private Long productSpecId;
/**
* 商品规格名称
*/
@Schema(description = "商品规格名称", example = "256GB 深空黑色")
private String productSpecName;
/**
* 刷单金额
*/
@Schema(description = "刷单金额", example = "9999.00")
private BigDecimal brushAmount;
/**
* 刷单时间
*/
@Schema(description = "刷单时间", example = "2024-01-01T10:00:00")
private LocalDateTime brushTime;
/**
* 平台订单号
*/
@Schema(description = "平台订单号", example = "TB202401010001")
private String platformOrderNo;
/**
* 刷单数量
*/
@Schema(description = "刷单数量", example = "1")
private Integer quantity;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
/**
* 创建时间
*/
@Schema(description = "创建时间", example = "2024-01-01T10:00:00")
private LocalDateTime createTime;
/**
* 更新时间
*/
@Schema(description = "更新时间", example = "2024-01-01T10:00:00")
private LocalDateTime updateTime;
/**
* 创建人ID
*/
@Schema(description = "创建人ID", example = "1")
private Long createBy;
/**
* 更新人ID
*/
@Schema(description = "更新人ID", example = "1")
private Long updateBy;
}
@@ -0,0 +1,190 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 全店铺概览VO
*/
@Data
@Schema(description = "全店铺概览VO")
public class CompanyOverviewVO {
/**
* 全店总销售额
*/
@Schema(description = "全店总销售额", example = "100000.00")
private BigDecimal totalSalesAmount;
/**
* 较上月同期增长百分比
*/
@Schema(description = "较上月同期增长百分比", example = "15.50")
private BigDecimal monthOverMonthGrowth;
/**
* 全店总单量
*/
@Schema(description = "全店总单量", example = "1000")
private Integer totalOrderCount;
/**
* 总推广费支出
*/
@Schema(description = "总推广费支出", example = "5000.00")
private BigDecimal totalPromotionFee;
/**
* 平均费比(推广费/销售额)
*/
@Schema(description = "平均费比", example = "0.05")
private BigDecimal averageFeeRatio;
/**
* 全店总净利(税后)
*/
@Schema(description = "全店总净利(税后)", example = "80000.00")
private BigDecimal totalNetProfitAfterTax;
/**
* 扣除总税额
*/
@Schema(description = "扣除总税额", example = "6000.00")
private BigDecimal totalTaxAmount;
/**
* 各店铺销售占比排行
*/
@Schema(description = "各店铺销售占比排行")
private List<ShopSalesRatio> shopSalesRatios;
/**
* 店铺效率象限(ROI vs 净利)
*/
@Schema(description = "店铺效率象限")
private List<ShopEfficiencyQuadrant> shopEfficiencyQuadrants;
/**
* 多店铺数据横向对比(16维度)
*/
@Schema(description = "多店铺数据横向对比")
private List<ShopComparison> shopComparisons;
/**
* 汇总ROI
*/
@Schema(description = "汇总ROI", example = "1.5")
private BigDecimal totalROI;
/**
* 总税后盈亏
*/
@Schema(description = "总税后盈亏", example = "80000.00")
private BigDecimal totalProfitAfterTax;
/**
* 店铺销售占比
*/
@Data
@Schema(description = "店铺销售占比")
public static class ShopSalesRatio {
@Schema(description = "店铺ID", example = "1")
private Long shopId;
@Schema(description = "店铺名称", example = "旗舰店")
private String shopName;
@Schema(description = "销售额", example = "50000.00")
private BigDecimal salesAmount;
@Schema(description = "占比百分比", example = "50.00")
private BigDecimal ratio;
}
/**
* 店铺效率象限
*/
@Data
@Schema(description = "店铺效率象限")
public static class ShopEfficiencyQuadrant {
@Schema(description = "店铺ID", example = "1")
private Long shopId;
@Schema(description = "店铺名称", example = "旗舰店")
private String shopName;
@Schema(description = "ROI", example = "1.5")
private BigDecimal roi;
@Schema(description = "净利", example = "30000.00")
private BigDecimal netProfit;
@Schema(description = "象限(1-高ROI高净利,2-高ROI低净利,3-低ROI高净利,4-低ROI低净利)", example = "1")
private Integer quadrant;
}
/**
* 店铺对比数据(16维度)
*/
@Data
@Schema(description = "店铺对比数据")
public static class ShopComparison {
@Schema(description = "店铺ID", example = "1")
private Long shopId;
@Schema(description = "店铺名称", example = "旗舰店")
private String shopName;
@Schema(description = "平台", example = "拼多多")
private String platform;
@Schema(description = "销售额", example = "50000.00")
private BigDecimal salesAmount;
@Schema(description = "ROI", example = "1.5")
private BigDecimal roi;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@Schema(description = "刷单费", example = "2000.00")
private BigDecimal brushFee;
@Schema(description = "推广费总和", example = "5000.00")
private BigDecimal totalPromotionFee;
@Schema(description = "税后盈亏", example = "30000.00")
private BigDecimal profitAfterTax;
@Schema(description = "订单数量", example = "500")
private Integer orderCount;
@Schema(description = "总成本", example = "15000.00")
private BigDecimal totalCost;
@Schema(description = "总利润(税前)", example = "35000.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "税额", example = "3000.00")
private BigDecimal taxAmount;
@Schema(description = "费比", example = "0.10")
private BigDecimal feeRatio;
@Schema(description = "客单价", example = "100.00")
private BigDecimal averageOrderValue;
@Schema(description = "利润率", example = "0.60")
private BigDecimal profitMargin;
@Schema(description = "推广费占比", example = "0.10")
private BigDecimal promotionFeeRatio;
@Schema(description = "退款率", example = "0.02")
private BigDecimal refundRate;
}
}
@@ -43,10 +43,10 @@ public class OrderStatusVO {
private Integer sortOrder;
/**
* 是否默认参与统计 0不参与 1参与
* 是否自动参与统计 0不参与 1参与
*/
@Schema(description = "是否默认参与统计", example = "1")
private Integer isDefaultStat;
@Schema(description = "是否自动参与统计", example = "1")
private Integer autoStatistics;
/**
* 创建时间
@@ -128,8 +128,38 @@ public class OrderVO {
private BigDecimal unitPrice;
/**
* 成本价(下单时快照)
* 单件商品成本(下单时快照)
*/
@Schema(description = "成本价", example = "8000.00")
private BigDecimal costPrice;
@Schema(description = "单件商品成本", example = "8000.00")
private BigDecimal productCost;
/**
* 单件运费成本(下单时快照)
*/
@Schema(description = "单件运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 单件其他成本(下单时快照)
*/
@Schema(description = "单件其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
/**
* 导入任务ID
*/
@Schema(description = "导入任务ID", example = "1")
private Long importTaskId;
/**
* 确认(0-否 1-是)
*/
@Schema(description = "确认", example = "1")
private Integer confirm;
}
@@ -50,10 +50,28 @@ public class ProductSpecVO {
private String specCode;
/**
* 成本价
* 商品成本
*/
@Schema(description = "成本价", example = "8000.00")
private BigDecimal costPrice;
@Schema(description = "商品成本", example = "8000.00")
private BigDecimal productCost;
/**
* 运费成本
*/
@Schema(description = "运费成本", example = "10.00")
private BigDecimal shippingCost;
/**
* 其他成本
*/
@Schema(description = "其他成本", example = "5.00")
private BigDecimal otherCost;
/**
* 备注
*/
@Schema(description = "备注", example = "备注信息")
private String remark;
/**
* 创建时间
@@ -0,0 +1,57 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.BrushOrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.CreateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.UpdateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.BrushOrderVO;
/**
* 刷单记录服务接口
*/
public interface BrushOrderService extends IService<BrushOrderPO> {
/**
* 创建刷单记录
*
* @param createBrushOrderDTO 创建刷单记录DTO
* @return 刷单记录VO
*/
BrushOrderVO createBrushOrder(CreateBrushOrderDTO createBrushOrderDTO);
/**
* 更新刷单记录
*
* @param updateBrushOrderDTO 更新刷单记录DTO
* @param id 刷单记录ID
* @return 刷单记录VO
*/
BrushOrderVO updateBrushOrder(UpdateBrushOrderDTO updateBrushOrderDTO, Long id);
/**
* 删除刷单记录
*
* @param id 刷单记录ID
*/
void deleteBrushOrder(Long id);
/**
* 分页获取刷单记录列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果
*/
PageResultVO<BrushOrderVO> getBrushOrderPage(PageQueryDTO<BrushOrderFilterDTO> pageQueryDTO);
/**
* 根据ID获取刷单记录详情
*
* @param id 刷单记录ID
* @return 刷单记录VO
*/
BrushOrderVO getBrushOrderById(Long id);
}
@@ -0,0 +1,19 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview.CompanyOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.CompanyOverviewVO;
/**
* 全店铺概览服务接口
*/
public interface CompanyOverviewService {
/**
* 获取全店铺概览统计数据
*
* @param queryDTO 查询DTO
* @return 全店铺概览VO
*/
CompanyOverviewVO getCompanyOverview(CompanyOverviewQueryDTO queryDTO);
}
@@ -0,0 +1,300 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.BrushOrderFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.CreateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.brushorder.UpdateBrushOrderDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.BrushOrderPO;
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.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.BrushOrderVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.BrushOrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.util.List;
import java.util.stream.Collectors;
/**
* 刷单记录服务实现类
*/
@Service
public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOrderPO> implements BrushOrderService {
private final CurrentUserContext currentUserContext;
private final ShopService shopService;
private final ProductService productService;
private final ProductSpecService productSpecService;
public BrushOrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
}
/**
* 创建刷单记录
*
* @param createBrushOrderDTO 创建刷单记录DTO
* @return 刷单记录VO
*/
@Override
@Transactional
public BrushOrderVO createBrushOrder(CreateBrushOrderDTO createBrushOrderDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证店铺是否存在且属于当前公司
ShopPO shop = shopService.getById(createBrushOrderDTO.getShopId());
if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在");
}
// 验证商品是否存在且属于当前公司(如果提供了商品ID)
if (createBrushOrderDTO.getProductId() != null) {
ProductPO product = productService.getById(createBrushOrderDTO.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证商品规格是否存在且属于当前公司(如果提供了规格ID)
if (createBrushOrderDTO.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(createBrushOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId) ||
!productSpec.getProductId().equals(createBrushOrderDTO.getProductId())) {
throw new BusinessException("商品规格不存在或不属于该商品");
}
}
}
// 创建刷单记录
BrushOrderPO brushOrder = new BrushOrderPO();
brushOrder.setCompanyId(companyId);
brushOrder.setShopId(createBrushOrderDTO.getShopId());
brushOrder.setProductId(createBrushOrderDTO.getProductId());
brushOrder.setProductSpecId(createBrushOrderDTO.getProductSpecId());
brushOrder.setBrushAmount(createBrushOrderDTO.getBrushAmount());
brushOrder.setBrushTime(createBrushOrderDTO.getBrushTime());
brushOrder.setPlatformOrderNo(createBrushOrderDTO.getPlatformOrderNo());
brushOrder.setQuantity(createBrushOrderDTO.getQuantity() != null ? createBrushOrderDTO.getQuantity() : 1);
brushOrder.setRemark(createBrushOrderDTO.getRemark());
brushOrder.setCreateBy(currentUserContext.getCurrentUserId());
// 保存刷单记录
this.save(brushOrder);
// 转换为VO并返回
return convertToVO(brushOrder);
}
/**
* 更新刷单记录
*
* @param updateBrushOrderDTO 更新刷单记录DTO
* @param id 刷单记录ID
* @return 刷单记录VO
*/
@Override
@Transactional
public BrushOrderVO updateBrushOrder(UpdateBrushOrderDTO updateBrushOrderDTO, Long id) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证刷单记录是否存在
BrushOrderPO existingBrushOrder = this.getById(id);
if (existingBrushOrder == null || !existingBrushOrder.getCompanyId().equals(companyId)) {
throw new BusinessException("刷单记录不存在");
}
// 验证店铺是否存在且属于当前公司
ShopPO shop = shopService.getById(updateBrushOrderDTO.getShopId());
if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在");
}
// 验证商品是否存在且属于当前公司(如果提供了商品ID)
if (updateBrushOrderDTO.getProductId() != null) {
ProductPO product = productService.getById(updateBrushOrderDTO.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证商品规格是否存在且属于当前公司(如果提供了规格ID)
if (updateBrushOrderDTO.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(updateBrushOrderDTO.getProductSpecId());
if (productSpec == null || !productSpec.getCompanyId().equals(companyId) ||
!productSpec.getProductId().equals(updateBrushOrderDTO.getProductId())) {
throw new BusinessException("商品规格不存在或不属于该商品");
}
}
}
// 更新刷单记录
existingBrushOrder.setShopId(updateBrushOrderDTO.getShopId());
existingBrushOrder.setProductId(updateBrushOrderDTO.getProductId());
existingBrushOrder.setProductSpecId(updateBrushOrderDTO.getProductSpecId());
existingBrushOrder.setBrushAmount(updateBrushOrderDTO.getBrushAmount());
existingBrushOrder.setBrushTime(updateBrushOrderDTO.getBrushTime());
existingBrushOrder.setPlatformOrderNo(updateBrushOrderDTO.getPlatformOrderNo());
if (updateBrushOrderDTO.getQuantity() != null) {
existingBrushOrder.setQuantity(updateBrushOrderDTO.getQuantity());
}
existingBrushOrder.setRemark(updateBrushOrderDTO.getRemark());
existingBrushOrder.setUpdateBy(currentUserContext.getCurrentUserId());
// 保存更新
this.updateById(existingBrushOrder);
// 转换为VO并返回
return convertToVO(existingBrushOrder);
}
/**
* 删除刷单记录
*
* @param id 刷单记录ID
*/
@Override
@Transactional
public void deleteBrushOrder(Long id) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证刷单记录是否存在
BrushOrderPO existingBrushOrder = this.getById(id);
if (existingBrushOrder == null || !existingBrushOrder.getCompanyId().equals(companyId)) {
throw new BusinessException("刷单记录不存在");
}
// 硬删除刷单记录
this.removeById(id);
}
/**
* 获取刷单记录分页列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果VO
*/
@Override
public PageResultVO<BrushOrderVO> getBrushOrderPage(PageQueryDTO<BrushOrderFilterDTO> pageQueryDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 创建分页对象
Page<BrushOrderPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
// 构建查询条件
LambdaQueryWrapper<BrushOrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(BrushOrderPO::getCompanyId, companyId);
// 添加过滤条件
BrushOrderFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getShopId() != null) {
wrapper.eq(BrushOrderPO::getShopId, filter.getShopId());
}
if (filter.getProductId() != null) {
wrapper.eq(BrushOrderPO::getProductId, filter.getProductId());
}
if (filter.getPlatformOrderNo() != null && !filter.getPlatformOrderNo().trim().isEmpty()) {
wrapper.like(BrushOrderPO::getPlatformOrderNo, filter.getPlatformOrderNo());
}
if (filter.getMinBrushAmount() != null) {
wrapper.ge(BrushOrderPO::getBrushAmount, filter.getMinBrushAmount());
}
if (filter.getMaxBrushAmount() != null) {
wrapper.le(BrushOrderPO::getBrushAmount, filter.getMaxBrushAmount());
}
if (filter.getStartBrushTime() != null) {
wrapper.ge(BrushOrderPO::getBrushTime, filter.getStartBrushTime());
}
if (filter.getEndBrushTime() != null) {
wrapper.le(BrushOrderPO::getBrushTime, filter.getEndBrushTime());
}
}
// 排序
wrapper.orderByDesc(BrushOrderPO::getBrushTime)
.orderByDesc(BrushOrderPO::getCreateTime);
// 执行分页查询
IPage<BrushOrderPO> pageResult = this.page(page, wrapper);
// 转换为VO
List<BrushOrderVO> voList = pageResult.getRecords().stream()
.map(this::convertToVO)
.collect(Collectors.toList());
// 构建分页结果
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
/**
* 根据ID查询刷单记录
*
* @param id 刷单记录ID
* @return 刷单记录VO
*/
@Override
public BrushOrderVO getBrushOrderById(Long id) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证刷单记录是否存在
BrushOrderPO brushOrder = this.getById(id);
if (brushOrder == null || !brushOrder.getCompanyId().equals(companyId)) {
throw new BusinessException("刷单记录不存在");
}
// 转换为VO并返回
return convertToVO(brushOrder);
}
/**
* 转换为VO
*/
private BrushOrderVO convertToVO(BrushOrderPO brushOrder) {
BrushOrderVO brushOrderVO = new BrushOrderVO();
BeanUtils.copyProperties(brushOrder, brushOrderVO);
// 设置店铺名称
ShopPO shop = shopService.getById(brushOrder.getShopId());
if (shop != null) {
brushOrderVO.setShopName(shop.getName());
}
// 设置商品名称和规格名称(如果存在)
if (brushOrder.getProductId() != null) {
ProductPO product = productService.getById(brushOrder.getProductId());
if (product != null) {
brushOrderVO.setProductName(product.getName());
}
if (brushOrder.getProductSpecId() != null) {
ProductSpecPO productSpec = productSpecService.getById(brushOrder.getProductSpecId());
if (productSpec != null) {
brushOrderVO.setProductSpecName(productSpec.getName());
}
}
}
return brushOrderVO;
}
}
@@ -0,0 +1,516 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.overview.CompanyOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.BrushOrderPO;
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.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.CompanyOverviewService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 全店铺概览服务实现类
*/
@Service
public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private static final BigDecimal TAX_RATE = new BigDecimal("0.06"); // 税率6%
private final CurrentUserContext currentUserContext;
private final OrderMapper orderMapper;
private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final ShopService shopService;
private final OrderStatusService orderStatusService;
public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
ShopService shopService,
OrderStatusService orderStatusService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.shopService = shopService;
this.orderStatusService = orderStatusService;
}
@Override
public CompanyOverviewVO getCompanyOverview(CompanyOverviewQueryDTO queryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
// 解析日期范围
LocalDate startDate;
LocalDate endDate;
if (queryDTO.getDateRange().size() == 1) {
// 只有一个日期,返回当天数据
startDate = queryDTO.getDateRange().get(0);
endDate = startDate;
} else {
startDate = queryDTO.getDateRange().get(0);
endDate = queryDTO.getDateRange().get(1);
if (startDate.isAfter(endDate)) {
throw new BusinessException("开始日期不能晚于结束日期");
}
}
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
// 查询所有店铺
LambdaQueryWrapper<ShopPO> shopWrapper = new LambdaQueryWrapper<>();
shopWrapper.eq(ShopPO::getCompanyId, companyId);
List<ShopPO> shops = shopService.list(shopWrapper);
if (shops.isEmpty()) {
throw new BusinessException("当前公司没有店铺");
}
// 查询订单数据(所有店铺)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(所有店铺)
LambdaQueryWrapper<PromotionFeePO> promotionWrapper = new LambdaQueryWrapper<>();
promotionWrapper.eq(PromotionFeePO::getCompanyId, companyId)
.ge(PromotionFeePO::getFeeDate, startDate)
.le(PromotionFeePO::getFeeDate, endDate);
List<PromotionFeePO> promotionFees = promotionFeeMapper.selectList(promotionWrapper);
// 查询刷单费数据(所有店铺)
LambdaQueryWrapper<BrushOrderPO> brushWrapper = new LambdaQueryWrapper<>();
brushWrapper.eq(BrushOrderPO::getCompanyId, companyId)
.ge(BrushOrderPO::getBrushTime, startDateTime)
.le(BrushOrderPO::getBrushTime, endDateTime);
List<BrushOrderPO> brushOrders = brushOrderMapper.selectList(brushWrapper);
// 获取退款状态ID
Long refundStatusId = getRefundStatusId();
// 计算上月同期数据(用于增长百分比)
LocalDate lastMonthStartDate = startDate.minusMonths(1);
LocalDate lastMonthEndDate = endDate.minusMonths(1);
LocalDateTime lastMonthStartDateTime = lastMonthStartDate.atStartOfDay();
LocalDateTime lastMonthEndDateTime = lastMonthEndDate.atTime(23, 59, 59);
LambdaQueryWrapper<OrderPO> lastMonthOrderWrapper = new LambdaQueryWrapper<>();
lastMonthOrderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, lastMonthStartDateTime)
.le(OrderPO::getOrderTime, lastMonthEndDateTime);
List<OrderPO> lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper);
// 构建返回对象
CompanyOverviewVO overviewVO = new CompanyOverviewVO();
// 1. 计算全店总销售额
BigDecimal totalSalesAmount = orders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
overviewVO.setTotalSalesAmount(totalSalesAmount);
// 2. 计算较上月同期增长百分比
BigDecimal lastMonthSalesAmount = lastMonthOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal monthOverMonthGrowth = BigDecimal.ZERO;
if (lastMonthSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = totalSalesAmount.subtract(lastMonthSalesAmount)
.divide(lastMonthSalesAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
monthOverMonthGrowth = new BigDecimal("100"); // 上月为0,本月有数据,增长100%
}
overviewVO.setMonthOverMonthGrowth(monthOverMonthGrowth);
// 3. 计算全店总单量
int totalOrderCount = orders.size();
overviewVO.setTotalOrderCount(totalOrderCount);
// 4. 计算总推广费支出
BigDecimal totalPromotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
overviewVO.setTotalPromotionFee(totalPromotionFee);
// 5. 计算平均费比
BigDecimal averageFeeRatio = BigDecimal.ZERO;
if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
averageFeeRatio = totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP);
}
overviewVO.setAverageFeeRatio(averageFeeRatio);
// 6. 计算全店总净利(税后)和总税额
BigDecimal totalProfitBeforeTax = calculateTotalProfit(orders);
BigDecimal totalTaxAmount = totalProfitBeforeTax.multiply(TAX_RATE);
BigDecimal totalNetProfitAfterTax = totalProfitBeforeTax.subtract(totalTaxAmount);
overviewVO.setTotalNetProfitAfterTax(totalNetProfitAfterTax);
overviewVO.setTotalTaxAmount(totalTaxAmount);
// 7. 计算各店铺销售占比排行
List<CompanyOverviewVO.ShopSalesRatio> shopSalesRatios = calculateShopSalesRatios(shops, orders, totalSalesAmount);
overviewVO.setShopSalesRatios(shopSalesRatios);
// 8. 计算店铺效率象限(ROI vs 净利)
List<CompanyOverviewVO.ShopEfficiencyQuadrant> shopEfficiencyQuadrants = calculateShopEfficiencyQuadrants(
shops, orders, promotionFees, brushOrders, refundStatusId);
overviewVO.setShopEfficiencyQuadrants(shopEfficiencyQuadrants);
// 9. 多店铺数据横向对比(16维度)
List<CompanyOverviewVO.ShopComparison> shopComparisons = calculateShopComparisons(
shops, orders, promotionFees, brushOrders, refundStatusId);
overviewVO.setShopComparisons(shopComparisons);
// 10. 汇总ROI和总税后盈亏
BigDecimal totalROI = calculateTotalROI(orders, promotionFees, brushOrders);
overviewVO.setTotalROI(totalROI);
overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax);
return overviewVO;
}
/**
* 计算总利润(税前)
*/
private BigDecimal calculateTotalProfit(List<OrderPO> orders) {
return orders.stream()
.map(order -> {
BigDecimal receivedAmount = order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO;
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
BigDecimal totalCost = productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity));
return receivedAmount.subtract(totalCost);
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* 计算各店铺销售占比排行
*/
private List<CompanyOverviewVO.ShopSalesRatio> calculateShopSalesRatios(
List<ShopPO> shops, List<OrderPO> orders, BigDecimal totalSalesAmount) {
Map<Long, BigDecimal> shopSalesMap = orders.stream()
.collect(Collectors.groupingBy(
OrderPO::getShopId,
Collectors.reducing(
BigDecimal.ZERO,
order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO,
BigDecimal::add)));
List<CompanyOverviewVO.ShopSalesRatio> ratios = new ArrayList<>();
for (ShopPO shop : shops) {
BigDecimal salesAmount = shopSalesMap.getOrDefault(shop.getId(), BigDecimal.ZERO);
BigDecimal ratio = BigDecimal.ZERO;
if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
}
CompanyOverviewVO.ShopSalesRatio shopRatio = new CompanyOverviewVO.ShopSalesRatio();
shopRatio.setShopId(shop.getId());
shopRatio.setShopName(shop.getName());
shopRatio.setSalesAmount(salesAmount);
shopRatio.setRatio(ratio);
ratios.add(shopRatio);
}
// 按销售额降序排序
ratios.sort(Comparator.comparing(CompanyOverviewVO.ShopSalesRatio::getSalesAmount).reversed());
return ratios;
}
/**
* 计算店铺效率象限(ROI vs 净利)
*/
private List<CompanyOverviewVO.ShopEfficiencyQuadrant> calculateShopEfficiencyQuadrants(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, Long refundStatusId) {
List<CompanyOverviewVO.ShopEfficiencyQuadrant> quadrants = new ArrayList<>();
// 按店铺分组数据
Map<Long, List<OrderPO>> ordersByShop = orders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId));
Map<Long, List<PromotionFeePO>> promotionFeesByShop = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId));
Map<Long, List<BrushOrderPO>> brushOrdersByShop = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId));
// 计算所有店铺的平均ROI和平均净利(用于划分象限)
List<BigDecimal> allROIs = new ArrayList<>();
List<BigDecimal> allNetProfits = new ArrayList<>();
for (ShopPO shop : shops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<PromotionFeePO> shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<BrushOrderPO> shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>());
BigDecimal profit = calculateShopProfit(shopOrders, refundStatusId);
BigDecimal totalCost = calculateShopTotalCost(shopPromotionFees, shopBrushOrders);
BigDecimal roi = calculateShopROI(profit, totalCost);
BigDecimal netProfit = calculateShopNetProfit(profit);
allROIs.add(roi);
allNetProfits.add(netProfit);
}
BigDecimal avgROI = allROIs.isEmpty() ? BigDecimal.ZERO :
allROIs.stream().reduce(BigDecimal.ZERO, BigDecimal::add)
.divide(new BigDecimal(allROIs.size()), 4, RoundingMode.HALF_UP);
BigDecimal avgNetProfit = allNetProfits.isEmpty() ? BigDecimal.ZERO :
allNetProfits.stream().reduce(BigDecimal.ZERO, BigDecimal::add)
.divide(new BigDecimal(allNetProfits.size()), 4, RoundingMode.HALF_UP);
// 计算每个店铺的象限
for (ShopPO shop : shops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<PromotionFeePO> shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<BrushOrderPO> shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>());
BigDecimal profit = calculateShopProfit(shopOrders, refundStatusId);
BigDecimal totalCost = calculateShopTotalCost(shopPromotionFees, shopBrushOrders);
BigDecimal roi = calculateShopROI(profit, totalCost);
BigDecimal netProfit = calculateShopNetProfit(profit);
int quadrant;
if (roi.compareTo(avgROI) >= 0 && netProfit.compareTo(avgNetProfit) >= 0) {
quadrant = 1; // 高ROI高净利
} else if (roi.compareTo(avgROI) >= 0 && netProfit.compareTo(avgNetProfit) < 0) {
quadrant = 2; // 高ROI低净利
} else if (roi.compareTo(avgROI) < 0 && netProfit.compareTo(avgNetProfit) >= 0) {
quadrant = 3; // 低ROI高净利
} else {
quadrant = 4; // 低ROI低净利
}
CompanyOverviewVO.ShopEfficiencyQuadrant shopQuadrant = new CompanyOverviewVO.ShopEfficiencyQuadrant();
shopQuadrant.setShopId(shop.getId());
shopQuadrant.setShopName(shop.getName());
shopQuadrant.setRoi(roi);
shopQuadrant.setNetProfit(netProfit);
shopQuadrant.setQuadrant(quadrant);
quadrants.add(shopQuadrant);
}
return quadrants;
}
/**
* 计算多店铺数据横向对比(16维度)
*/
private List<CompanyOverviewVO.ShopComparison> calculateShopComparisons(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, Long refundStatusId) {
List<CompanyOverviewVO.ShopComparison> comparisons = new ArrayList<>();
// 按店铺分组数据
Map<Long, List<OrderPO>> ordersByShop = orders.stream()
.collect(Collectors.groupingBy(OrderPO::getShopId));
Map<Long, List<PromotionFeePO>> promotionFeesByShop = promotionFees.stream()
.collect(Collectors.groupingBy(PromotionFeePO::getShopId));
Map<Long, List<BrushOrderPO>> brushOrdersByShop = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId));
for (ShopPO shop : shops) {
List<OrderPO> shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<PromotionFeePO> shopPromotionFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>());
List<BrushOrderPO> shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>());
// 计算各项指标
BigDecimal salesAmount = shopOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal refundAmount = shopOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal brushFee = shopBrushOrders.stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalPromotionFee = shopPromotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = calculateShopTotalCost(shopOrders);
BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount);
BigDecimal taxAmount = profitBeforeTax.multiply(TAX_RATE);
BigDecimal profitAfterTax = profitBeforeTax.subtract(taxAmount);
BigDecimal totalCostForROI = totalPromotionFee.add(brushFee);
BigDecimal roi = calculateShopROI(profitBeforeTax, totalCostForROI);
BigDecimal feeRatio = BigDecimal.ZERO;
if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
feeRatio = totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP);
}
BigDecimal averageOrderValue = BigDecimal.ZERO;
int orderCount = shopOrders.size();
if (orderCount > 0) {
averageOrderValue = salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP);
}
BigDecimal profitMargin = BigDecimal.ZERO;
if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
profitMargin = profitBeforeTax.divide(salesAmount, 4, RoundingMode.HALF_UP);
}
BigDecimal promotionFeeRatio = BigDecimal.ZERO;
if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
promotionFeeRatio = totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP);
}
BigDecimal refundRate = BigDecimal.ZERO;
if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
refundRate = refundAmount.divide(salesAmount, 4, RoundingMode.HALF_UP);
}
CompanyOverviewVO.ShopComparison comparison = new CompanyOverviewVO.ShopComparison();
comparison.setShopId(shop.getId());
comparison.setShopName(shop.getName());
comparison.setPlatform(shop.getPlatform());
comparison.setSalesAmount(salesAmount);
comparison.setRoi(roi);
comparison.setRefundAmount(refundAmount);
comparison.setBrushFee(brushFee);
comparison.setTotalPromotionFee(totalPromotionFee);
comparison.setProfitAfterTax(profitAfterTax);
comparison.setOrderCount(orderCount);
comparison.setTotalCost(totalCost);
comparison.setTotalProfitBeforeTax(profitBeforeTax);
comparison.setTaxAmount(taxAmount);
comparison.setFeeRatio(feeRatio);
comparison.setAverageOrderValue(averageOrderValue);
comparison.setProfitMargin(profitMargin);
comparison.setPromotionFeeRatio(promotionFeeRatio);
comparison.setRefundRate(refundRate);
comparisons.add(comparison);
}
// 按销售额降序排序
comparisons.sort(Comparator.comparing(CompanyOverviewVO.ShopComparison::getSalesAmount).reversed());
return comparisons;
}
/**
* 计算店铺利润(扣除退款)
*/
private BigDecimal calculateShopProfit(List<OrderPO> orders, Long refundStatusId) {
BigDecimal totalSales = orders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal refundAmount = orders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = calculateShopTotalCost(orders);
return totalSales.subtract(totalCost).subtract(refundAmount);
}
/**
* 计算店铺总成本(订单成本)
*/
private BigDecimal calculateShopTotalCost(List<OrderPO> orders) {
return orders.stream()
.map(order -> {
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return productCost.add(shippingCost).add(otherCost).multiply(new BigDecimal(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* 计算店铺总成本(推广费+刷单费)
*/
private BigDecimal calculateShopTotalCost(List<PromotionFeePO> promotionFees, List<BrushOrderPO> brushOrders) {
BigDecimal promotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal brushFee = brushOrders.stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return promotionFee.add(brushFee);
}
/**
* 计算店铺ROI
*/
private BigDecimal calculateShopROI(BigDecimal profit, BigDecimal totalCost) {
if (totalCost.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
return profit.divide(totalCost, 4, RoundingMode.HALF_UP);
}
/**
* 计算店铺净利(税后)
*/
private BigDecimal calculateShopNetProfit(BigDecimal profitBeforeTax) {
BigDecimal taxAmount = profitBeforeTax.multiply(TAX_RATE);
return profitBeforeTax.subtract(taxAmount);
}
/**
* 计算汇总ROI
*/
private BigDecimal calculateTotalROI(List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders) {
BigDecimal totalProfit = calculateTotalProfit(orders);
BigDecimal totalPromotionFee = promotionFees.stream()
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalBrushFee = brushOrders.stream()
.map(brush -> brush.getBrushAmount() != null ? brush.getBrushAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal totalCost = totalPromotionFee.add(totalBrushFee);
return calculateShopROI(totalProfit, totalCost);
}
/**
* 获取退款状态ID
*/
private Long getRefundStatusId() {
Long companyId = currentUserContext.getCurrentCompanyId();
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getStatusName, "已退款")
.last("LIMIT 1");
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
}
@@ -5,8 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
@@ -151,8 +149,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
private static final Logger logger = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
private final ImportTaskService importTaskService;
private final ProductSpecService productSpecService;
private final OrderMapper orderMapper;
@@ -194,10 +190,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
@Transactional
public void processImportTask(Long taskId) {
ImportTaskPO task = importTaskService.getById(taskId);
if (task == null) {
logger.error("导入任务不存在,taskId: {}", taskId);
return;
}
if (task == null) {
return;
}
// 更新任务状态为处理中
updateTaskStatus(taskId, "processing", null, 0, 0, 0);
@@ -211,7 +206,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
processOrderImport(task);
} else if ("product".equals(task.getType())) {
// 商品导入逻辑待实现
logger.warn("商品导入功能暂未实现,taskId: {}", taskId);
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
} else {
throw new BusinessException("不支持的导入类型: " + task.getType());
@@ -222,7 +216,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
notifyTaskProgress(task.getCreateBy(), convertToVO(completedTask));
} catch (Exception e) {
logger.error("处理导入任务失败,taskId: {}", taskId, e);
updateTaskStatus(taskId, "failed", "处理失败: " + e.getMessage(), 0, 0, 0);
ImportTaskPO failedTask = importTaskService.getById(taskId);
notifyTaskProgress(task.getCreateBy(), convertToVO(failedTask));
@@ -280,7 +273,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 尝试多种编码读取CSV文件(常见的中文编码)
java.nio.charset.Charset charset = detectFileEncoding(csvFile);
logger.info("检测到CSV文件编码: {}", charset);
try (java.io.InputStreamReader reader = new java.io.InputStreamReader(
new java.io.FileInputStream(csvFile), charset);
@@ -291,11 +283,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
.setTrim(true) // 自动去除表头和值的前后空格
.build())) {
// 记录CSV表头,用于调试
Map<String, Integer> headerMap = csvParser.getHeaderMap();
logger.info("CSV表头信息: {}", headerMap);
logger.info("字段映射信息: {}", fieldMapping);
logger.info("状态映射信息: {}", statusMapping);
List<CSVRecord> records = csvParser.getRecords();
totalCount = records.size();
@@ -312,7 +299,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(), defaultStatusId, companyId, task.getCreateBy());
// 创建订单(复用OrderService.createOrder的业务逻辑,但不依赖CurrentUserContext)
createOrderWithoutContext(orderDTO, companyId, task.getCreateBy());
createOrderWithoutContext(orderDTO, companyId, task.getCreateBy(), task.getId());
successCount++;
// 每处理10条记录通知一次进度
@@ -324,9 +311,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
} catch (Exception e) {
failCount++;
String errorMsg = String.format("第%d行处理失败: %s", rowNumber, e.getMessage());
errorMessages.append(errorMsg).append("; ");
logger.error("处理订单导入第{}行失败", rowNumber, e);
String errorMsg = String.format("第%d行:%s", rowNumber, e.getMessage());
errorMessages.append(errorMsg).append(System.lineSeparator());
// 更新失败计数
updateTaskStatus(task.getId(), "processing", null, totalCount, successCount, failCount);
@@ -358,61 +344,83 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// "statusMapping": [...]
// }
// 使用JsonNode先解析,然后手动构建对象,避免内部类反序列化问题
com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(mappingJson);
com.fasterxml.jackson.databind.JsonNode rootNode;
try {
rootNode = objectMapper.readTree(mappingJson);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new BusinessException("解析字段映射失败: JSON格式错误 - " + e.getMessage() + ",JSON内容: " + mappingJson);
}
if (!rootNode.isObject()) {
throw new BusinessException("解析字段映射失败: 映射配置必须是JSON对象,当前类型: " + rootNode.getNodeType());
}
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);
if (fieldMappingNode == null) {
throw new BusinessException("解析字段映射失败: 缺少fieldMapping字段");
}
// 解析状态映射
if (!fieldMappingNode.isArray()) {
throw new BusinessException("解析字段映射失败: fieldMapping必须是数组类型,当前类型: " + fieldMappingNode.getNodeType());
}
List<MappingField> mappingFields = new java.util.ArrayList<>();
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
if (!fieldNode.isObject()) {
continue;
}
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 (statusMappingNode != null) {
if (statusMappingNode.isArray()) {
List<StatusMapping> statusMappings = new java.util.ArrayList<>();
for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) {
if (!statusNode.isObject()) {
continue;
}
StatusMapping statusMapping = new StatusMapping();
if (statusNode.has("csvStatus")) {
statusMapping.setCsvStatus(statusNode.get("csvStatus").asText());
}
if (statusNode.has("mappedStatusId")) {
statusMapping.setMappedStatusId(statusNode.get("mappedStatusId").asLong());
}
statusMappings.add(statusMapping);
}
if (statusNode.has("mappedStatusId")) {
statusMapping.setMappedStatusId(statusNode.get("mappedStatusId").asLong());
}
statusMappings.add(statusMapping);
config.setStatusMapping(statusMappings);
}
config.setStatusMapping(statusMappings);
}
if (config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) {
throw new BusinessException("字段映射不能为空");
throw new BusinessException("解析字段映射失败: 字段映射不能为空");
}
return config;
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
logger.error("解析映射配置失败(JSON格式错误),JSON: {}", mappingJson, e);
throw new BusinessException("解析映射配置失败: JSON格式错误 - " + e.getMessage());
} catch (BusinessException e) {
// 业务异常直接抛出
throw e;
} catch (Exception e) {
logger.error("解析映射配置失败,JSON: {}", mappingJson, e);
throw new BusinessException("解析映射配置失败: " + e.getMessage());
throw new BusinessException("解析字段映射失败: " + e.getMessage());
}
}
@@ -446,14 +454,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); // 平台订单号
MappingField orderDateField = fieldMapping.get("order_time"); // 下单时间
// 调试日志:记录字段映射
if (logger.isDebugEnabled()) {
logger.debug("字段映射 - spec_code: {}, received_amount: {}, product_quantity: {}",
specCodeField != null ? specCodeField.getFileFieldName() : null,
receivedAmountField != null ? receivedAmountField.getFileFieldName() : null,
productQuantityField != null ? productQuantityField.getFileFieldName() : null);
}
// 必填字段验证
String specCode = getValue(record, specCodeField);
if (specCode == null || specCode.trim().isEmpty()) {
@@ -508,18 +508,36 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
throw new BusinessException("商品数量不能为空");
}
// 解析可选字段(先解析,用于后续创建商品和规格)
String productName = getValue(record, linkProductNameField);
productName = productName != null ? productName.trim() : null;
// 解析可选字段(优先使用链接商品名称和链接规格名称)
// 这些字段来自CSV中的 link_product_name 和 link_spec_name,用于创建商品和规格时的命名
String linkProductName = getValue(record, linkProductNameField);
// trim并转换空字符串为null
if (linkProductName != null) {
linkProductName = linkProductName.trim();
if (linkProductName.isEmpty()) {
linkProductName = null;
}
}
String productCode = getValue(record, productCodeField);
productCode = productCode != null ? productCode.trim() : null;
if (productCode != null) {
productCode = productCode.trim();
if (productCode.isEmpty()) {
productCode = null;
}
}
String specName = getValue(record, linkSpecNameField);
specName = specName != null ? specName.trim() : null;
String linkSpecName = getValue(record, linkSpecNameField);
if (linkSpecName != null) {
linkSpecName = linkSpecName.trim();
if (linkSpecName.isEmpty()) {
linkSpecName = null;
}
}
// 首先通过规格编码查找商品规格
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId);
boolean isNewSpecCreated = false; // 标记是否创建了新规格
// 如果找不到规格,则尝试通过商品编码或商品名称查找商品,然后创建规格
if (productSpec == null) {
@@ -528,63 +546,61 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 优先使用商品编码查找商品
if (productCode != null && !productCode.isEmpty()) {
product = findProductByProductCode(productCode, companyId);
if (product != null) {
logger.info("未找到规格编码 '{}',但通过商品编码 '{}' 找到了商品 '{}' (ID: {})",
specCode, productCode, product.getName(), product.getId());
}
}
// 如果商品编码查找失败,使用商品名称精准查找商品
if (product == null && productName != null && !productName.isEmpty()) {
product = findProductByName(productName, companyId);
if (product != null) {
logger.info("未找到规格编码 '{}',但通过商品名称 '{}' 找到了商品 (ID: {})",
specCode, productName, product.getId());
}
// 如果商品编码查找失败,使用链接商品名称精准查找商品
if (product == null && linkProductName != null && !linkProductName.isEmpty()) {
product = findProductByName(linkProductName, companyId);
}
// 如果找到了商品,创建规格
if (product != null) {
if (specName == null || specName.isEmpty()) {
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
",且未提供规格名称,无法创建规格");
}
logger.info("为商品 '{}' (ID: {}) 创建规格 '{}' (编码: {})",
product.getName(), product.getId(), specName, specCode);
productSpec = createSpecForProduct(companyId, product.getId(), specName, specCode.trim(), createBy);
// 优先使用链接规格名称,如果没有则使用"未知规格"
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = createSpecForProduct(companyId, product.getId(), finalSpecName, specCode.trim(), createBy);
isNewSpecCreated = true;
}
// 如果没有找到商品,但有商品名称和规格名称,则自动创建商品和规格
else if (productName != null && !productName.isEmpty() &&
specName != null && !specName.isEmpty()) {
logger.info("未找到规格编码 '{}',也未找到商品,将自动创建商品 '{}' 和规格 '{}'",
specCode, productName, specName);
productSpec = createProductAndSpecIfNotExists(companyId, productName, productCode, specName, specCode.trim(), createBy);
} else {
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
(productCode == null || productCode.isEmpty() ? "" : ",商品编码 '" + productCode + "' 未找到商品") +
(productName == null || productName.isEmpty() ? ",且未提供商品名称" : "") +
(specName == null || specName.isEmpty() ? ",且未提供规格名称" : ""));
// 如果没有找到商品,则自动创建商品和规格
else {
// 优先使用链接商品名称,如果没有则使用"未知商品"
String finalProductName = (linkProductName != null && !linkProductName.isEmpty()) ? linkProductName : "未知商品";
// 优先使用链接规格名称,如果没有则使用"未知规格"
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = createProductAndSpecIfNotExists(companyId, finalProductName, productCode, finalSpecName, specCode.trim(), createBy);
isNewSpecCreated = true;
}
}
orderDTO.setProductId(productSpec.getProductId());
orderDTO.setProductSpecId(productSpec.getId());
orderDTO.setCostPrice(productSpec.getCostPrice());
// 设置单件成本(从商品规格中获取,作为下单时快照)
orderDTO.setProductCost(productSpec.getProductCost() != null ? productSpec.getProductCost() : BigDecimal.ZERO);
orderDTO.setShippingCost(productSpec.getShippingCost() != null ? productSpec.getShippingCost() : BigDecimal.ZERO);
orderDTO.setOtherCost(productSpec.getOtherCost() != null ? productSpec.getOtherCost() : BigDecimal.ZERO);
// 设置链接商品名称和链接规格名称
if (productName != null && !productName.isEmpty()) {
orderDTO.setLinkProductName(productName);
// 优先使用CSV中的链接商品名称和链接规格名称,如果没有则使用创建的商品/规格名称
if (linkProductName != null && !linkProductName.isEmpty()) {
orderDTO.setLinkProductName(linkProductName);
} else {
// 如果CSV中没有商品名称,从商品规格关联的商品中获取
ProductPO product = productMapper.selectById(productSpec.getProductId());
orderDTO.setLinkProductName(product != null ? product.getName() : "");
orderDTO.setLinkProductName(product != null ? product.getName() : "未知商品");
}
if (specName != null && !specName.isEmpty()) {
orderDTO.setLinkSpecName(specName);
// 优先使用CSV中的链接规格名称,如果没有则使用规格的名称
if (linkSpecName != null && !linkSpecName.isEmpty()) {
orderDTO.setLinkSpecName(linkSpecName);
} else {
orderDTO.setLinkSpecName(productSpec.getName());
}
// 如果创建了新规格,订单的确认状态设为0(需要用户手动确认)
if (isNewSpecCreated) {
orderDTO.setConfirm(0);
} else {
// 如果找到已存在的规格,订单的确认状态设为1(已确认)
orderDTO.setConfirm(1);
}
String platformOrderNo = getValue(record, platformOrderNoField);
if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) {
@@ -606,25 +622,20 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 首先尝试通过状态映射转换(statusMapping中存储的是状态ID)
if (statusMapping != null && !statusMapping.isEmpty()) {
statusId = statusMapping.get(trimmedStatus);
if (statusId != null) {
logger.debug("通过状态映射转换: '{}' -> ID: {}", trimmedStatus, statusId);
}
}
// 如果状态映射没有找到,尝试直接通过状态名称查找
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);
// 用户没有做映射,且数据库中该公司没有当前状态名称,自动创建新的订单状态
statusId = createOrderStatusIfNotExists(companyId, trimmedStatus, createBy);
orderDTO.setStatusId(statusId);
}
}
@@ -634,14 +645,11 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
LocalDateTime orderTime = parseDateTime(orderDateStr.trim());
if (orderTime != null) {
orderDTO.setOrderTime(orderTime);
logger.info("成功解析下单时间: '{}' -> {}", orderDateStr.trim(), orderTime);
} else {
logger.warn("无法解析下单时间: '{}' (可能格式不支持),使用当前时间", orderDateStr);
orderDTO.setOrderTime(LocalDateTime.now());
}
} else {
// 如果没有提供下单时间,使用当前时间
logger.debug("未提供下单时间字段,使用当前时间");
orderDTO.setOrderTime(LocalDateTime.now());
}
@@ -708,29 +716,17 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
try {
if (pattern.hasTime) {
// 包含时间部分,直接解析为LocalDateTime
LocalDateTime result = LocalDateTime.parse(dateTimeStr, pattern.formatter);
if (logger.isDebugEnabled()) {
logger.debug("成功使用格式 '{}' 解析时间 '{}' -> {}", pattern.pattern, dateTimeStr, result);
}
return result;
return LocalDateTime.parse(dateTimeStr, pattern.formatter);
} else {
// 只有日期部分,解析为LocalDate后转换为LocalDateTime(时间为00:00:00)
LocalDateTime result = java.time.LocalDate.parse(dateTimeStr, pattern.formatter).atStartOfDay();
if (logger.isDebugEnabled()) {
logger.debug("成功使用格式 '{}' 解析日期 '{}' -> {}", pattern.pattern, dateTimeStr, result);
}
return result;
return java.time.LocalDate.parse(dateTimeStr, pattern.formatter).atStartOfDay();
}
} catch (DateTimeParseException e) {
// 当前格式不匹配,尝试下一个(trace级别,避免太多日志)
if (logger.isTraceEnabled()) {
logger.trace("尝试使用格式 '{}' 解析时间 '{}' 失败: {}", pattern.pattern, dateTimeStr, e.getMessage());
}
// 当前格式不匹配,尝试下一个
}
}
// 所有格式都失败
logger.warn("无法解析日期时间字符串: '{}',支持的格式包括: yyyy/MM/dd HH:mm:ss, yyyy-MM-dd HH:mm:ss 等", dateTimeStr);
return null;
}
@@ -743,7 +739,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
*/
private String getValue(CSVRecord record, MappingField mappingField) {
if (mappingField == null || mappingField.getFileFieldName() == null || mappingField.getFileFieldName().trim().isEmpty()) {
logger.debug("映射字段为空或文件字段名为空,无法获取值");
return null;
}
return getValue(record, mappingField.getFileFieldName());
@@ -758,31 +753,67 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
*/
private String getValue(CSVRecord record, String header) {
if (header == null || header.trim().isEmpty()) {
logger.debug("表头名称为空,无法获取值");
return null;
}
String trimmedHeader = header.trim();
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
// 首先尝试精确匹配(考虑CSV解析器已经设置了setTrim(true))
try {
String trimmedHeader = header.trim();
String value = record.get(trimmedHeader);
logger.debug("从表头 '{}' 获取值: '{}'", trimmedHeader, value);
return value;
return record.get(trimmedHeader);
} catch (IllegalArgumentException e) {
// 表头不存在,尝试忽略大小写匹配
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
// 精确匹配失败,尝试忽略大小写匹配
String matchedHeader = headerMap.keySet().stream()
.filter(h -> h.trim().equalsIgnoreCase(header.trim()))
.filter(h -> h.trim().equalsIgnoreCase(trimmedHeader))
.findFirst()
.orElse(null);
if (matchedHeader != null) {
return record.get(matchedHeader);
}
// 如果还是找不到,尝试包含匹配(处理可能的空格或特殊字符)
matchedHeader = headerMap.keySet().stream()
.filter(h -> h.trim().equalsIgnoreCase(trimmedHeader) ||
h.trim().replaceAll("\\s+", "").equalsIgnoreCase(trimmedHeader.replaceAll("\\s+", "")))
.findFirst()
.orElse(null);
if (matchedHeader != null) {
return record.get(matchedHeader);
}
// 处理BOM字符:尝试去除BOM后匹配(BOM字符是\uFEFF)
matchedHeader = headerMap.keySet().stream()
.filter(h -> removeBOM(h).trim().equalsIgnoreCase(trimmedHeader))
.findFirst()
.orElse(null);
if (matchedHeader != null) {
logger.debug("表头 '{}' 不存在,但找到忽略大小写的匹配: '{}'", header, matchedHeader);
return record.get(matchedHeader);
}
logger.warn("表头 '{}' 不存在,可用的表头: {}", header, headerMap.keySet());
return null;
}
}
/**
* 去除字符串开头的BOM字符
*
* @param s 字符串
* @return 去除BOM后的字符串
*/
private String removeBOM(String s) {
if (s == null || s.isEmpty()) {
return s;
}
// BOM字符是 \uFEFF
if (s.charAt(0) == '\uFEFF') {
return s.substring(1);
}
return s;
}
/**
* 通过规格编码查找商品规格
@@ -872,10 +903,11 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
productSpec.setProductId(productId);
productSpec.setName(specName);
productSpec.setSpecCode(specCode);
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
productSpec.setProductCost(BigDecimal.ZERO); // 默认商品成本为0,后续可以手动更新
productSpec.setShippingCost(BigDecimal.ZERO); // 默认运费成本为0
productSpec.setOtherCost(BigDecimal.ZERO); // 默认其他成本为0
productSpec.setCreateBy(createBy);
productSpecService.save(productSpec);
logger.info("为商品 (ID: {}) 创建规格: {} (编码: {}, ID: {})", productId, specName, specCode, productSpec.getId());
return productSpec;
}
@@ -916,7 +948,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 在检查期间商品被创建了,重新查询
product = productMapper.selectOne(productWrapper);
productId = product.getId();
logger.debug("商品在检查期间被创建: {} (ID: {})", productName, productId);
} else {
// 创建新商品(复用ProductService.createProduct的逻辑)
product = new ProductPO();
@@ -936,12 +967,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
product.setCreateBy(createBy);
productMapper.insert(product);
productId = product.getId();
logger.info("自动创建商品: {} (ID: {})" + (productCode != null && !productCode.isEmpty() ? ", 商品编码: " + productCode : ""),
productName, productId);
}
} else {
productId = product.getId();
logger.debug("商品已存在: {} (ID: {})", productName, productId);
}
// 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑)
@@ -954,9 +982,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param createOrderDTO 创建订单DTO
* @param companyId 公司ID
* @param createBy 创建人ID
* @param importTaskId 导入任务ID(可选,如果为null则表示手动创建)
* @return 订单VO
*/
private OrderVO createOrderWithoutContext(CreateOrderDTO createOrderDTO, Long companyId, Long createBy) {
private OrderVO createOrderWithoutContext(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId) {
// 复用OrderService.createOrder的验证逻辑
// 验证店铺是否存在且属于当前公司
@@ -1007,10 +1036,17 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setCostPrice(createOrderDTO.getCostPrice());
order.setProductCost(createOrderDTO.getProductCost());
order.setShippingCost(createOrderDTO.getShippingCost());
order.setOtherCost(createOrderDTO.getOtherCost());
// 备注不复制,订单导入时不设置备注字段
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setOrderTime(createOrderDTO.getOrderTime());
order.setCreateBy(createBy);
// 设置导入任务ID和确认状态
order.setImportTaskId(importTaskId);
// 使用DTO中的确认状态(如果DTO中指定了值则使用指定值,否则默认为1)
order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1);
// 保存订单
orderMapper.insert(order);
@@ -1058,9 +1094,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
relation.setSortOrder(0); // 默认排序为0
relation.setCreateBy(createBy);
shopProductRelationMapper.insert(relation);
logger.info("创建店铺商品关联: 店铺ID={}, 商品ID={}", shopId, productId);
} else {
logger.debug("店铺商品关联已存在: 店铺ID={}, 商品ID={}", shopId, productId);
}
}
@@ -1105,7 +1138,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
try {
sseNotificationService.sendTaskProgress(userId, taskVO);
} catch (Exception e) {
logger.warn("发送任务进度通知失败,userId: {}, taskId: {}", userId, taskVO != null ? taskVO.getId() : null, e);
// 静默处理通知失败
}
}
@@ -1152,17 +1185,15 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
if (content.contains("商家") || content.contains("编码") ||
content.contains("商品") || content.contains("订单") ||
content.contains("规格") || content.contains("金额")) {
logger.debug("检测到编码 {} 可能正确,内容预览: {}", charset, content.substring(0, Math.min(100, content.length())));
return charset;
}
}
} catch (Exception e) {
logger.debug("尝试编码 {} 失败: {}", charset, e.getMessage());
// 忽略编码检测错误
}
}
// 默认返回GBK(中文CSV文件最常用)
logger.warn("无法确定文件编码,使用默认GBK");
return java.nio.charset.Charset.forName("GBK");
}
@@ -1188,7 +1219,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
.last("LIMIT 1");
OrderStatusPO firstStatus = orderStatusService.getOne(wrapper);
if (firstStatus != null) {
logger.info("未找到'未知状态',使用第一个状态: {} (ID: {})", firstStatus.getStatusName(), firstStatus.getId());
return firstStatus.getId();
}
@@ -1213,5 +1243,41 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
/**
* 如果订单状态不存在,则自动创建(不依赖CurrentUserContext)
*
* @param companyId 公司ID
* @param statusName 状态名称
* @param createBy 创建人ID
* @return 订单状态ID
*/
private Long createOrderStatusIfNotExists(Long companyId, String statusName, Long createBy) {
if (statusName == null || statusName.trim().isEmpty()) {
throw new BusinessException("订单状态名称不能为空");
}
String trimmedStatusName = statusName.trim();
// 再次检查状态是否已存在(避免并发创建)
Long existingStatusId = findOrderStatusIdByName(companyId, trimmedStatusName);
if (existingStatusId != null) {
return existingStatusId;
}
// 创建新的订单状态
OrderStatusPO orderStatus = new OrderStatusPO();
orderStatus.setCompanyId(companyId);
orderStatus.setStatusName(trimmedStatusName);
orderStatus.setDescription("自动创建的状态");
orderStatus.setSortOrder(0);
orderStatus.setAutoStatistics(0); // 自动参与统计字段设置为否(0)
orderStatus.setCreateBy(createBy);
// 保存订单状态
orderStatusService.save(orderStatus);
return orderStatus.getId();
}
}
@@ -116,10 +116,16 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setCostPrice(createOrderDTO.getCostPrice());
order.setProductCost(createOrderDTO.getProductCost());
order.setShippingCost(createOrderDTO.getShippingCost());
order.setOtherCost(createOrderDTO.getOtherCost());
order.setRemark(createOrderDTO.getRemark());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setOrderTime(createOrderDTO.getOrderTime());
order.setCreateBy(currentUserContext.getCurrentUserId());
// 设置导入任务ID和确认状态(默认已确认)
order.setImportTaskId(createOrderDTO.getImportTaskId());
order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1);
// 保存订单
this.save(order);
@@ -240,6 +246,12 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
if (filter.getEndOrderTime() != null) {
wrapper.le(OrderPO::getOrderTime, filter.getEndOrderTime());
}
if (filter.getImportTaskId() != null) {
wrapper.eq(OrderPO::getImportTaskId, filter.getImportTaskId());
}
if (filter.getConfirm() != null) {
wrapper.eq(OrderPO::getConfirm, filter.getConfirm());
}
}
// 排序
@@ -58,8 +58,8 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
if (orderStatus.getSortOrder() == null) {
orderStatus.setSortOrder(0);
}
if (orderStatus.getIsDefaultStat() == null) {
orderStatus.setIsDefaultStat(1);
if (orderStatus.getAutoStatistics() == null) {
orderStatus.setAutoStatistics(1);
}
// 设置创建人ID
@@ -103,7 +103,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
productSpec.setProductId(product.getId());
productSpec.setName(specDTO.getName());
productSpec.setSpecCode(specDTO.getSpecCode());
productSpec.setCostPrice(specDTO.getCostPrice());
productSpec.setProductCost(specDTO.getProductCost());
productSpec.setShippingCost(specDTO.getShippingCost());
productSpec.setOtherCost(specDTO.getOtherCost());
productSpec.setRemark(specDTO.getRemark());
productSpec.setCreateBy(currentUserContext.getCurrentUserId());
productSpecService.save(productSpec);
@@ -211,7 +214,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
productSpec.setId(specDTO.getId());
productSpec.setName(specDTO.getName());
productSpec.setSpecCode(specDTO.getSpecCode());
productSpec.setCostPrice(specDTO.getCostPrice());
productSpec.setProductCost(specDTO.getProductCost());
productSpec.setShippingCost(specDTO.getShippingCost());
productSpec.setOtherCost(specDTO.getOtherCost());
productSpec.setRemark(specDTO.getRemark());
productSpec.setUpdateBy(currentUserContext.getCurrentUserId());
productSpecService.updateById(productSpec);
@@ -485,12 +485,15 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
Map<LocalDate, List<OrderPO>> ordersByDate, List<LocalDate> dateList, List<OrderPO> allOrders) {
ShopOverviewVO.DailyStatistics stats = new ShopOverviewVO.DailyStatistics();
// 计算总成本
// 计算总成本(单件商品成本 + 单件运费成本 + 单件其他成本) * 数量
BigDecimal total = allOrders.stream()
.map(order -> {
BigDecimal cost = order.getCostPrice() != null ? order.getCostPrice() : BigDecimal.ZERO;
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
BigDecimal unitCost = productCost.add(shippingCost).add(otherCost);
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 0;
return cost.multiply(BigDecimal.valueOf(quantity));
return unitCost.multiply(BigDecimal.valueOf(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
stats.setTotal(total);
@@ -503,9 +506,12 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
List<OrderPO> dayOrders = ordersByDate.getOrDefault(date, List.of());
BigDecimal dayCost = dayOrders.stream()
.map(order -> {
BigDecimal cost = order.getCostPrice() != null ? order.getCostPrice() : BigDecimal.ZERO;
BigDecimal productCost = order.getProductCost() != null ? order.getProductCost() : BigDecimal.ZERO;
BigDecimal shippingCost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
BigDecimal otherCost = order.getOtherCost() != null ? order.getOtherCost() : BigDecimal.ZERO;
BigDecimal unitCost = productCost.add(shippingCost).add(otherCost);
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 0;
return cost.multiply(BigDecimal.valueOf(quantity));
return unitCost.multiply(BigDecimal.valueOf(quantity));
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
dailyData.setValue(dayCost);
@@ -52,7 +52,10 @@ CREATE TABLE `ec_product_spec` (
`product_id` BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
`name` VARCHAR(200) NOT NULL COMMENT '规格名称',
`spec_code` VARCHAR(100) DEFAULT NULL COMMENT '规格编码',
`cost_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '成本价',
`product_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`shipping_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
`remark` VARCHAR(500) DEFAULT 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',
@@ -76,7 +79,7 @@ CREATE TABLE `ec_order_status` (
`status_name` VARCHAR(100) NOT NULL COMMENT '状态名称(中文)',
`description` VARCHAR(200) DEFAULT NULL COMMENT '状态描述',
`sort_order` INT NOT NULL DEFAULT 0 COMMENT '排序',
`is_default_stat` TINYINT NOT NULL DEFAULT 1 COMMENT '是否默认参与统计 0不参与 1参与',
`auto_statistics` 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 +88,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_default_stat` (`is_default_stat`),
KEY `idx_auto_statistics` (`auto_statistics`),
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,
@@ -107,7 +110,12 @@ CREATE TABLE `ec_order` (
`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 '成本价(下单时快照)',
`product_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '单件商品成本(下单时快照)',
`shipping_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '单件运费成本(下单时快照)',
`other_cost` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '单件其他成本(下单时快照)',
`remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
`import_task_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '导入任务ID',
`confirm` TINYINT NOT NULL DEFAULT 1 COMMENT '确认(0-否 1-是)',
`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 '更新时间',
@@ -119,6 +127,8 @@ CREATE TABLE `ec_order` (
KEY `idx_platform_order_no` (`platform_order_no`),
KEY `idx_product_id` (`product_id`),
KEY `idx_product_spec_id` (`product_spec_id`),
KEY `idx_import_task_id` (`import_task_id`),
KEY `idx_confirm` (`confirm`),
KEY `fk_ec_order_creator` (`create_by`),
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,
@@ -126,6 +136,7 @@ CREATE TABLE `ec_order` (
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_import_task` FOREIGN KEY (`import_task_id`) REFERENCES `ec_import_tasks` (`id`) ON DELETE SET NULL 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='电商-订单表(含商品明细)';
@@ -282,3 +293,37 @@ CREATE TABLE `ec_shop_product_relation` (
CONSTRAINT `fk_ec_shop_product_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_shop_product_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_brush_order` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '刷单记录ID',
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` BIGINT UNSIGNED NOT NULL COMMENT '店铺ID',
`product_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商品ID(可选)',
`product_spec_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商品规格ID(可选)',
`brush_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '刷单金额',
`brush_time` TIMESTAMP NOT NULL COMMENT '刷单时间',
`platform_order_no` VARCHAR(100) DEFAULT NULL COMMENT '平台订单号(可选)',
`quantity` INT DEFAULT 1 COMMENT '刷单数量',
`remark` VARCHAR(500) DEFAULT 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_id` (`company_id`),
KEY `idx_shop_id` (`shop_id`),
KEY `idx_product_id` (`product_id`),
KEY `idx_product_spec_id` (`product_spec_id`),
KEY `idx_brush_time` (`brush_time`),
KEY `idx_platform_order_no` (`platform_order_no`),
KEY `idx_company_shop_time` (`company_id`, `shop_id`, `brush_time`),
KEY `fk_ec_brush_order_creator` (`create_by`),
KEY `fk_ec_brush_order_updater` (`update_by`),
CONSTRAINT `fk_ec_brush_order_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_brush_order_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_brush_order_product` FOREIGN KEY (`product_id`) REFERENCES `ec_product` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_brush_order_product_spec` FOREIGN KEY (`product_spec_id`) REFERENCES `ec_product_spec` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_brush_order_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_brush_order_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电商-刷单记录表';
@@ -56,8 +56,8 @@ mybatis-plus:
configuration:
# 驼峰命名转换
map-underscore-to-camel-case: true
# 打印SQL日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 打印SQL日志(已关闭)
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# knife4j配置
springdoc:
@@ -109,6 +109,6 @@ knife4j:
# 日志配置
logging:
level:
top.xyquan.ecomdmbbackend: DEBUG
org.springframework.security: DEBUG
org.springframework.web: DEBUG
top.xyquan.ecomdmbbackend: INFO
org.springframework.security: INFO
org.springframework.web: INFO
@@ -0,0 +1,55 @@
import type { BrushOrderDTO, BrushOrderVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
/**
* 刷单记录管理API
*/
/**
* 创建刷单记录
*/
export async function createBrushOrderApi(data: BrushOrderDTO.Create) {
return requestClient.post<BrushOrderVO.Info>('/ec/brush-order/create', data);
}
/**
* 更新刷单记录
*/
export async function updateBrushOrderApi(
id: number,
data: BrushOrderDTO.Update,
) {
return requestClient.put<BrushOrderVO.Info>(
`/ec/brush-order/update/${id}`,
data,
);
}
/**
* 删除刷单记录
*/
export async function deleteBrushOrderApi(id: number) {
return requestClient.delete(`/ec/brush-order/delete/${id}`);
}
/**
* 分页获取刷单记录列表
*/
export async function getBrushOrderPageApi(
params: PageQueryDTO<BrushOrderDTO.Filters>,
) {
return requestClient.post<PageResultVO<BrushOrderVO.Info>>(
'/ec/brush-order/page',
params,
);
}
/**
* 获取刷单记录详情
*/
export async function getBrushOrderByIdApi(id: number) {
return requestClient.get<BrushOrderVO.Info>(`/ec/brush-order/detail/${id}`);
}
@@ -0,0 +1,6 @@
/**
* 刷单记录管理模块API导出
*/
export * from './apis';
export * from './types';
@@ -0,0 +1,6 @@
/**
* 刷单记录管理模块类型定义导出
*/
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,63 @@
/**
* 刷单记录相关DTO类型定义
*/
export namespace BrushOrderDTO {
/** 创建刷单记录参数 */
export interface Create {
/** 店铺ID */
shopId: number;
/** 商品ID(可选) */
productId?: number;
/** 商品规格ID(可选) */
productSpecId?: number;
/** 刷单金额 */
brushAmount: number;
/** 刷单时间 */
brushTime: string;
/** 平台订单号(可选) */
platformOrderNo?: string;
/** 刷单数量 */
quantity?: number;
/** 备注 */
remark?: string;
}
/** 更新刷单记录参数 */
export interface Update {
/** 店铺ID */
shopId: number;
/** 商品ID(可选) */
productId?: number;
/** 商品规格ID(可选) */
productSpecId?: number;
/** 刷单金额 */
brushAmount: number;
/** 刷单时间 */
brushTime: string;
/** 平台订单号(可选) */
platformOrderNo?: string;
/** 刷单数量 */
quantity?: number;
/** 备注 */
remark?: string;
}
/** 刷单记录过滤条件 */
export interface Filters {
/** 店铺ID */
shopId?: number;
/** 商品ID */
productId?: number;
/** 平台订单号(模糊查询) */
platformOrderNo?: string;
/** 刷单金额范围-最小值 */
minBrushAmount?: number;
/** 刷单金额范围-最大值 */
maxBrushAmount?: number;
/** 刷单时间范围-开始时间 */
startBrushTime?: string;
/** 刷单时间范围-结束时间 */
endBrushTime?: string;
}
}
@@ -0,0 +1,43 @@
/**
* 刷单记录相关VO类型定义
*/
export namespace BrushOrderVO {
/** 刷单记录信息 */
export interface Info {
/** 刷单记录ID */
id: number;
/** 公司ID */
companyId: number;
/** 店铺ID */
shopId: number;
/** 店铺名称 */
shopName: string;
/** 商品ID */
productId?: number;
/** 商品名称 */
productName?: string;
/** 商品规格ID */
productSpecId?: number;
/** 商品规格名称 */
productSpecName?: string;
/** 刷单金额 */
brushAmount: number;
/** 刷单时间 */
brushTime: string;
/** 平台订单号 */
platformOrderNo?: string;
/** 刷单数量 */
quantity?: number;
/** 备注 */
remark?: string;
/** 创建时间 */
createTime: string;
/** 更新时间 */
updateTime: string;
/** 创建人ID */
createBy?: number;
/** 更新人ID */
updateBy?: number;
}
}
@@ -0,0 +1,17 @@
import type { CompanyOverviewDTO, CompanyOverviewVO } from './types';
import { requestClient } from '#/api/request';
/**
* 全店铺概览管理API
*/
/**
* 获取全店铺概览统计数据
*/
export async function getCompanyOverviewApi(data: CompanyOverviewDTO.Query) {
return requestClient.post<CompanyOverviewVO.Info>(
'/ec/company-overview/statistics',
data,
);
}
@@ -0,0 +1,6 @@
/**
* 全店铺概览管理模块API导出
*/
export * from './apis';
export * from './types';
@@ -0,0 +1,6 @@
/**
* 全店铺概览管理模块类型定义导出
*/
export * from './types.dto';
export * from './types.vo';
@@ -0,0 +1,11 @@
/**
* 全店铺概览相关DTO类型定义
*/
export namespace CompanyOverviewDTO {
/** 全店铺概览查询参数 */
export interface Query {
/** 日期范围数组(第一个是开始日期,第二个是结束日期,只有一个日期则返回当天数据) */
dateRange: string[];
}
}
@@ -0,0 +1,99 @@
/**
* 全店铺概览相关VO类型定义
*/
export namespace CompanyOverviewVO {
/** 全店铺概览信息 */
export interface Info {
/** 全店总销售额 */
totalSalesAmount: number;
/** 较上月同期增长百分比 */
monthOverMonthGrowth?: number;
/** 全店总单量 */
totalOrderCount: number;
/** 总推广费支出 */
totalPromotionFee: number;
/** 平均费比(推广费/销售额) */
averageFeeRatio?: number;
/** 全店总净利(税后) */
totalNetProfitAfterTax: number;
/** 扣除总税额 */
totalTaxAmount?: number;
/** 各店铺销售占比排行 */
shopSalesRatios?: ShopSalesRatio[];
/** 店铺效率象限(ROI vs 净利) */
shopEfficiencyQuadrants?: ShopEfficiencyQuadrant[];
/** 多店铺数据横向对比(16维度) */
shopComparisons?: ShopComparison[];
/** 汇总ROI */
totalROI?: number;
/** 总税后盈亏 */
totalProfitAfterTax?: number;
}
/** 店铺销售占比 */
export interface ShopSalesRatio {
/** 店铺ID */
shopId: number;
/** 店铺名称 */
shopName: string;
/** 销售额 */
salesAmount: number;
/** 占比百分比 */
ratio: number;
}
/** 店铺效率象限 */
export interface ShopEfficiencyQuadrant {
/** 店铺ID */
shopId: number;
/** 店铺名称 */
shopName: string;
/** ROI */
roi: number;
/** 净利 */
netProfit: number;
/** 象限(1-高ROI高净利,2-高ROI低净利,3-低ROI高净利,4-低ROI低净利) */
quadrant: number;
}
/** 店铺对比数据(16维度) */
export interface ShopComparison {
/** 店铺ID */
shopId: number;
/** 店铺名称 */
shopName: string;
/** 平台 */
platform?: string;
/** 销售额 */
salesAmount: number;
/** ROI */
roi?: number;
/** 退款金额 */
refundAmount?: number;
/** 刷单费 */
brushFee?: number;
/** 推广费总和 */
totalPromotionFee?: number;
/** 税后盈亏 */
profitAfterTax?: number;
/** 订单数量 */
orderCount?: number;
/** 总成本 */
totalCost?: number;
/** 总利润(税前) */
totalProfitBeforeTax?: number;
/** 税额 */
taxAmount?: number;
/** 费比 */
feeRatio?: number;
/** 客单价 */
averageOrderValue?: number;
/** 利润率 */
profitMargin?: number;
/** 推广费占比 */
promotionFeeRatio?: number;
/** 退款率 */
refundRate?: number;
}
}
@@ -11,8 +11,8 @@ export namespace OrderStatusDTO {
description?: string;
/** 排序 */
sortOrder?: number;
/** 是否默认参与统计 0不参与 1参与 */
isDefaultStat: number;
/** 自动统计 0不参与 1参与 */
autoStatistics: number;
}
/** 更新订单状态参数 */
@@ -23,7 +23,7 @@ export namespace OrderStatusDTO {
description?: string;
/** 排序 */
sortOrder?: number;
/** 是否默认参与统计 0不参与 1参与 */
isDefaultStat: number;
/** 自动统计 0不参与 1参与 */
autoStatistics: number;
}
}
@@ -15,8 +15,8 @@ export namespace OrderStatusVO {
description?: string;
/** 排序 */
sortOrder?: number;
/** 是否默认参与统计 0不参与 1参与 */
isDefaultStat: number;
/** 自动统计 0不参与 1参与 */
autoStatistics: number;
/** 创建时间 */
createTime: string;
/** 更新时间 */
@@ -27,8 +27,14 @@ export namespace OrderDTO {
quantity: number;
/** 销售单价 */
unitPrice: number;
/** 成本价(下单时快照) */
costPrice: number;
/** 单件商品成本(下单时快照) */
productCost: number;
/** 单件运费成本(下单时快照) */
shippingCost?: number;
/** 单件其他成本(下单时快照) */
otherCost?: number;
/** 备注 */
remark?: string;
}
/** 更新订单参数 */
@@ -55,8 +61,14 @@ export namespace OrderDTO {
quantity?: number;
/** 销售单价 */
unitPrice?: number;
/** 成本价(下单时快照) */
costPrice?: number;
/** 单件商品成本(下单时快照) */
productCost?: number;
/** 单件运费成本(下单时快照) */
shippingCost?: number;
/** 单件其他成本(下单时快照) */
otherCost?: number;
/** 备注 */
remark?: string;
}
/** 订单过滤条件 */
@@ -43,8 +43,14 @@ export namespace OrderVO {
quantity: number;
/** 销售单价 */
unitPrice: number;
/** 成本价(下单时快照) */
costPrice: number;
/** 单件商品成本(下单时快照) */
productCost: number;
/** 单件运费成本(下单时快照) */
shippingCost?: number;
/** 单件其他成本(下单时快照) */
otherCost?: number;
/** 备注 */
remark?: string;
}
}
@@ -11,18 +11,32 @@ export namespace ProductSpecDTO {
name: string;
/** 规格编码 */
specCode?: string;
/** 成本价 */
costPrice: number;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 备注 */
remark?: string;
}
/** 更新商品规格参数 */
export interface Update {
/** 规格ID */
id: number;
/** 规格名称 */
name: string;
/** 规格编码 */
specCode?: string;
/** 成本价 */
costPrice: number;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 备注 */
remark?: string;
}
/** 商品规格过滤条件 */
@@ -17,8 +17,14 @@ export namespace ProductSpecVO {
name: string;
/** 规格编码 */
specCode?: string;
/** 成本价 */
costPrice: number;
/** 商品成本 */
productCost: number;
/** 运费成本 */
shippingCost?: number;
/** 其他成本 */
otherCost?: number;
/** 备注 */
remark?: string;
/** 创建时间 */
createTime: string;
/** 更新时间 */
@@ -0,0 +1,449 @@
<script setup lang="ts">
import type { BrushOrderDTO, BrushOrderVO } from '#/api/ecommerce/brush-order';
import type {
ProductSpecDTO,
ProductSpecVO,
} from '#/api/ecommerce/product-spec/types';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
Spin,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
createBrushOrderApi,
updateBrushOrderApi,
} from '#/api/ecommerce/brush-order';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getProductSpecPageApi } from '#/api/ecommerce/product-spec';
import { getShopPageApi } from '#/api/ecommerce/shop';
defineOptions({ name: 'BrushOrderFormModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// Props
interface Props {
open: boolean;
brushOrderData?: null | BrushOrderVO.Info;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
onCancel() {
handleCancel();
},
onConfirm() {
handleOk();
},
});
// 响应式数据
const formRef = ref();
const isEdit = ref(false);
// 表单数据
const formData = ref<BrushOrderDTO.Create>({
shopId: undefined as any,
productId: undefined,
productSpecId: undefined,
brushAmount: undefined as any,
brushTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
platformOrderNo: undefined,
quantity: 1,
remark: undefined,
});
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
brushAmount: [
{ required: true, message: '请输入刷单金额', trigger: 'blur' },
{ type: 'number', min: 0, message: '刷单金额必须大于等于0', trigger: 'blur' },
],
brushTime: [{ required: true, message: '请选择刷单时间', trigger: 'change' }],
} as any;
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 商品选项数据
const productOptions = ref<
{ label: string; product: ProductVO.Info; value: number }[]
>([]);
const productLoading = ref(false);
const productSearchKeyword = ref('');
// 规格选项数据
const productSpecOptions = ref<
{ label: string; spec: ProductSpecVO.Info; value: number }[]
>([]);
const productSpecLoading = ref(false);
const productSpecSearchKeyword = ref('');
// 处理日期选择器的双向绑定
const brushTimeValue = computed({
get() {
return formData.value.brushTime
? dayjs(formData.value.brushTime, 'YYYY-MM-DD HH:mm:ss')
: null;
},
set(value: any) {
formData.value.brushTime = value
? value.format('YYYY-MM-DD HH:mm:ss')
: '';
},
});
// 监听props变化
watch(
() => props.open,
(newVal) => {
if (newVal) {
modalApi.open();
isEdit.value = !!props.brushOrderData;
if (props.brushOrderData) {
// 编辑模式,填充表单数据
formData.value = {
shopId: props.brushOrderData.shopId,
productId: props.brushOrderData.productId,
productSpecId: props.brushOrderData.productSpecId,
brushAmount: props.brushOrderData.brushAmount,
brushTime: props.brushOrderData.brushTime
? dayjs(props.brushOrderData.brushTime).format('YYYY-MM-DD HH:mm:ss')
: dayjs().format('YYYY-MM-DD HH:mm:ss'),
platformOrderNo: props.brushOrderData.platformOrderNo,
quantity: props.brushOrderData.quantity || 1,
remark: props.brushOrderData.remark,
};
// 如果有商品ID,加载商品和规格选项
if (props.brushOrderData.productId) {
searchProducts('');
if (props.brushOrderData.productSpecId) {
searchProductSpecs('');
}
}
} else {
// 新增模式,重置表单数据
resetFormData();
}
} else {
modalApi.close();
}
},
{ immediate: true },
);
// 加载店铺列表
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
// 搜索商品
async function searchProducts(keyword: string) {
productSearchKeyword.value = keyword;
productLoading.value = true;
try {
const params: PageQueryDTO<ProductDTO.Filters> = {
page: 1,
pageSize: 50,
filters: {
name: keyword || undefined,
},
};
const data = await getProductPageApi(params);
productOptions.value = data.records.map((product: ProductVO.Info) => ({
label: `${product.name}${product.productCode ? ` (${product.productCode})` : ''}`,
value: product.id,
product,
}));
} catch (error) {
console.error('搜索商品失败:', error);
message.error('搜索商品失败');
} finally {
productLoading.value = false;
}
}
// 搜索规格
async function searchProductSpecs(keyword: string) {
if (!formData.value.productId) {
productSpecOptions.value = [];
return;
}
productSpecSearchKeyword.value = keyword;
productSpecLoading.value = true;
try {
const params: PageQueryDTO<ProductSpecDTO.Filters> = {
page: 1,
pageSize: 50,
filters: {
productId: formData.value.productId,
name: keyword || undefined,
},
};
const data = await getProductSpecPageApi(params);
productSpecOptions.value = data.records.map((spec: ProductSpecVO.Info) => ({
label: `${spec.name}${spec.specCode ? ` (${spec.specCode})` : ''}`,
value: spec.id,
spec,
}));
} catch (error) {
console.error('搜索规格失败:', error);
message.error('搜索规格失败');
} finally {
productSpecLoading.value = false;
}
}
// 处理商品选择
function handleProductChange(productId: number | undefined) {
if (!productId) {
formData.value.productSpecId = undefined;
productSpecOptions.value = [];
} else {
// 加载该商品的规格列表
searchProductSpecs('');
}
}
// 监听商品ID变化,加载规格列表
watch(
() => formData.value.productId,
(newProductId) => {
if (newProductId) {
searchProductSpecs('');
} else {
productSpecOptions.value = [];
formData.value.productSpecId = undefined;
}
},
);
// 重置表单数据
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
productId: undefined,
productSpecId: undefined,
brushAmount: undefined as any,
brushTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
platformOrderNo: undefined,
quantity: 1,
remark: undefined,
};
productOptions.value = [];
productSpecOptions.value = [];
};
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (isEdit.value && props.brushOrderData) {
// 更新刷单记录
await updateBrushOrderApi(props.brushOrderData.id, formData.value);
message.success('更新成功');
} else {
// 创建刷单记录
await createBrushOrderApi(formData.value);
message.success('创建成功');
}
emit('success');
modalApi.close();
emit('update:open', false);
} catch (error) {
if ((error as any)?.errorFields) {
// 表单验证错误
return;
}
console.error('操作失败:', error);
message.error(isEdit.value ? '更新失败' : '创建失败');
}
};
// 取消操作
const handleCancel = () => {
emit('cancel');
modalApi.close();
emit('update:open', false);
resetFormData();
};
// 组件挂载时加载数据
onMounted(() => {
loadShopList();
});
</script>
<template>
<Modal :title="isEdit ? '编辑刷单记录' : '新增刷单记录'">
<Form
ref="formRef"
:model="formData"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="店铺" name="shopId">
<Select
v-model:value="formData.shopId"
placeholder="请选择店铺"
:loading="shopListLoading"
>
<Select.Option
v-for="shop in shopList"
:key="shop.id"
:value="shop.id"
>
{{ shop.name }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="商品" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选)"
show-search
:filter-option="false"
:loading="productLoading"
allow-clear
@search="searchProducts"
@change="handleProductChange"
>
<template #notFoundContent>
<div v-if="productLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
请输入关键词搜索商品
</div>
</template>
<Select.Option
v-for="option in productOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="商品规格" name="productSpecId">
<Select
v-model:value="formData.productSpecId"
placeholder="请选择商品规格(可选)"
show-search
:filter-option="false"
:loading="productSpecLoading"
:disabled="!formData.productId"
allow-clear
@search="searchProductSpecs"
>
<template #notFoundContent>
<div v-if="productSpecLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
{{ formData.productId ? '请输入关键词搜索规格' : '请先选择商品' }}
</div>
</template>
<Select.Option
v-for="option in productSpecOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="刷单金额" name="brushAmount">
<InputNumber
v-model:value="formData.brushAmount"
placeholder="请输入刷单金额"
:min="0"
:precision="2"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="刷单时间" name="brushTime">
<DatePicker
v-model:value="brushTimeValue"
placeholder="请选择刷单时间"
show-time
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="平台订单号" name="platformOrderNo">
<Input
v-model:value="formData.platformOrderNo"
placeholder="请输入平台订单号(可选)"
/>
</Form.Item>
<Form.Item label="刷单数量" name="quantity">
<InputNumber
v-model:value="formData.quantity"
placeholder="请输入刷单数量"
:min="1"
:precision="0"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注(可选)"
:rows="3"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,383 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { BrushOrderDTO, BrushOrderVO } from '#/api/ecommerce/brush-order';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteBrushOrderApi,
getBrushOrderPageApi,
} from '#/api/ecommerce/brush-order';
import { getShopPageApi } from '#/api/ecommerce/shop';
import BrushOrderFormModal from './components/BrushOrderFormModal.vue';
defineOptions({ name: 'BrushOrderManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false);
const formModalVisible = ref(false);
const currentBrushOrderData = ref<BrushOrderVO.Info | null>(null);
// 搜索表单
const searchForm = ref({
platformOrderNo: '',
shopId: undefined as number | undefined,
productId: undefined as number | undefined,
minBrushAmount: undefined as number | undefined,
maxBrushAmount: undefined as number | undefined,
startBrushTime: undefined as string | undefined,
endBrushTime: undefined as string | undefined,
});
// 店铺选项(从搜索表单中获取)
const shopOptions = ref<{ label: string; value: number }[]>([]);
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
field: 'platformOrderNo',
title: '平台订单号',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'shopName',
title: '店铺名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
title: '商品信息',
minWidth: 'auto',
slots: { default: 'productInfo' },
},
{
field: 'quantity',
title: '刷单数量',
minWidth: 'auto',
},
{
title: '刷单金额',
minWidth: 'auto',
slots: { default: 'brushAmount' },
},
{
field: 'brushTime',
title: '刷单时间',
minWidth: 'auto',
},
{
field: 'createTime',
title: '创建时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
highlightHoverRow: true,
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<BrushOrderDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
platformOrderNo: searchForm.value.platformOrderNo || undefined,
shopId: searchForm.value.shopId,
productId: searchForm.value.productId,
minBrushAmount: searchForm.value.minBrushAmount,
maxBrushAmount: searchForm.value.maxBrushAmount,
startBrushTime: searchForm.value.startBrushTime,
endBrushTime: searchForm.value.endBrushTime,
},
};
const data = await getBrushOrderPageApi(params);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取刷单记录列表失败:', error);
message.error('获取刷单记录列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 搜索表单配置
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入平台订单号',
},
fieldName: 'platformOrderNo',
label: '平台订单号',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择店铺',
options: shopOptions.value,
allowClear: true,
},
fieldName: 'shopId',
label: '店铺',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最小金额',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'minBrushAmount',
label: '金额范围',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最大金额',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'maxBrushAmount',
label: '',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '开始时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
style: { width: '100%' },
},
fieldName: 'startBrushTime',
label: '刷单时间',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '结束时间',
showTime: true,
format: 'YYYY-MM-DD HH:mm:ss',
style: { width: '100%' },
},
fieldName: 'endBrushTime',
label: '',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '刷单记录管理',
});
// 处理新增
const handleAdd = () => {
currentBrushOrderData.value = null;
formModalVisible.value = true;
};
// 处理编辑
const handleEdit = (record: BrushOrderVO.Info) => {
currentBrushOrderData.value = record;
formModalVisible.value = true;
};
// 处理删除
const handleDelete = async (id: number) => {
try {
await deleteBrushOrderApi(id);
message.success('删除成功');
refreshTable();
} catch {
message.error('删除失败');
}
};
// 处理表单成功
const handleFormSuccess = () => {
refreshTable();
};
// 格式化金额
const formatAmount = (amount: number) => {
return `¥${amount.toFixed(2)}`;
};
// 加载店铺选项
const loadShopOptions = async () => {
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopOptions.value = response.records.map((shop: ShopVO.Info) => ({
label: shop.name,
value: shop.id,
}));
} catch (error) {
console.error('加载店铺列表失败:', error);
}
};
// 组件挂载时加载数据
onMounted(() => {
loadShopOptions();
});
</script>
<template>
<Page title="刷单记录管理" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理店铺刷单记录,支持按店铺、商品、金额、时间等维度查询和统计
</div>
</template>
<template #extra>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
新增刷单记录
</Button>
</Space>
</template>
<!-- 数据表格 -->
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<span class="text-gray-500">
支持按店铺、商品、金额、时间等维度查询刷单记录
</span>
</Space>
</template>
<!-- 商品信息列 -->
<template #productInfo="{ row }: { row: any }">
<div v-if="row.productName">
<div style="font-weight: bold">{{ row.productName }}</div>
<div v-if="row.productSpecName" style="color: #666; font-size: 12px">
{{ row.productSpecName }}
</div>
</div>
<span v-else class="text-gray-400">-</span>
</template>
<!-- 刷单金额列 -->
<template #brushAmount="{ row }: { row: any }">
<span class="font-medium text-green-600">
{{ formatAmount(row.brushAmount || 0) }}
</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Popconfirm
title="确定要删除这条刷单记录吗?"
@confirm="handleDelete(row.id)"
>
<Button size="small" danger> 删除 </Button>
</Popconfirm>
</Space>
</template>
</Grid>
<!-- 表单弹窗 -->
<BrushOrderFormModal
v-model:open="formModalVisible"
:brush-order-data="currentBrushOrderData"
@success="handleFormSuccess"
@cancel="formModalVisible = false"
/>
</Page>
</template>
@@ -0,0 +1,597 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import type {
CompanyOverviewDTO,
CompanyOverviewVO,
} from '#/api/ecommerce/company-overview';
import { onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { Button, DatePicker, message, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getCompanyOverviewApi } from '#/api/ecommerce/company-overview';
import { getShopPageApi } from '#/api/ecommerce/shop';
defineOptions({ name: 'CompanyOverview' });
// 响应式数据
const loading = ref(false);
const overviewData = ref<CompanyOverviewVO.Info | null>(null);
const shopCount = ref(0);
// 日期范围
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().subtract(30, 'day'),
dayjs(),
]);
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'custom' | 'today' | 'yesterday'
>('30days');
// 自定义日期范围
const customDateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>(undefined);
// 切换时间范围
const switchTimeRange = (
type: '7days' | '30days' | 'custom' | 'today' | 'yesterday',
) => {
activeTimeRange.value = type;
let startDate: dayjs.Dayjs;
let endDate: dayjs.Dayjs = dayjs();
switch (type) {
case '7days': {
startDate = dayjs().subtract(7, 'day');
break;
}
case '30days': {
startDate = dayjs().subtract(30, 'day');
break;
}
case 'custom': {
if (customDateRange.value) {
dateRange.value = customDateRange.value;
}
return;
}
case 'today': {
startDate = dayjs();
endDate = dayjs();
break;
}
case 'yesterday': {
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
}
dateRange.value = [startDate, endDate];
};
// 自定义日期范围变化
const handleCustomDateRangeChange = (
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
_dateString?: [string, string],
) => {
if (value && Array.isArray(value) && value.length === 2) {
// 确保是 dayjs 对象
const dates = [
dayjs.isDayjs(value[0]) ? value[0] : dayjs(value[0]),
dayjs.isDayjs(value[1]) ? value[1] : dayjs(value[1]),
] as [dayjs.Dayjs, dayjs.Dayjs];
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
}
};
// 图表引用
const barChartRef = ref<EchartsUIType>();
const scatterChartRef = ref<EchartsUIType>();
const { renderEcharts: renderBarChart } = useEcharts(barChartRef);
const { renderEcharts: renderScatterChart } = useEcharts(scatterChartRef);
// 格式化金额
const formatAmount = (amount: number) => {
return `¥${(amount / 10_000).toFixed(2)}万`;
};
// 格式化金额(完整)
const formatAmountFull = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN')}`;
};
// 格式化百分比
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
// 加载店铺数量
const loadShopCount = async () => {
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1,
filters: {},
});
shopCount.value = response.total || 0;
} catch (error) {
console.error('获取店铺数量失败:', error);
}
};
// 加载概览数据
const loadOverviewData = async () => {
try {
loading.value = true;
const params: CompanyOverviewDTO.Query = {
dateRange: [
dateRange.value[0].format('YYYY-MM-DD'),
dateRange.value[1].format('YYYY-MM-DD'),
],
};
const data = await getCompanyOverviewApi(params);
overviewData.value = data;
} catch (error) {
console.error('获取全店概览数据失败:', error);
message.error('获取全店概览数据失败');
} finally {
loading.value = false;
}
};
// 渲染店铺销售占比排行图表
const renderShopBarChart = () => {
if (!barChartRef.value || !overviewData.value?.shopSalesRatios) return;
const ratios = overviewData.value.shopSalesRatios;
const shopNames = ratios.map((r) => r.shopName).reverse();
const salesAmounts = ratios.map((r) => r.salesAmount / 1000).reverse(); // 转换为千元
renderBarChart({
tooltip: {
trigger: 'axis',
formatter: (params: any) => {
const param = Array.isArray(params) ? params[0] : params;
const index = param.dataIndex;
const shop = ratios[ratios.length - 1 - index];
if (!shop) return '';
return `${shop.shopName}<br/>销售额: ${formatAmountFull(shop.salesAmount)}<br/>占比: ${shop.ratio.toFixed(2)}%`;
},
},
xAxis: {
type: 'value',
show: false,
},
yAxis: {
type: 'category',
data: shopNames,
axisLine: { show: false },
},
series: [
{
type: 'bar',
data: salesAmounts,
itemStyle: {
color: {
type: 'linear',
x: 1,
y: 0,
x2: 0,
y2: 0,
colorStops: [
{ offset: 0, color: '#6366f1' },
{ offset: 1, color: '#a5b4fc' },
],
},
borderRadius: [0, 10, 10, 0],
},
barWidth: 25,
},
],
});
};
// 渲染店铺效率象限图
const renderShopScatterChart = () => {
if (!scatterChartRef.value || !overviewData.value?.shopEfficiencyQuadrants)
return;
const quadrants = overviewData.value.shopEfficiencyQuadrants;
const data = quadrants.map((q) => [q.roi, q.netProfit / 1000]); // 净利转换为千元
renderScatterChart({
grid: {
top: '10%',
bottom: '10%',
left: '10%',
right: '10%',
},
tooltip: {
trigger: 'item',
formatter: (params: any) => {
const index = params.dataIndex;
const shop = quadrants[index];
if (!shop) return '';
return `${shop.shopName}<br/>ROI: ${shop.roi.toFixed(2)}<br/>净利: ${formatAmountFull(shop.netProfit)}`;
},
},
xAxis: {
name: 'ROI',
nameLocation: 'middle',
nameGap: 30,
splitLine: {
lineStyle: {
type: 'dashed',
},
},
},
yAxis: {
name: '净利(千元)',
nameLocation: 'middle',
nameGap: 50,
splitLine: {
lineStyle: {
type: 'dashed',
},
},
},
series: [
{
type: 'scatter',
symbolSize: 40,
data,
itemStyle: {
color: '#6366f1',
opacity: 0.6,
},
},
],
});
};
// 监听数据变化,重新渲染图表
watch(
() => overviewData.value,
() => {
if (overviewData.value) {
// 使用 setTimeout 确保 DOM 已更新
setTimeout(() => {
renderShopBarChart();
renderShopScatterChart();
}, 100);
}
},
{ deep: true },
);
// 监听日期范围变化
watch(
() => dateRange.value,
() => {
loadOverviewData();
},
);
// 初始化
onMounted(async () => {
await loadShopCount();
await loadOverviewData();
});
</script>
<template>
<Page
title="全店铺经营大盘"
auto-content-height
class="bg-gradient-to-br from-rose-50 via-indigo-50 to-green-50"
>
<template #description>
<div class="font-bold text-indigo-600">
Company Dashboard · 共 {{ shopCount }} 家在营店铺
</div>
</template>
<template #extra>
<div class="flex items-center gap-4">
<!-- 汇总 ROI 和总税后盈亏 -->
<div
class="flex items-center gap-6 rounded-[2rem] border border-white/60 bg-white/50 px-6 py-3 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="text-center">
<div class="text-[10px] font-bold uppercase text-slate-400">
汇总 ROI
</div>
<div class="text-lg font-black">
{{ overviewData?.totalROI?.toFixed(2) || '-' }}
</div>
</div>
<div class="h-8 w-px bg-slate-200"></div>
<div class="text-center">
<div class="text-[10px] font-bold uppercase text-slate-400">
总税后盈亏
</div>
<div class="text-lg font-black text-emerald-600">
{{
overviewData?.totalProfitAfterTax
? formatAmount(overviewData.totalProfitAfterTax)
: '-'
}}
</div>
</div>
</div>
<!-- 时间选择器组件 -->
<div
class="flex flex-wrap items-center gap-2 rounded-2xl border border-white/60 bg-white/40 p-1.5 shadow-[0_8px_32px_0_rgba(31,38,135,0.05)] backdrop-blur-[16px]"
>
<!-- 快速选择按钮 -->
<div class="flex rounded-xl bg-white/30 p-1">
<Button
:type="activeTimeRange === 'today' ? 'primary' : 'text'"
size="small"
class="!h-auto border-none !px-4 !py-1.5 !text-sm !font-bold"
:class="
activeTimeRange === 'today'
? '!bg-indigo-600 !text-white !shadow-[0_4px_12px_rgba(99,102,241,0.3)]'
: ''
"
@click="switchTimeRange('today')"
>
今日
</Button>
<Button
:type="activeTimeRange === 'yesterday' ? 'primary' : 'text'"
size="small"
class="!h-auto border-none !px-4 !py-1.5 !text-sm !font-bold"
:class="
activeTimeRange === 'yesterday'
? '!bg-indigo-600 !text-white !shadow-[0_4px_12px_rgba(99,102,241,0.3)]'
: ''
"
@click="switchTimeRange('yesterday')"
>
昨日
</Button>
<Button
:type="activeTimeRange === '7days' ? 'primary' : 'text'"
size="small"
class="!h-auto border-none !px-4 !py-1.5 !text-sm !font-bold"
:class="
activeTimeRange === '7days'
? '!bg-indigo-600 !text-white !shadow-[0_4px_12px_rgba(99,102,241,0.3)]'
: ''
"
@click="switchTimeRange('7days')"
>
近7日
</Button>
<Button
:type="activeTimeRange === '30days' ? 'primary' : 'text'"
size="small"
class="!h-auto border-none !px-4 !py-1.5 !text-sm !font-bold"
:class="
activeTimeRange === '30days'
? '!bg-indigo-600 !text-white !shadow-[0_4px_12px_rgba(99,102,241,0.3)]'
: ''
"
@click="switchTimeRange('30days')"
>
近30日
</Button>
</div>
<!-- 分隔线 -->
<div class="mx-1 h-6 w-px bg-slate-300"></div>
<!-- 自定义时间 -->
<div
class="flex items-center gap-2 rounded-xl bg-white/30 px-3 py-1.5"
>
<span class="text-[10px] font-bold uppercase text-slate-400">
自定义
</span>
<DatePicker.RangePicker
v-model:value="customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
class="!border-none !bg-transparent"
:class="
activeTimeRange === 'custom'
? '[&_.ant-picker-input>input]:!font-bold [&_.ant-picker-input>input]:!text-indigo-600'
: ''
"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</div>
</template>
<Spin :spinning="loading">
<div class="mx-auto max-w-[1600px] space-y-8 p-6">
<!-- 汇总卡片 -->
<div class="grid grid-cols-1 gap-6 md:grid-cols-4">
<!-- 全店总销售额 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 bg-gradient-to-br from-indigo-500/10 to-transparent p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="text-sm font-bold text-slate-500">全店总销售额</div>
<div class="mt-1 text-3xl font-black">
{{
overviewData?.totalSalesAmount
? formatAmount(overviewData.totalSalesAmount)
: '-'
}}
</div>
<div
v-if="overviewData?.monthOverMonthGrowth !== undefined"
class="mt-4 w-fit rounded-lg bg-emerald-50 px-2 py-1 text-xs font-bold text-emerald-500"
>
{{ formatPercent(overviewData.monthOverMonthGrowth) }} 较上月同期
</div>
</div>
<!-- 全店总单量 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="text-sm font-bold text-slate-500">全店总单量</div>
<div class="mt-1 text-3xl font-black">
{{
overviewData?.totalOrderCount?.toLocaleString('zh-CN') || '-'
}}
</div>
<div class="mt-4 text-xs font-bold italic text-slate-400">
目标达成率 92%
</div>
</div>
<!-- 总推广费支出 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="text-sm font-bold text-slate-500">总推广费支出</div>
<div class="mt-1 text-3xl font-black">
{{
overviewData?.totalPromotionFee
? formatAmount(overviewData.totalPromotionFee)
: '-'
}}
</div>
<div class="mt-4 text-xs font-bold text-indigo-400">
平均费比:
{{
overviewData?.averageFeeRatio
? `${overviewData.averageFeeRatio.toFixed(1)}%`
: '-'
}}
</div>
</div>
<!-- 全店总净利 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 bg-gradient-to-br from-emerald-500/10 to-transparent p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="text-sm font-bold text-slate-500">
全店总净利 (税后)
</div>
<div class="mt-1 text-3xl font-black text-emerald-600">
{{
overviewData?.totalNetProfitAfterTax
? formatAmount(overviewData.totalNetProfitAfterTax)
: '-'
}}
</div>
<div class="mt-4 text-xs font-bold text-slate-400">
扣除总税额:
{{
overviewData?.totalTaxAmount
? formatAmount(overviewData.totalTaxAmount)
: '-'
}}
</div>
</div>
</div>
<!-- 各店对比分析 -->
<div class="grid grid-cols-1 gap-8 lg:grid-cols-2">
<!-- 店铺销售占比排行 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<h3 class="mb-6 text-xl font-bold">各店铺销售占比排行</h3>
<div class="h-[400px]">
<EchartsUI ref="barChartRef" />
</div>
</div>
<!-- 店铺效率象限 -->
<div
class="rounded-[2rem] border border-white/60 bg-white/50 p-8 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<h3 class="mb-6 text-xl font-bold">店铺效率象限 (ROI vs 净利)</h3>
<div class="h-[400px]">
<EchartsUI ref="scatterChartRef" />
</div>
</div>
</div>
<!-- 店铺多维度对比表 -->
<div
class="overflow-hidden rounded-[2rem] border border-white/60 bg-white/50 shadow-[0_10px_30px_rgba(0,0,0,0.02)] backdrop-blur-[20px]"
>
<div class="flex items-center justify-between p-8">
<h3 class="text-xl font-bold">多店铺数据横向对比</h3>
</div>
<div class="overflow-x-auto px-4 pb-6">
<table class="w-full border-collapse whitespace-nowrap text-left">
<thead
class="border-b border-white/40 text-[11px] uppercase text-slate-400"
>
<tr>
<th class="p-4 font-black">店铺名称</th>
<th class="p-4 font-black">销售额</th>
<th class="p-4 font-black text-indigo-600">ROI</th>
<th class="p-4 font-black text-red-400">退款/刷单费</th>
<th class="p-4 font-black">推广费总和</th>
<th class="p-4 font-black text-emerald-600">税后盈亏</th>
</tr>
</thead>
<tbody class="text-sm">
<tr
v-for="shop in overviewData?.shopComparisons"
:key="shop.shopId"
class="border-t border-white/20 transition hover:bg-white/40"
>
<td class="p-4 font-bold">{{ shop.shopName }}</td>
<td class="p-4">
{{ formatAmountFull(shop.salesAmount) }}
</td>
<td class="p-4 font-black text-indigo-600">
{{ shop.roi?.toFixed(2) || '-' }}
</td>
<td class="p-4 text-red-400">
{{ formatAmountFull(shop.refundAmount || 0) }} /
{{ formatAmountFull(shop.brushFee || 0) }}
</td>
<td class="p-4">
{{
shop.totalPromotionFee
? formatAmountFull(shop.totalPromotionFee)
: '-'
}}
</td>
<td class="p-4 font-black text-emerald-600">
{{
shop.profitAfterTax
? formatAmountFull(shop.profitAfterTax)
: '-'
}}
</td>
</tr>
<tr v-if="!overviewData?.shopComparisons?.length">
<td colspan="6" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</Spin>
</Page>
</template>
<style scoped>
/* 自定义样式 */
</style>
@@ -41,7 +41,7 @@ const currentRecord = ref<null | OrderStatusVO.Info>(null);
const formData = ref<Partial<OrderStatusDTO.Create>>({
statusName: '',
description: '',
isDefaultStat: 1,
autoStatistics: 1,
sortOrder: 0,
});
@@ -66,13 +66,13 @@ function open(edit: boolean, record?: OrderStatusVO.Info) {
? {
statusName: record.statusName,
description: record.description || '',
isDefaultStat: record.isDefaultStat,
autoStatistics: record.autoStatistics,
sortOrder: record.sortOrder || 0,
}
: {
statusName: '',
description: '',
isDefaultStat: 1,
autoStatistics: 1,
sortOrder: 0,
};
}
@@ -95,7 +95,7 @@ async function handleSubmit() {
const updateData: OrderStatusDTO.Update = {
statusName: formData.value.statusName!,
description: formData.value.description,
isDefaultStat: formData.value.isDefaultStat!,
autoStatistics: formData.value.autoStatistics!,
sortOrder: formData.value.sortOrder,
};
await updateOrderStatusApi(currentRecord.value.id, updateData);
@@ -105,7 +105,7 @@ async function handleSubmit() {
const createData: OrderStatusDTO.Create = {
statusName: formData.value.statusName!,
description: formData.value.description,
isDefaultStat: formData.value.isDefaultStat!,
autoStatistics: formData.value.autoStatistics!,
sortOrder: formData.value.sortOrder,
};
await createOrderStatusApi(createData);
@@ -176,9 +176,9 @@ defineExpose({
/>
</Form.Item>
<Form.Item label="默认参与统计" name="isDefaultStat">
<Form.Item label="自动统计" name="autoStatistics">
<Switch
v-model:checked="formData.isDefaultStat"
v-model:checked="formData.autoStatistics"
:checked-value="1"
:un-checked-value="0"
checked-children="参与"
@@ -52,9 +52,9 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 'auto',
},
{
title: '是否默认参与统计',
title: '自动统计',
minWidth: 'auto',
slots: { default: 'isDefaultStat' },
slots: { default: 'autoStatistics' },
},
{
field: 'createTime',
@@ -128,15 +128,15 @@ const formOptions = computed(() => ({
{
component: 'Select',
componentProps: {
placeholder: '请选择是否参与统计',
placeholder: '请选择是否自动统计',
options: [
{ label: '参与默认统计', value: 1 },
{ label: '不参默认与统计', value: 0 },
{ label: '参与自动统计', value: 1 },
{ label: '不参与自动统计', value: 0 },
],
allowClear: true,
},
fieldName: 'isDefaultStat',
label: '是否参与默认统计',
fieldName: 'autoStatistics',
label: '自动统计',
},
],
showDefaultActions: true,
@@ -191,7 +191,7 @@ function handleModalSuccess() {
<Page title="订单状态配置" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理订单状态类型,包括状态名称、描述和是否默认参与统计
管理订单状态类型,包括状态名称、描述和自动统计
</div>
</template>
@@ -207,10 +207,10 @@ function handleModalSuccess() {
</Space>
</template>
<!-- 是否默认参与统计列 -->
<template #isDefaultStat="{ row }: { row: OrderStatusVO.Info }">
<Tag :color="row.isDefaultStat === 1 ? 'green' : 'default'">
{{ row.isDefaultStat === 1 ? '参与统计' : '不参与统计' }}
<!-- 自动统计列 -->
<template #autoStatistics="{ row }: { row: OrderStatusVO.Info }">
<Tag :color="row.autoStatistics === 1 ? 'green' : 'default'">
{{ row.autoStatistics === 1 ? '参与统计' : '不参与统计' }}
</Tag>
</template>
@@ -163,10 +163,8 @@ const canGoToNextStep = computed(() => {
});
}
if (currentStep.value === 2) {
// 订单状态映射步骤:所有唯一的订单状态值都必须映射
return uniqueStatusValues.value.every(
(status) => statusMappings.value[status] !== undefined,
);
// 订单状态映射步骤:允许不映射,所以总是返回 true
return true;
}
return true;
});
@@ -565,13 +563,13 @@ async function handleConfirmSaveStatusTemplate() {
return;
}
// 验证所有订单状态是否都已映射
const unMappedStatuses = uniqueStatusValues.value.filter(
(status) => statusMappings.value[status] === undefined,
// 验证是否有映射数据(至少需要一个映射才能保存模板)
const mappedStatuses = uniqueStatusValues.value.filter(
(status) => statusMappings.value[status] !== undefined,
);
if (unMappedStatuses.length > 0) {
message.warning(`请先映射所有订单状态:${unMappedStatuses.join('、')}`);
if (mappedStatuses.length === 0) {
message.warning('请至少映射一个订单状态');
return;
}
@@ -579,13 +577,13 @@ async function handleConfirmSaveStatusTemplate() {
savingStatusTemplate.value = true;
saveStatusTemplateModalApi.lock();
// 构建映射数据(已验证所有状态都已映射,所以不会有 undefined)
const mappingItems: StatusMappingItem[] = uniqueStatusValues.value.map(
(status) => ({
// 构建映射数据(只包含已映射的状态)
const mappingItems: StatusMappingItem[] = uniqueStatusValues.value
.filter((status) => statusMappings.value[status] !== undefined)
.map((status) => ({
csvStatus: status,
mappedStatusId: statusMappings.value[status]!,
}),
);
}));
const mappingJson = JSON.stringify(mappingItems);
@@ -712,14 +710,7 @@ const handleNext = () => {
break;
}
case 2: {
// 验证所有订单状态是否都已映射
const unMappedStatuses = uniqueStatusValues.value.filter(
(status) => statusMappings.value[status] === undefined,
);
if (unMappedStatuses.length > 0) {
message.warning(`请先映射所有订单状态:${unMappedStatuses.join('、')}`);
return;
}
// 订单状态映射是可选的,可以直接进入下一步
currentStep.value = 3;
break;
@@ -781,9 +772,10 @@ const handleCreateTask = async () => {
required: m.fieldDef.required,
}));
// 构建订单状态映射 JSON(已验证所有状态都已映射,所以不会有 undefined)
const statusMappingItems: StatusMappingItem[] =
uniqueStatusValues.value.map((status) => ({
// 构建订单状态映射 JSON(只包含已映射的状态)
const statusMappingItems: StatusMappingItem[] = uniqueStatusValues.value
.filter((status) => statusMappings.value[status] !== undefined)
.map((status) => ({
csvStatus: status,
mappedStatusId: statusMappings.value[status]!,
}));
@@ -886,7 +878,7 @@ const shopOptions = computed(() => {
<template>
<Modal title="创建导入任务" :loading="loading">
<div class="space-y-6">
<div class="space-y-3">
<!-- 步骤条 -->
<Steps :current="currentStep">
<Steps.Step title="选择店铺" />
@@ -1014,7 +1006,7 @@ const shopOptions = computed(() => {
<div v-if="currentStep === 2" class="py-4">
<div class="mb-4 flex items-center justify-between">
<div class="text-sm text-gray-600">
请为每个订单状态值映射到对应的系统订单状态,所有状态必须映射
请为每个订单状态值映射到对应的系统订单状态(可选,可不映射)
</div>
<div class="flex items-center space-x-2">
<Select
@@ -1065,10 +1057,6 @@ const shopOptions = computed(() => {
v-for="statusValue in uniqueStatusValues"
:key="statusValue"
class="flex items-center space-x-4 rounded border p-3"
:class="{
'border-red-300 bg-red-50':
statusMappings[statusValue] === undefined,
}"
>
<div class="flex-1">
<div class="font-medium">{{ statusValue }}</div>
@@ -1076,9 +1064,10 @@ const shopOptions = computed(() => {
</div>
<Select
v-model:value="statusMappings[statusValue]"
placeholder="请选择订单状态"
placeholder="请选择订单状态(可选)"
class="w-[200px]"
show-search
allow-clear
:loading="orderStatusLoading"
:options="
orderStatusList.map((status) => ({
@@ -1143,7 +1132,7 @@ const shopOptions = computed(() => {
</div>
<!-- 操作按钮 -->
<div class="flex justify-between border-t pt-4">
<div class="flex justify-between">
<Button @click="handleCancel">取消</Button>
<div class="space-x-2">
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
@@ -1198,7 +1187,3 @@ const shopOptions = computed(() => {
</SaveStatusTemplateModal>
</Modal>
</template>
<style scoped>
/* 自定义样式 */
</style>
@@ -1,9 +1,7 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { Button, message } from 'ant-design-vue';
@@ -20,6 +18,8 @@ const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
// 动态生成Grid列配置
const gridColumns = computed(() => {
@@ -53,7 +53,7 @@ const gridColumns = computed(() => {
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [],
height: 'auto',
height: tableHeight.value,
border: true,
stripe: true,
highlightHoverRow: true,
@@ -122,11 +122,23 @@ const [Grid, gridApi] = useVbenVxeGrid({
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
});
// 触发重新加载数据
gridApi.reload();
};
// 监听表格高度变化,更新表格配置
watch(
tableHeight,
(newHeight) => {
gridApi.setGridOptions({
height: newHeight,
});
},
{ immediate: false },
);
// 处理文件上传
const handleFileUpload = async (file: File) => {
importLoading.value = true;
@@ -148,6 +160,10 @@ const handleFileUpload = async (file: File) => {
// 更新表格
updateTable();
// 重新计算表格高度
nextTick(() => {
calculateTableHeight();
});
message.success(`成功解析 ${result.data.length} 条数据`);
} catch (error: any) {
@@ -183,45 +199,213 @@ const handleClearData = () => {
updateTable();
message.success('已清空数据');
};
// 计算表格高度
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
// 减去 padding (1.5rem * 2 = 3rem = 48px) 和其他元素的高度
const headerHeight = 100; // 估算表头高度
const padding = 48; // 1.5rem * 2
const availableHeight = rect.height - padding - headerHeight;
tableHeight.value = Math.max(400, availableHeight);
}
});
};
// 监听窗口大小变化
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
if (resizeObserver) {
resizeObserver.disconnect();
}
});
</script>
<template>
<Page auto-content-height>
<!-- 顶部栏 -->
<template #extra>
<div class="flex items-center space-x-2">
<Button
:disabled="csvData.length === 0"
@click="handleClearData"
>
清空数据
</Button>
<Button
type="primary"
:disabled="csvHeaders.length === 0"
@click="handleCreateImportTask"
>
创建导入任务
</Button>
<div
class="h-full overflow-hidden bg-gradient-to-br from-indigo-100 via-pink-100 to-slate-100 p-8"
>
<div class="mx-auto flex h-full w-[60%] flex-col overflow-hidden">
<!-- 头部标题 -->
<div class="mb-12 shrink-0 text-center">
<h1 class="mb-2 text-4xl font-black tracking-tight text-slate-800">
订单导入中心
</h1>
<p class="text-base font-medium text-slate-500">
请上传 CSV 格式的订单原始数据进行分析
</p>
</div>
</template>
<!-- 主体内容区域 -->
<div
v-if="csvData.length === 0"
class="flex h-full items-center justify-center"
>
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
<!-- 主体内容区域 -->
<div
v-if="csvData.length === 0"
class="flex min-h-0 flex-1 flex-col overflow-hidden"
>
<div
class="mb-8 grid shrink-0 grid-cols-1 gap-6 lg:grid-cols-[2fr_1fr]"
>
<!-- 左侧:导入区域 -->
<div
class="relative flex min-h-[400px] flex-col items-center justify-center overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-8 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] backdrop-blur-2xl"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
></div>
<div
class=":deep(.ant-spin-nested-loading) :deep(.ant-spin-container) w-full"
>
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
<!-- 右侧:指引与历史 -->
<div class="flex flex-col gap-6">
<!-- 操作指南卡片 -->
<div
class="relative flex flex-col gap-4 overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] backdrop-blur-2xl"
>
<h3 class="m-0 text-base font-bold text-slate-800">操作指南</h3>
<div class="flex flex-col gap-4">
<div class="flex items-start gap-3">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-indigo-600 text-xs font-bold text-white"
>
1
</div>
<p
class="m-0 text-xs font-medium leading-relaxed text-slate-500"
>
从电商后台导出【订单详情】CSV文件
</p>
</div>
<div class="flex items-start gap-3">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-indigo-100 bg-white text-xs font-bold text-indigo-600"
>
2
</div>
<p
class="m-0 text-xs font-medium leading-relaxed text-slate-500"
>
检查文件是否包含【订单号】与【金额】列
</p>
</div>
<div class="flex items-start gap-3">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-indigo-100 bg-white text-xs font-bold text-indigo-600"
>
3
</div>
<p
class="m-0 text-xs font-medium leading-relaxed text-slate-500"
>
上传成功后,系统将自动解析并显示数据
</p>
</div>
</div>
</div>
</div>
</div>
<!-- 底部全局按钮 -->
<div class="flex justify-center gap-4 pt-4">
<Button :disabled="csvData.length === 0" @click="handleClearData">
清空当前选择
</Button>
<Button
type="primary"
:disabled="csvHeaders.length === 0"
@click="handleCreateImportTask"
>
创建导入任务
</Button>
</div>
</div>
<!-- 数据表格区域 -->
<div v-else class="flex min-h-0 w-full flex-1 flex-col overflow-hidden">
<div
class="mb-6 flex shrink-0 flex-wrap items-start justify-between gap-4"
>
<div class="flex-1">
<h2 class="mb-1 text-2xl font-bold text-slate-800">数据预览</h2>
<p class="m-0 text-sm text-slate-500">
共 {{ csvData.length }} 条数据,请检查数据后创建导入任务
</p>
</div>
<div class="flex gap-2">
<Button @click="handleClearData">清空数据</Button>
<Button type="primary" @click="handleCreateImportTask">
创建导入任务
</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] backdrop-blur-2xl"
>
<Grid />
</div>
</div>
<CreateImportTaskModal ref="createImportTaskModalRef" />
</div>
<Grid v-else />
<CreateImportTaskModal ref="createImportTaskModalRef" />
</Page>
</div>
</template>
<style scoped>
/* 自定义样式 */
/* 上传区域深度选择器样式 */
:deep(.ant-spin-nested-loading),
:deep(.ant-spin-container) {
width: 100%;
}
:deep(.border-dashed) {
background: transparent;
border: 2px dashed rgba(99, 102, 241, 0.3);
border-radius: 2rem;
padding: 3rem;
transition: all 0.3s ease;
width: 100%;
}
:deep(.border-dashed:hover) {
border-color: #6366f1;
background: rgba(99, 102, 241, 0.05);
transform: scale(1.01);
}
:deep(.border-blue-500) {
border-color: #6366f1 !important;
background: rgba(99, 102, 241, 0.05) !important;
}
/* VxeGrid 表格样式 */
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
</style>
@@ -68,7 +68,10 @@ const formData = ref<Partial<OrderDTO.Create>>({
linkSpecName: '',
quantity: 1,
unitPrice: 0,
costPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
});
// 下拉选项数据
@@ -103,7 +106,7 @@ const rules = {
],
quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
unitPrice: [{ required: true, message: '请输入销售单价', trigger: 'blur' }],
costPrice: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
productCost: [{ required: true, message: '请输入商品成本', trigger: 'blur' }],
};
// 表单引用
@@ -212,7 +215,9 @@ function handleProductChange(productId: number | undefined) {
formData.value.linkProductName = '';
formData.value.productSpecId = undefined;
formData.value.linkSpecName = '';
formData.value.costPrice = 0;
formData.value.productCost = 0;
formData.value.shippingCost = 0;
formData.value.otherCost = 0;
productSpecOptions.value = [];
}
}
@@ -225,11 +230,15 @@ function handleProductSpecChange(specId: number | undefined) {
);
if (selectedSpec) {
formData.value.linkSpecName = selectedSpec.spec.name;
formData.value.costPrice = selectedSpec.spec.costPrice;
formData.value.productCost = selectedSpec.spec.productCost;
formData.value.shippingCost = selectedSpec.spec.shippingCost || 0;
formData.value.otherCost = selectedSpec.spec.otherCost || 0;
}
} else {
formData.value.linkSpecName = '';
formData.value.costPrice = 0;
formData.value.productCost = 0;
formData.value.shippingCost = 0;
formData.value.otherCost = 0;
}
}
@@ -274,7 +283,10 @@ async function open(edit: boolean, record?: OrderVO.Info) {
linkSpecName: record.linkSpecName,
quantity: record.quantity,
unitPrice: record.unitPrice,
costPrice: record.costPrice,
productCost: record.productCost,
shippingCost: record.shippingCost || 0,
otherCost: record.otherCost || 0,
remark: record.remark || '',
}
: {
shopId: undefined,
@@ -288,7 +300,10 @@ async function open(edit: boolean, record?: OrderVO.Info) {
linkSpecName: '',
quantity: 1,
unitPrice: 0,
costPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
};
// 如果是编辑模式且有商品ID,加载商品和规格选项
@@ -319,7 +334,9 @@ async function open(edit: boolean, record?: OrderVO.Info) {
spec: {
id: record.productSpecId,
name: record.linkSpecName || '',
costPrice: record.costPrice,
productCost: record.productCost,
shippingCost: record.shippingCost,
otherCost: record.otherCost,
} as ProductSpecVO.Info,
});
}
@@ -354,7 +371,10 @@ async function handleSubmit() {
linkSpecName: formData.value.linkSpecName,
quantity: formData.value.quantity,
unitPrice: formData.value.unitPrice,
costPrice: formData.value.costPrice,
productCost: formData.value.productCost,
shippingCost: formData.value.shippingCost,
otherCost: formData.value.otherCost,
remark: formData.value.remark,
};
await updateOrderApi(currentRecord.value.id, updateData);
message.success('更新订单成功');
@@ -372,7 +392,10 @@ async function handleSubmit() {
linkSpecName: formData.value.linkSpecName,
quantity: formData.value.quantity!,
unitPrice: formData.value.unitPrice!,
costPrice: formData.value.costPrice!,
productCost: formData.value.productCost!,
shippingCost: formData.value.shippingCost,
otherCost: formData.value.otherCost,
remark: formData.value.remark,
};
await createOrderApi(createData);
message.success('创建订单成功');
@@ -532,10 +555,10 @@ defineExpose({
/>
</Form.Item>
<Form.Item label="成本价" name="costPrice">
<Form.Item label="商品成本" name="productCost">
<InputNumber
v-model:value="formData.costPrice"
placeholder="请输入成本价"
v-model:value="formData.productCost"
placeholder="请输入商品成本"
style="width: 100%"
:min="0"
:precision="2"
@@ -543,6 +566,36 @@ defineExpose({
</Form.Item>
</div>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="运费成本" name="shippingCost">
<InputNumber
v-model:value="formData.shippingCost"
placeholder="请输入运费成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="其他成本" name="otherCost">
<InputNumber
v-model:value="formData.otherCost"
placeholder="请输入其他成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</div>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注"
:rows="3"
/>
</Form.Item>
<Form.Item label="实收金额" name="receivedAmount">
<InputNumber
v-model:value="formData.receivedAmount"
@@ -51,7 +51,10 @@ const currentSpecId = ref<null | number>(null);
const specFormData = ref({
name: '',
specCode: '',
costPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
});
// 声明模态框 API(稍后赋值)
@@ -75,10 +78,11 @@ async function handleSpecSubmit() {
specFormModalApi?.setState({ confirmLoading: true });
if (isEditSpec.value && currentSpecId.value) {
await updateProductSpecApi(
currentSpecId.value,
specFormData.value as ProductSpecDTO.Update,
);
const updateData: ProductSpecDTO.Update = {
id: currentSpecId.value,
...specFormData.value,
};
await updateProductSpecApi(currentSpecId.value, updateData);
message.success('更新成功');
} else {
if (!currentProduct.value) {
@@ -149,12 +153,12 @@ const columns = [
width: 150,
},
{
title: '成本价',
dataIndex: 'costPrice',
key: 'costPrice',
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 120,
customRender: ({ record }: { record: ProductSpecVO.Info }) => {
return `¥${record.costPrice.toFixed(2)}`;
return `¥${record.productCost.toFixed(2)}`;
},
},
{
@@ -236,7 +240,10 @@ function handleAddSpec() {
specFormData.value = {
name: '',
specCode: '',
costPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
};
specFormModalApi.setState({ title: '添加规格' });
specFormModalApi.open();
@@ -249,7 +256,10 @@ function handleEditSpec(record: ProductSpecVO.Info) {
specFormData.value = {
name: record.name,
specCode: record.specCode || '',
costPrice: record.costPrice,
productCost: record.productCost,
shippingCost: record.shippingCost || 0,
otherCost: record.otherCost || 0,
remark: record.remark || '',
};
specFormModalApi.setState({ title: '编辑规格' });
specFormModalApi.open();
@@ -358,18 +368,46 @@ defineExpose({
</Form.Item>
<Form.Item
label="成本价"
name="costPrice"
:rules="[{ required: true, message: '请输入成本价' }]"
label="商品成本"
name="productCost"
:rules="[{ required: true, message: '请输入商品成本' }]"
>
<InputNumber
v-model:value="specFormData.costPrice"
placeholder="请输入成本价"
v-model:value="specFormData.productCost"
placeholder="请输入商品成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="运费成本" name="shippingCost">
<InputNumber
v-model:value="specFormData.shippingCost"
placeholder="请输入运费成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="其他成本" name="otherCost">
<InputNumber
v-model:value="specFormData.otherCost"
placeholder="请输入其他成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="specFormData.remark"
placeholder="请输入备注"
:rows="3"
/>
</Form.Item>
</Form>
</SpecFormModal>
</template>
@@ -0,0 +1,157 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>订单导入中心 - 毛玻璃设计</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Plus Jakarta Sans', sans-serif;
/* 延续统计页的柔和渐变背景 */
background: linear-gradient(135deg, #e0e7ff 0%, #fae8ff 50%, #f1f5f9 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.glass {
background: rgba(255, 255, 255, 0.45);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.5);
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1);
}
.drop-zone {
border: 2px dashed rgba(99, 102, 241, 0.3);
transition: all 0.3s ease;
}
.drop-zone:hover {
border-color: #6366f1;
background: rgba(99, 102, 241, 0.05);
transform: scale(1.01);
}
.step-circle {
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
font-size: 12px;
font-weight: bold;
}
</style>
</head>
<body class="p-4">
<div class="max-w-4xl w-full space-y-6">
<!-- 头部标题 -->
<div class="text-center space-y-2 mb-8">
<h1 class="text-4xl font-black text-slate-800 tracking-tight">订单导入中心</h1>
<p class="text-slate-500 font-medium">请上传 CSV 格式的订单原始数据进行分析</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- 左侧:导入区域 -->
<div class="lg:col-span-2 glass p-8 rounded-[2.5rem] flex flex-col justify-center items-center relative overflow-hidden">
<!-- 装饰性光晕 -->
<div class="absolute -top-10 -right-10 w-32 h-32 bg-indigo-400 opacity-10 blur-3xl"></div>
<div class="w-full drop-zone rounded-[2rem] p-12 flex flex-col items-center justify-center space-y-4 cursor-pointer">
<div class="w-16 h-16 bg-indigo-100 text-indigo-600 rounded-2xl flex items-center justify-center shadow-inner">
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
</div>
<div class="text-center">
<p class="text-lg font-bold text-slate-700">拖拽 CSV 文件到此处上传</p>
<p class="text-sm text-slate-400 mt-1">支持标准电商平台导出格式,最大 20MB</p>
</div>
<button class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-indigo-200 hover:bg-indigo-700 transition">
选择本地文件
</button>
</div>
<!-- 导入选项 -->
<div class="w-full mt-8 flex justify-between items-center text-sm">
<div class="flex items-center gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" class="rounded text-indigo-600 focus:ring-indigo-500">
<span class="text-slate-500 font-medium">自动去重</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked class="rounded text-indigo-600 focus:ring-indigo-500">
<span class="text-slate-500 font-medium">覆盖旧数据</span>
</label>
</div>
<a href="#" class="text-indigo-600 font-bold hover:underline">下载导入模板</a>
</div>
</div>
<!-- 右侧:指引与历史 -->
<div class="space-y-6">
<!-- 步骤卡片 -->
<div class="glass p-6 rounded-[2rem] space-y-4">
<h3 class="font-bold text-slate-800 flex items-center gap-2">
操作指南
</h3>
<div class="space-y-4">
<div class="flex gap-3">
<div class="step-circle bg-indigo-600 text-white">1</div>
<p class="text-xs text-slate-500 leading-relaxed font-medium">从电商后台导出【订单详情】CSV文件</p>
</div>
<div class="flex gap-3">
<div class="step-circle bg-white text-indigo-600 border border-indigo-100">2</div>
<p class="text-xs text-slate-500 leading-relaxed font-medium">检查文件是否包含【订单号】与【金额】列</p>
</div>
<div class="flex gap-3">
<div class="step-circle bg-white text-indigo-600 border border-indigo-100">3</div>
<p class="text-xs text-slate-500 leading-relaxed font-medium">上传成功后,系统将自动跳转至统计页面</p>
</div>
</div>
</div>
<!-- 最近上传历史 -->
<div class="glass p-6 rounded-[2rem] space-y-4">
<div class="flex justify-between items-center">
<h3 class="font-bold text-slate-800">最近导入</h3>
<span class="text-[10px] font-bold text-indigo-500">查看全部</span>
</div>
<div class="space-y-3">
<div class="flex items-center justify-between p-3 rounded-2xl bg-white/30 text-xs">
<div>
<p class="font-bold text-slate-700 italic">20231027_orders.csv</p>
<p class="text-[10px] text-slate-400">10:20 · 1,280 行</p>
</div>
<span class="text-emerald-500 font-black">完成</span>
</div>
<div class="flex items-center justify-between p-3 rounded-2xl bg-white/30 text-xs">
<div>
<p class="font-bold text-slate-700 italic">temp_data_02.csv</p>
<p class="text-[10px] text-slate-400">昨天 · 450 行</p>
</div>
<span class="text-slate-400 font-black">失效</span>
</div>
</div>
</div>
</div>
</div>
<!-- 底部全局按钮 -->
<div class="flex justify-center gap-4 pt-4">
<button class="glass px-10 py-3 rounded-2xl font-bold text-slate-500 hover:bg-white/60 transition">
清空当前选择
</button>
<button class="bg-slate-900 text-white px-10 py-3 rounded-2xl font-bold shadow-2xl hover:bg-slate-800 transition">
开始解析并创建任务
</button>
</div>
</div>
</body>
</html>
@@ -0,0 +1,178 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>创建导入任务 - 毛玻璃组件</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: linear-gradient(135deg, #e0e7ff 0%, #fae8ff 50%, #f1f5f9 100%);
min-height: 100vh;
display: flex; align-items: center; justify-content: center;
}
/* 延续之前的 Glass 核心类 */
.glass {
background: rgba(255, 255, 255, 0.45);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.5);
}
/* 内部映射卡片 */
.glass-inner-card {
background: rgba(255, 255, 255, 0.3);
border: 1px solid rgba(255, 255, 255, 0.4);
transition: all 0.3s ease;
}
.glass-inner-card:hover { background: rgba(255, 255, 255, 0.5); transform: translateY(-2px); }
/* 步进器线条动画 */
.step-line { height: 2px; background: rgba(99, 102, 241, 0.1); flex-grow: 1; margin: 0 1rem; position: relative; overflow: hidden; }
.step-line-active::after { content: ""; position: absolute; left: 0; top: 0; height: 100%; width: 100%; background: #6366f1; animation: slide 1s ease-in-out; }
@keyframes slide { from { width: 0; } to { width: 100%; } }
.custom-scroll::-webkit-scrollbar { width: 4px; }
.custom-scroll::-webkit-scrollbar-thumb { background: rgba(99, 102, 241, 0.2); border-radius: 10px; }
</style>
</head>
<body class="p-4">
<!-- 弹窗主体容器 -->
<div class="max-w-4xl w-full glass rounded-[3rem] shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
<!-- Header -->
<div class="px-10 py-8 border-b border-white/40 flex justify-between items-center">
<div>
<h2 class="text-2xl font-black text-slate-800 tracking-tight">创建导入任务</h2>
<p class="text-xs text-slate-500 font-bold mt-1 uppercase tracking-widest">Import Task Wizard</p>
</div>
<button class="w-10 h-10 glass rounded-full flex items-center justify-center text-slate-400 hover:text-slate-600 transition">✕</button>
</div>
<!-- 步进器 Stepper -->
<div class="px-12 py-10">
<div class="flex items-center">
<!-- Step 1: Done -->
<div class="flex items-center">
<div class="w-10 h-10 bg-indigo-100 text-indigo-600 rounded-2xl flex items-center justify-center font-bold shadow-inner">✓</div>
<span class="ml-3 text-xs font-black text-indigo-600">选择店铺</span>
</div>
<div class="step-line step-line-active"></div>
<!-- Step 2: Active -->
<div class="flex items-center">
<div class="w-10 h-10 bg-indigo-600 text-white rounded-2xl flex items-center justify-center font-bold shadow-lg shadow-indigo-200">2</div>
<span class="ml-3 text-xs font-black text-slate-700">字段映射</span>
</div>
<div class="step-line"></div>
<!-- Step 3: Pending -->
<div class="flex items-center">
<div class="w-10 h-10 glass rounded-2xl flex items-center justify-center font-bold text-slate-400">3</div>
<span class="ml-3 text-xs font-bold text-slate-400">状态映射</span>
</div>
<div class="step-line"></div>
<!-- Step 4: Pending -->
<div class="flex items-center">
<div class="w-10 h-10 glass rounded-2xl flex items-center justify-center font-bold text-slate-400">4</div>
<span class="ml-3 text-xs font-bold text-slate-400">确认信息</span>
</div>
</div>
</div>
<!-- 内容区域 (这里以 Step 2 字段映射为例展示) -->
<div class="px-12 pb-10 flex-1 overflow-y-auto custom-scroll space-y-6">
<!-- 顶部操作栏 -->
<div class="flex justify-between items-center bg-white/20 p-4 rounded-2xl border border-white/40">
<span class="text-sm font-medium text-slate-600">系统已根据 CSV 表头为您自动匹配了 5 个字段</span>
<div class="flex gap-2">
<select class="bg-white/50 border-none rounded-xl text-xs font-bold px-4 py-2 outline-none">
<option>默认映射模板 (拼多多)</option>
</select>
<button class="text-xs font-bold text-indigo-600 hover:underline">保存为新模板</button>
</div>
</div>
<!-- 映射列表布局 -->
<div class="grid grid-cols-1 gap-4">
<!-- 映射单元 1 -->
<div class="glass-inner-card p-5 rounded-[1.5rem] flex items-center gap-8">
<div class="w-1/3">
<label class="text-[10px] font-black text-indigo-500 uppercase">系统标准字段</label>
<h4 class="text-base font-bold text-slate-800">规格编码 <span class="text-rose-500">*</span></h4>
<p class="text-[10px] text-slate-400">字段定义: spec_code</p>
</div>
<div class="flex-1 flex items-center gap-4">
<div class="text-slate-300">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
</div>
<div class="flex-1">
<select class="w-full bg-white/60 border border-white/80 rounded-2xl px-5 py-3 text-sm font-bold outline-none focus:ring-2 focus:ring-indigo-300 transition-all">
<option>商家编码-规格维度 (CSV列)</option>
<option>商品ID</option>
</select>
</div>
</div>
</div>
<!-- 映射单元 2 (错误示例) -->
<div class="glass-inner-card p-5 rounded-[1.5rem] flex items-center gap-8 border-rose-200 bg-rose-50/20">
<div class="w-1/3">
<label class="text-[10px] font-black text-rose-500 uppercase">系统标准字段</label>
<h4 class="text-base font-bold text-slate-800">商家实收金额 <span class="text-rose-500">*</span></h4>
<p class="text-[10px] text-slate-400">字段定义: received_amount</p>
</div>
<div class="flex-1 flex items-center gap-4">
<div class="text-rose-300">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
</div>
<div class="flex-1">
<select class="w-full bg-rose-50/50 border border-rose-200 rounded-2xl px-5 py-3 text-sm font-bold outline-none text-rose-500">
<option>-- 请选择 CSV 对应列 --</option>
</select>
</div>
</div>
</div>
<!-- 映射单元 3 -->
<div class="glass-inner-card p-5 rounded-[1.5rem] flex items-center gap-8">
<div class="w-1/3">
<label class="text-[10px] font-black text-indigo-500 uppercase">系统标准字段</label>
<h4 class="text-base font-bold text-slate-800">下单时间 <span class="text-rose-500">*</span></h4>
</div>
<div class="flex-1 flex items-center gap-4">
<div class="text-slate-300">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
</div>
<div class="flex-1">
<select class="w-full bg-white/60 border border-white/80 rounded-2xl px-5 py-3 text-sm font-bold outline-none">
<option>支付时间 (Pay Time)</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div class="px-12 py-8 border-t border-white/40 bg-white/20 flex justify-between items-center">
<button class="px-8 py-3 rounded-2xl font-bold text-slate-500 hover:bg-white/50 transition">
取消导入
</button>
<div class="flex gap-4">
<button class="glass px-8 py-3 rounded-2xl font-bold text-indigo-600 hover:bg-white/60 transition border border-indigo-100">
上一步
</button>
<button class="bg-indigo-600 text-white px-10 py-3 rounded-2xl font-bold shadow-xl shadow-indigo-200 hover:bg-indigo-700 transition">
下一步:状态映射
</button>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全店汇总毛玻璃看板</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: linear-gradient(135deg, #fef2f2 0%, #eef2ff 50%, #f0fdf4 100%);
min-height: 100vh;
}
.glass {
background: rgba(255, 255, 255, 0.5);
backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 2rem;
box-shadow: 0 10px 30px rgba(0,0,0,0.02);
}
</style>
</head>
<body class="p-6 md:p-10">
<div class="max-w-[1600px] mx-auto space-y-8">
<!-- 公司级头部 -->
<header class="flex justify-between items-center">
<div>
<h1 class="text-4xl font-black text-slate-800 tracking-tight">全店铺经营大盘</h1>
<p class="text-indigo-600 font-bold">Company Dashboard · 共 8 家在营店铺</p>
</div>
<div class="glass px-6 py-3 flex gap-8 items-center">
<div class="text-center"><div class="text-[10px] uppercase font-bold text-slate-400">汇总 ROI</div><div class="text-lg font-black">4.05</div></div>
<div class="w-px h-8 bg-slate-200"></div>
<div class="text-center"><div class="text-[10px] uppercase font-bold text-slate-400">总税后盈亏</div><div class="text-lg font-black text-emerald-600">¥842,000</div></div>
</div>
</header>
<!-- 汇总卡片 -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-6">
<div class="glass p-8 bg-gradient-to-br from-indigo-500/10 to-transparent">
<div class="text-slate-500 text-sm font-bold">全店总销售额</div>
<div class="text-3xl font-black mt-1">¥4,829,000</div>
<div class="mt-4 text-xs font-bold text-emerald-500 bg-emerald-50 w-fit px-2 py-1 rounded-lg">↑ 18% 较上月同期</div>
</div>
<div class="glass p-8">
<div class="text-slate-500 text-sm font-bold">全店总单量</div>
<div class="text-3xl font-black mt-1">12,408</div>
<div class="mt-4 text-xs font-bold text-slate-400 italic">目标达成率 92%</div>
</div>
<div class="glass p-8">
<div class="text-slate-500 text-sm font-bold">总推广费支出</div>
<div class="text-3xl font-black mt-1">¥1,192,000</div>
<div class="mt-4 text-xs font-bold text-indigo-400">平均费比: 24.6%</div>
</div>
<div class="glass p-8 bg-gradient-to-br from-emerald-500/10 to-transparent">
<div class="text-slate-500 text-sm font-bold">全店总净利 (税后)</div>
<div class="text-3xl font-black mt-1 text-emerald-600">¥842,500</div>
<div class="mt-4 text-xs font-bold text-slate-400">扣除总税额: ¥193,160</div>
</div>
</div>
<!-- 各店对比分析 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
<div class="glass p-8">
<h3 class="font-bold text-xl mb-6">各店铺销售占比排行</h3>
<div id="shopBarChart" style="height: 400px;"></div>
</div>
<div class="glass p-8">
<h3 class="font-bold text-xl mb-6">店铺效率象限 (ROI vs 净利)</h3>
<div id="shopScatterChart" style="height: 400px;"></div>
</div>
</div>
<!-- 店铺多维度对比表 (包含16维度) -->
<div class="glass overflow-hidden pb-6">
<div class="p-8 flex justify-between items-center">
<h3 class="font-bold text-xl">多店铺数据横向对比 (全16维度)</h3>
</div>
<div class="overflow-x-auto px-4">
<table class="w-full text-left border-collapse whitespace-nowrap">
<thead class="text-[11px] uppercase text-slate-400 border-b border-white/40">
<tr>
<th class="p-4 font-black">店铺名称</th>
<th class="p-4 font-black">销售额</th>
<th class="p-4 font-black text-indigo-600">ROI</th>
<th class="p-4 font-black">目标达成</th>
<th class="p-4 font-black text-red-400">退款/刷单费</th>
<th class="p-4 font-black">推广费总和</th>
<th class="p-4 font-black text-emerald-600">税后盈亏</th>
</tr>
</thead>
<tbody class="text-sm">
<tr class="hover:bg-white/40 transition">
<td class="p-4 font-bold">旗舰店 A</td>
<td class="p-4">¥1,284,000</td>
<td class="p-4 font-black text-indigo-600">4.21</td>
<td class="p-4"><div class="w-24 bg-slate-200 h-1 rounded-full"><div class="bg-indigo-500 h-full w-[85%]"></div></div></td>
<td class="p-4 text-red-400">¥12,400 / ¥1,500</td>
<td class="p-4">¥305,000</td>
<td class="p-4 font-black text-emerald-600">¥124,500</td>
</tr>
<tr class="hover:bg-white/40 transition border-t border-white/20">
<td class="p-4 font-bold">精品海外店 B</td>
<td class="p-4">¥942,000</td>
<td class="p-4 font-black text-indigo-600">3.85</td>
<td class="p-4"><div class="w-24 bg-slate-200 h-1 rounded-full"><div class="bg-indigo-500 h-full w-[105%]"></div></div></td>
<td class="p-4 text-red-400">¥8,200 / ¥2,100</td>
<td class="p-4">¥240,000</td>
<td class="p-4 font-black text-emerald-600">¥98,000</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script>
// 店铺排行
const barChart = echarts.init(document.getElementById('shopBarChart'));
barChart.setOption({
tooltip: { trigger: 'axis' },
xAxis: { type: 'value', show: false },
yAxis: { type: 'category', data: ['店 D', '店 C', '店 B', '旗舰店 A'], axisLine: {show: false} },
series: [{
type: 'bar',
data: [420, 780, 942, 1284],
itemStyle: {
color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [{offset: 0, color: '#6366f1'}, {offset: 1, color: '#a5b4fc'}]),
borderRadius: [0, 10, 10, 0]
},
barWidth: 25
}]
});
// 效率象限图
const scatterChart = echarts.init(document.getElementById('shopScatterChart'));
scatterChart.setOption({
grid: { top: '10%', bottom: '10%', left: '10%' },
xAxis: { name: '销售额', splitLine: { lineStyle: { type: 'dashed' } } },
yAxis: { name: 'ROI', splitLine: { lineStyle: { type: 'dashed' } } },
series: [{
type: 'scatter',
symbolSize: 40,
data: [[1284, 4.21], [942, 3.85], [780, 5.2], [420, 2.1]],
itemStyle: { color: '#6366f1', opacity: 0.6 }
}]
});
</script>
</body>
</html>
@@ -0,0 +1,182 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>单店毛玻璃看板 - 时间筛选</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Plus Jakarta Sans', sans-serif;
background: linear-gradient(135deg, #eef2ff 0%, #fae8ff 50%, #f1f5f9 100%);
min-height: 100vh;
color: #1e293b;
}
.glass {
background: rgba(255, 255, 255, 0.4);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.5);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.05);
}
/* 时间选择器激活状态 */
.time-btn.active {
background: #6366f1;
color: white;
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}
.time-btn { transition: all 0.3s ease; }
.no-scrollbar::-webkit-scrollbar { display: none; }
</style>
</head>
<body class="p-6">
<div class="max-w-7xl mx-auto space-y-6">
<!-- 头部:店铺信息 & 增强型时间选择器 -->
<header class="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 pb-4">
<div>
<h1 class="text-3xl font-black text-slate-800">星辰优选旗舰店</h1>
<p class="text-slate-500 font-medium">数据维度:全方位损益实时统计</p>
</div>
<!-- 时间选择器组件 -->
<div class="glass p-1.5 rounded-2xl flex flex-wrap items-center gap-2">
<div class="flex bg-white/30 rounded-xl p-1">
<button onclick="switchTime(this)" class="time-btn active px-4 py-1.5 rounded-lg text-sm font-bold">今日</button>
<button onclick="switchTime(this)" class="time-btn px-4 py-1.5 rounded-lg text-sm font-bold">昨日</button>
<button onclick="switchTime(this)" class="time-btn px-4 py-1.5 rounded-lg text-sm font-bold">近7日</button>
<button onclick="switchTime(this)" class="time-btn px-4 py-1.5 rounded-lg text-sm font-bold">近30日</button>
</div>
<div class="h-6 w-px bg-slate-300 mx-1"></div>
<!-- 自定义时间 -->
<div class="flex items-center gap-2 px-3 py-1.5 bg-white/30 rounded-xl">
<span class="text-[10px] font-bold text-slate-400 uppercase">自定义</span>
<input type="date" class="bg-transparent text-xs font-bold outline-none border-none cursor-pointer">
<span class="text-slate-400">-</span>
<input type="date" class="bg-transparent text-xs font-bold outline-none border-none cursor-pointer">
</div>
</div>
</header>
<!-- 1. 核心 KPI (覆盖:销售额, ROI, 目标达成, 税后盈亏, 日单量, 客单价) -->
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
<div class="glass p-5 rounded-3xl">
<div class="text-[10px] font-bold text-indigo-500 uppercase">销售额</div>
<div class="text-2xl font-black">¥128,400</div>
</div>
<div class="glass p-5 rounded-3xl border-l-4 border-l-indigo-500">
<div class="text-[10px] font-bold text-indigo-500 uppercase">ROI / 费比</div>
<div class="text-2xl font-black">4.21 <span class="text-xs text-slate-400 font-normal">/ 23%</span></div>
</div>
<div class="glass p-5 rounded-3xl">
<div class="text-[10px] font-bold text-indigo-500 uppercase">达成率</div>
<div class="text-2xl font-black text-indigo-600">85.4%</div>
</div>
<div class="glass p-5 rounded-3xl">
<div class="text-[10px] font-bold text-indigo-500 uppercase">单量 / 客单价</div>
<div class="text-2xl font-black">812 <span class="text-xs text-slate-400 font-normal">/ ¥158</span></div>
</div>
<div class="glass p-5 rounded-3xl">
<div class="text-[10px] font-bold text-indigo-500 uppercase">推广费总和</div>
<div class="text-2xl font-black">¥45,000</div>
</div>
<div class="glass p-5 rounded-3xl bg-emerald-500/10 border-l-4 border-l-emerald-500">
<div class="text-[10px] font-bold text-emerald-600 uppercase">税后盈亏</div>
<div class="text-2xl font-black text-emerald-600">¥12,450</div>
</div>
</div>
<!-- 2. 图表与财务损益拆解 -->
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-2 glass p-6 rounded-[2rem]">
<h3 class="font-bold text-lg mb-4">业绩趋势 (10/05 - 10/11)</h3>
<div id="shopTrend" style="height: 380px;"></div>
</div>
<!-- 16维度损益明细 -->
<div class="glass p-6 rounded-[2rem] flex flex-col">
<h3 class="font-bold text-lg mb-4">财务损益全维度 (P&L)</h3>
<div class="space-y-3 text-sm flex-1 overflow-y-auto pr-2 no-scrollbar">
<div class="flex justify-between p-2 rounded-xl bg-white/20"><span class="opacity-60">目标单量</span><span class="font-bold">2,000 单</span></div>
<div class="flex justify-between p-2"><span class="opacity-60">成本运费</span><span class="font-bold text-red-500">-¥32,400</span></div>
<div class="flex justify-between p-2"><span class="opacity-60">退款金额</span><span class="font-bold text-red-500">-¥8,200</span></div>
<div class="flex justify-between p-2"><span class="opacity-60">推广费用(今日)</span><span class="font-bold">¥3,200</span></div>
<div class="flex justify-between p-2"><span class="opacity-60">刷单费用</span><span class="font-bold text-orange-500">¥1,500</span></div>
<div class="flex justify-between p-2 pt-4 border-t border-white/40"><span class="text-indigo-600 font-bold">税前盈亏</span><span class="font-bold text-indigo-600">¥17,586</span></div>
<div class="flex justify-between p-2"><span class="opacity-40 italic text-xs">销售额 4% 税</span><span class="opacity-40 text-xs">¥5,136</span></div>
<!-- 最终结果 -->
<div class="flex justify-between p-4 rounded-2xl bg-gradient-to-r from-indigo-600 to-indigo-800 text-white shadow-xl shadow-indigo-100 mt-4">
<span class="font-bold uppercase tracking-widest text-xs opacity-80">税后盈亏 (Final)</span>
<span class="text-2xl font-black">¥12,450</span>
</div>
</div>
</div>
</div>
<!-- 3. 商品贡献列表 -->
<div class="glass rounded-[2rem] overflow-hidden">
<div class="p-6 border-b border-white/40">
<h3 class="font-bold text-lg">核心商品利润排名</h3>
</div>
<div class="overflow-x-auto">
<table class="w-full text-left">
<thead>
<tr class="text-[10px] uppercase tracking-widest text-slate-400">
<th class="p-5 font-bold">商品名/SKU</th>
<th class="p-5 font-bold">销售额</th>
<th class="p-5 font-bold">推广费</th>
<th class="p-5 font-bold">ROI</th>
<th class="p-5 font-bold text-emerald-600">单品净利</th>
</tr>
</thead>
<tbody class="text-sm divide-y divide-white/20">
<tr class="hover:bg-white/30 transition">
<td class="p-5 font-bold italic">2023 智能降噪耳机 Pro</td>
<td class="p-5">¥42,000</td>
<td class="p-5">¥5,200</td>
<td class="p-5"><span class="px-3 py-1 bg-indigo-100 text-indigo-600 rounded-lg font-bold">8.1</span></td>
<td class="p-5 font-black text-emerald-600">¥12,400</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script>
// 时间切换效果
function switchTime(btn) {
document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
}
// Echarts 初始化 (销售趋势图)
const chart = echarts.init(document.getElementById('shopTrend'));
chart.setOption({
grid: { top: 20, left: 40, right: 20, bottom: 40 },
tooltip: { trigger: 'axis', backgroundColor: 'rgba(255,255,255,0.9)' },
xAxis: { type: 'category', data: ['10-05', '10-06', '10-07', '10-08', '10-09', '10-10', '10-11'] },
yAxis: { type: 'value', splitLine: { lineStyle: { type: 'dashed', color: 'rgba(255,255,255,0.5)' } } },
series: [{
name: '销售额',
type: 'line',
smooth: true,
symbol: 'circle',
symbolSize: 10,
lineStyle: { width: 4, color: '#6366f1' },
itemStyle: { color: '#6366f1', borderColor: '#fff', borderWidth: 2 },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(99, 102, 241, 0.4)' },
{ offset: 1, color: 'rgba(99, 102, 241, 0)' }
])
},
data: [82, 93, 90, 120, 129, 133, 128]
}]
});
window.onresize = chart.resize;
</script>
</body>
</html>