feat: 完善公司全店概览

This commit is contained in:
ah--desktop
2026-01-12 23:55:21 +08:00
parent 59a649f002
commit 290223fdba
22 changed files with 2457 additions and 324 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.shopmonthlytarget.CreateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.ShopMonthlyTargetFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.UpdateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopMonthlyTargetVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopMonthlyTargetService;
/**
* 店铺月销量目标管理控制器
*/
@Tag(name = "电商-店铺月销量目标管理", description = "店铺月销量目标的增删改查接口")
@RestController
@RequestMapping("/ec/shop-monthly-target")
public class ShopMonthlyTargetController {
private final ShopMonthlyTargetService shopMonthlyTargetService;
public ShopMonthlyTargetController(ShopMonthlyTargetService shopMonthlyTargetService) {
this.shopMonthlyTargetService = shopMonthlyTargetService;
}
@Operation(summary = "创建店铺月销量目标", description = "创建新的店铺月销量目标")
@PostMapping("/create")
@RequireRole(description = "创建店铺月销量目标", allowUser = false)
public ApiResponse<ShopMonthlyTargetVO> createShopMonthlyTarget(@Valid @RequestBody CreateShopMonthlyTargetDTO createDTO) {
ShopMonthlyTargetVO vo = shopMonthlyTargetService.createShopMonthlyTarget(createDTO);
return ApiResponse.success(vo);
}
@Operation(summary = "更新店铺月销量目标", description = "更新现有店铺月销量目标信息")
@PutMapping("/update/{id}")
@RequireRole(description = "更新店铺月销量目标", allowUser = false)
public ApiResponse<ShopMonthlyTargetVO> updateShopMonthlyTarget(@Valid @RequestBody UpdateShopMonthlyTargetDTO updateDTO,
@Parameter(description = "目标ID") @PathVariable Long id) {
ShopMonthlyTargetVO vo = shopMonthlyTargetService.updateShopMonthlyTarget(updateDTO, id);
return ApiResponse.success(vo);
}
@Operation(summary = "删除店铺月销量目标", description = "删除指定店铺月销量目标")
@DeleteMapping("/delete/{id}")
@RequireRole(description = "删除店铺月销量目标", allowUser = false)
public ApiResponse<Void> deleteShopMonthlyTarget(
@Parameter(description = "目标ID") @PathVariable Long id) {
shopMonthlyTargetService.deleteShopMonthlyTarget(id);
return ApiResponse.success();
}
@Operation(summary = "分页获取店铺月销量目标列表", description = "分页获取店铺月销量目标列表,支持条件过滤")
@PostMapping("/page")
@RequireRole(description = "查询店铺月销量目标列表", allowUser = true)
public ApiResponse<PageResultVO<ShopMonthlyTargetVO>> getShopMonthlyTargetPage(
@Valid @RequestBody PageQueryDTO<ShopMonthlyTargetFilterDTO> pageQueryDTO) {
PageResultVO<ShopMonthlyTargetVO> result = shopMonthlyTargetService.getShopMonthlyTargetPage(pageQueryDTO);
return ApiResponse.success(result);
}
@Operation(summary = "获取店铺月销量目标详情", description = "根据ID获取店铺月销量目标详情")
@GetMapping("/detail/{id}")
@RequireRole(description = "查询店铺月销量目标详情", allowUser = true)
public ApiResponse<ShopMonthlyTargetVO> getShopMonthlyTargetById(
@Parameter(description = "目标ID") @PathVariable Long id) {
ShopMonthlyTargetVO vo = shopMonthlyTargetService.getShopMonthlyTargetById(id);
return ApiResponse.success(vo);
}
}
@@ -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.ShopMonthlyTargetPO;
/**
* 店铺月销量目标Mapper接口
*/
@Mapper
public interface ShopMonthlyTargetMapper extends BaseMapper<ShopMonthlyTargetPO> {
}
@@ -0,0 +1,54 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* 创建店铺月销量目标DTO
*/
@Data
@Schema(description = "创建店铺月销量目标DTO")
public class CreateShopMonthlyTargetDTO {
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "店铺ID不能为空")
private Long shopId;
/**
* 目标月份(格式:YYYY-MM-01)
*/
@Schema(description = "目标月份", example = "2024-01-01", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标月份不能为空")
private LocalDate targetMonth;
/**
* 目标销售额
*/
@Schema(description = "目标销售额", example = "100000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标销售额不能为空")
@PositiveOrZero(message = "目标销售额必须大于等于0")
private BigDecimal targetAmount;
/**
* 目标订单数
*/
@Schema(description = "目标订单数", example = "1000", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标订单数不能为空")
@PositiveOrZero(message = "目标订单数必须大于等于0")
private Integer targetOrderCount;
/**
* 备注
*/
@Schema(description = "备注", example = "1月目标")
private String remark;
}
@@ -0,0 +1,33 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDate;
/**
* 店铺月销量目标分页查询过滤DTO
*/
@Data
@Schema(description = "店铺月销量目标分页查询过滤DTO")
public class ShopMonthlyTargetFilterDTO {
/**
* 店铺ID
*/
@Schema(description = "店铺ID", example = "1")
private Long shopId;
/**
* 目标月份范围-开始月份
*/
@Schema(description = "目标月份范围-开始月份", example = "2024-01-01")
private LocalDate startTargetMonth;
/**
* 目标月份范围-结束月份
*/
@Schema(description = "目标月份范围-结束月份", example = "2024-12-01")
private LocalDate endTargetMonth;
}
@@ -0,0 +1,47 @@
package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* 更新店铺月销量目标DTO
*/
@Data
@Schema(description = "更新店铺月销量目标DTO")
public class UpdateShopMonthlyTargetDTO {
/**
* 目标月份(格式:YYYY-MM-01)
*/
@Schema(description = "目标月份", example = "2024-01-01", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标月份不能为空")
private LocalDate targetMonth;
/**
* 目标销售额
*/
@Schema(description = "目标销售额", example = "100000.00", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标销售额不能为空")
@PositiveOrZero(message = "目标销售额必须大于等于0")
private BigDecimal targetAmount;
/**
* 目标订单数
*/
@Schema(description = "目标订单数", example = "1000", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "目标订单数不能为空")
@PositiveOrZero(message = "目标订单数必须大于等于0")
private Integer targetOrderCount;
/**
* 备注
*/
@Schema(description = "备注", example = "1月目标")
private String remark;
}
@@ -0,0 +1,85 @@
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.LocalDate;
import java.time.LocalDateTime;
/**
* 电商-店铺月销量目标实体
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("ec_shop_monthly_target")
public class ShopMonthlyTargetPO {
/**
* 目标ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 公司ID
*/
@TableField("company_id")
private Long companyId;
/**
* 店铺ID
*/
@TableField("shop_id")
private Long shopId;
/**
* 目标月份(格式:YYYY-MM-01)
*/
@TableField("target_month")
private LocalDate targetMonth;
/**
* 目标销售额
*/
@TableField("target_amount")
private BigDecimal targetAmount;
/**
* 目标订单数
*/
@TableField("target_order_count")
private Integer targetOrderCount;
/**
* 备注
*/
@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;
}
@@ -85,6 +85,30 @@ public class CompanyOverviewVO {
@Schema(description = "总税后盈亏", example = "80000.00")
private BigDecimal totalProfitAfterTax;
/**
* 全店总销量目标(目标订单数)
*/
@Schema(description = "全店总销量目标(目标订单数)", example = "1200")
private Integer totalTargetOrderCount;
/**
* 全店总销售额目标
*/
@Schema(description = "全店总销售额目标", example = "120000.00")
private BigDecimal totalTargetAmount;
/**
* 销量目标达成率(实际订单数/目标订单数)
*/
@Schema(description = "销量目标达成率", example = "83.33")
private BigDecimal orderCountAchievementRate;
/**
* 销售额目标达成率(实际销售额/目标销售额)
*/
@Schema(description = "销售额目标达成率", example = "83.33")
private BigDecimal salesAmountAchievementRate;
/**
* 店铺销售占比
*/
@@ -127,7 +151,7 @@ public class CompanyOverviewVO {
}
/**
* 店铺对比数据(16维度)
* 店铺对比数据
*/
@Data
@Schema(description = "店铺对比数据")
@@ -141,50 +165,53 @@ public class CompanyOverviewVO {
@Schema(description = "平台", example = "拼多多")
private String platform;
@Schema(description = "目标销量(目标订单数)", example = "1000")
private Integer targetOrderCount;
@Schema(description = "销量达成率", example = "83.33")
private BigDecimal orderCountAchievementRate;
@Schema(description = "目标销售额", example = "100000.00")
private BigDecimal targetAmount;
@Schema(description = "销售额达成率", example = "83.33")
private BigDecimal salesAmountAchievementRate;
@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")
@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 = "5000.00")
private BigDecimal shippingCost;
@Schema(description = "推广费占比", example = "0.10")
private BigDecimal promotionFeeRatio;
@Schema(description = "退款金额", example = "1000.00")
private BigDecimal refundAmount;
@Schema(description = "退款率", example = "0.02")
private BigDecimal refundRate;
@Schema(description = "推广费", example = "5000.00")
private BigDecimal totalPromotionFee;
@Schema(description = "刷单费用", example = "2000.00")
private BigDecimal brushFee;
@Schema(description = "费比", example = "0.10")
private BigDecimal feeRatio;
@Schema(description = "税前盈亏", example = "35000.00")
private BigDecimal totalProfitBeforeTax;
@Schema(description = "销售额4%税额", example = "2000.00")
private BigDecimal salesTaxAmount;
@Schema(description = "税后盈亏", example = "30000.00")
private BigDecimal profitAfterTax;
@Schema(description = "ROI", example = "1.5")
private BigDecimal roi;
}
}
@@ -0,0 +1,89 @@
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.LocalDate;
import java.time.LocalDateTime;
/**
* 店铺月销量目标VO
*/
@Data
@Schema(description = "店铺月销量目标VO")
public class ShopMonthlyTargetVO {
/**
* 目标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;
/**
* 目标月份
*/
@Schema(description = "目标月份", example = "2024-01-01")
private LocalDate targetMonth;
/**
* 目标销售额
*/
@Schema(description = "目标销售额", example = "100000.00")
private BigDecimal targetAmount;
/**
* 目标订单数
*/
@Schema(description = "目标订单数", example = "1000")
private Integer targetOrderCount;
/**
* 备注
*/
@Schema(description = "备注", example = "1月目标")
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,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.shopmonthlytarget.CreateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.ShopMonthlyTargetFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.UpdateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopMonthlyTargetVO;
/**
* 店铺月销量目标服务接口
*/
public interface ShopMonthlyTargetService extends IService<ShopMonthlyTargetPO> {
/**
* 创建店铺月销量目标
*
* @param createDTO 创建店铺月销量目标DTO
* @return 店铺月销量目标VO
*/
ShopMonthlyTargetVO createShopMonthlyTarget(CreateShopMonthlyTargetDTO createDTO);
/**
* 更新店铺月销量目标
*
* @param updateDTO 更新店铺月销量目标DTO
* @param id 目标ID
* @return 店铺月销量目标VO
*/
ShopMonthlyTargetVO updateShopMonthlyTarget(UpdateShopMonthlyTargetDTO updateDTO, Long id);
/**
* 删除店铺月销量目标
*
* @param id 目标ID
*/
void deleteShopMonthlyTarget(Long id);
/**
* 分页获取店铺月销量目标列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果
*/
PageResultVO<ShopMonthlyTargetVO> getShopMonthlyTargetPage(PageQueryDTO<ShopMonthlyTargetFilterDTO> pageQueryDTO);
/**
* 根据ID获取店铺月销量目标详情
*
* @param id 目标ID
* @return 店铺月销量目标VO
*/
ShopMonthlyTargetVO getShopMonthlyTargetById(Long id);
}
@@ -6,11 +6,13 @@ 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.mapper.ShopMonthlyTargetMapper;
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.ShopMonthlyTargetPO;
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;
@@ -40,6 +42,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private final OrderMapper orderMapper;
private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService;
private final OrderStatusService orderStatusService;
@@ -47,12 +50,14 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
OrderMapper orderMapper,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService,
OrderStatusService orderStatusService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService;
this.orderStatusService = orderStatusService;
}
@@ -179,9 +184,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
shops, orders, promotionFees, brushOrders, refundStatusId);
overviewVO.setShopEfficiencyQuadrants(shopEfficiencyQuadrants);
// 9. 多店铺数据横向对比(16维度)
// 9. 多店铺数据横向对比
List<CompanyOverviewVO.ShopComparison> shopComparisons = calculateShopComparisons(
shops, orders, promotionFees, brushOrders, refundStatusId);
shops, orders, promotionFees, brushOrders, refundStatusId, companyId, startDate, endDate);
overviewVO.setShopComparisons(shopComparisons);
// 10. 汇总ROI和总税后盈亏
@@ -189,9 +194,81 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
overviewVO.setTotalROI(totalROI);
overviewVO.setTotalProfitAfterTax(totalNetProfitAfterTax);
// 11. 计算目标维度的数据
calculateTargetData(overviewVO, companyId, startDate, endDate, totalSalesAmount, totalOrderCount);
return overviewVO;
}
/**
* 计算目标维度的数据
*/
private void calculateTargetData(CompanyOverviewVO overviewVO, Long companyId, LocalDate startDate, LocalDate endDate,
BigDecimal totalSalesAmount, Integer totalOrderCount) {
// 生成日期范围内所有月份的第一天列表
List<LocalDate> targetMonths = new ArrayList<>();
LocalDate currentMonth = startDate.withDayOfMonth(1);
LocalDate endMonth = endDate.withDayOfMonth(1);
while (!currentMonth.isAfter(endMonth)) {
targetMonths.add(currentMonth);
currentMonth = currentMonth.plusMonths(1);
}
// 查询所有店铺在这些月份的目标数据
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> targets = shopMonthlyTargetMapper.selectList(targetWrapper);
// 汇总所有店铺的目标数据(按店铺汇总,因为同一店铺可能有多个月的目标)
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = targets.stream()
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
// 计算总目标销售额和总目标订单数
BigDecimal totalTargetAmount = BigDecimal.ZERO;
Integer totalTargetOrderCount = 0;
for (List<ShopMonthlyTargetPO> shopTargets : targetsByShop.values()) {
// 对于每个店铺,汇总其所有月份的目标
BigDecimal shopTargetAmount = shopTargets.stream()
.map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Integer shopTargetOrderCount = shopTargets.stream()
.mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0)
.sum();
totalTargetAmount = totalTargetAmount.add(shopTargetAmount);
totalTargetOrderCount += shopTargetOrderCount;
}
overviewVO.setTotalTargetAmount(totalTargetAmount);
overviewVO.setTotalTargetOrderCount(totalTargetOrderCount);
// 计算达成率
BigDecimal salesAmountAchievementRate = BigDecimal.ZERO;
if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
// 目标为0但实际有销售额,达成率设为100%
salesAmountAchievementRate = new BigDecimal("100");
}
overviewVO.setSalesAmountAchievementRate(salesAmountAchievementRate);
BigDecimal orderCountAchievementRate = BigDecimal.ZERO;
if (totalTargetOrderCount > 0) {
orderCountAchievementRate = new BigDecimal(totalOrderCount)
.divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (totalOrderCount > 0) {
// 目标为0但实际有订单,达成率设为100%
orderCountAchievementRate = new BigDecimal("100");
}
overviewVO.setOrderCountAchievementRate(orderCountAchievementRate);
}
/**
* 计算总利润(税前)
*/
@@ -320,11 +397,11 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
/**
* 计算多店铺数据横向对比(16维度)
* 计算多店铺数据横向对比
*/
private List<CompanyOverviewVO.ShopComparison> calculateShopComparisons(
List<ShopPO> shops, List<OrderPO> orders, List<PromotionFeePO> promotionFees,
List<BrushOrderPO> brushOrders, Long refundStatusId) {
List<BrushOrderPO> brushOrders, Long refundStatusId, Long companyId, LocalDate startDate, LocalDate endDate) {
List<CompanyOverviewVO.ShopComparison> comparisons = new ArrayList<>();
// 按店铺分组数据
@@ -335,16 +412,37 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
Map<Long, List<BrushOrderPO>> brushOrdersByShop = brushOrders.stream()
.collect(Collectors.groupingBy(BrushOrderPO::getShopId));
// 查询所有店铺的目标数据
List<LocalDate> targetMonths = new ArrayList<>();
LocalDate currentMonth = startDate.withDayOfMonth(1);
LocalDate endMonth = endDate.withDayOfMonth(1);
while (!currentMonth.isAfter(endMonth)) {
targetMonths.add(currentMonth);
currentMonth = currentMonth.plusMonths(1);
}
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.in(ShopMonthlyTargetPO::getTargetMonth, targetMonths);
List<ShopMonthlyTargetPO> allTargets = shopMonthlyTargetMapper.selectList(targetWrapper);
// 按店铺分组目标数据
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = allTargets.stream()
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::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<>());
List<ShopMonthlyTargetPO> shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>());
// 计算各项指标
BigDecimal salesAmount = shopOrders.stream()
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
int orderCount = shopOrders.size();
BigDecimal refundAmount = shopOrders.stream()
.filter(order -> refundStatusId != null && refundStatusId.equals(order.getStatusId()))
.map(order -> order.getReceivedAmount() != null ? order.getReceivedAmount() : BigDecimal.ZERO)
@@ -358,10 +456,23 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// 计算成本运费(单独计算运费成本)
BigDecimal shippingCost = shopOrders.stream()
.map(order -> {
BigDecimal cost = order.getShippingCost() != null ? order.getShippingCost() : BigDecimal.ZERO;
Integer quantity = order.getQuantity() != null ? order.getQuantity() : 1;
return cost.multiply(new BigDecimal(quantity));
})
.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);
// 销售额4%税额
BigDecimal salesTaxAmount = salesAmount.multiply(new BigDecimal("0.04"));
// 税后盈亏(扣除销售额4%税额)
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
BigDecimal totalCostForROI = totalPromotionFee.add(brushFee);
BigDecimal roi = calculateShopROI(profitBeforeTax, totalCostForROI);
@@ -372,45 +483,57 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
}
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 targetAmount = shopTargets.stream()
.map(target -> target.getTargetAmount() != null ? target.getTargetAmount() : BigDecimal.ZERO)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Integer targetOrderCount = shopTargets.stream()
.mapToInt(target -> target.getTargetOrderCount() != null ? target.getTargetOrderCount() : 0)
.sum();
// 计算达成率
BigDecimal salesAmountAchievementRate = BigDecimal.ZERO;
if (targetAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = salesAmount.divide(targetAmount, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (salesAmount.compareTo(BigDecimal.ZERO) > 0) {
salesAmountAchievementRate = new BigDecimal("100");
}
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);
BigDecimal orderCountAchievementRate = BigDecimal.ZERO;
if (targetOrderCount > 0) {
orderCountAchievementRate = new BigDecimal(orderCount)
.divide(new BigDecimal(targetOrderCount), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"));
} else if (orderCount > 0) {
orderCountAchievementRate = new BigDecimal("100");
}
CompanyOverviewVO.ShopComparison comparison = new CompanyOverviewVO.ShopComparison();
comparison.setShopId(shop.getId());
comparison.setShopName(shop.getName());
comparison.setPlatform(shop.getPlatform());
comparison.setTargetOrderCount(targetOrderCount);
comparison.setOrderCountAchievementRate(orderCountAchievementRate);
comparison.setTargetAmount(targetAmount);
comparison.setSalesAmountAchievementRate(salesAmountAchievementRate);
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);
comparison.setShippingCost(shippingCost);
comparison.setRefundAmount(refundAmount);
comparison.setTotalPromotionFee(totalPromotionFee);
comparison.setBrushFee(brushFee);
comparison.setFeeRatio(feeRatio);
comparison.setTotalProfitBeforeTax(profitBeforeTax);
comparison.setSalesTaxAmount(salesTaxAmount);
comparison.setProfitAfterTax(profitAfterTax);
comparison.setRoi(roi);
comparisons.add(comparison);
}
@@ -0,0 +1,222 @@
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.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.CreateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.ShopMonthlyTargetFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.shopmonthlytarget.UpdateShopMonthlyTargetDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ShopMonthlyTargetVO;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopMonthlyTargetService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;
/**
* 店铺月销量目标服务实现类
*/
@Service
public class ShopMonthlyTargetServiceImpl extends ServiceImpl<ShopMonthlyTargetMapper, ShopMonthlyTargetPO> implements ShopMonthlyTargetService {
private final CurrentUserContext currentUserContext;
private final ShopService shopService;
public ShopMonthlyTargetServiceImpl(CurrentUserContext currentUserContext, ShopService shopService) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
}
/**
* 创建店铺月销量目标
*
* @param createDTO 创建店铺月销量目标DTO
* @return 店铺月销量目标VO
*/
@Override
@Transactional
public ShopMonthlyTargetVO createShopMonthlyTarget(CreateShopMonthlyTargetDTO createDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
// 验证店铺是否存在且属于当前公司
ShopPO shop = shopService.getById(createDTO.getShopId());
if (shop == null || !shop.getCompanyId().equals(companyId)) {
throw new BusinessException("店铺不存在");
}
// 验证目标月份格式(确保是每月的第一天)
LocalDate targetMonth = createDTO.getTargetMonth();
if (targetMonth.getDayOfMonth() != 1) {
throw new BusinessException("目标月份必须是每月的第一天(格式:YYYY-MM-01)");
}
// 检查该店铺该月份是否已存在目标
LambdaQueryWrapper<ShopMonthlyTargetPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShopMonthlyTargetPO::getShopId, createDTO.getShopId())
.eq(ShopMonthlyTargetPO::getTargetMonth, targetMonth)
.eq(ShopMonthlyTargetPO::getCompanyId, companyId);
if (this.count(wrapper) > 0) {
throw new BusinessException("该店铺该月份的目标已存在");
}
// 创建目标记录
ShopMonthlyTargetPO target = new ShopMonthlyTargetPO();
BeanUtils.copyProperties(createDTO, target);
target.setCompanyId(companyId);
target.setCreateBy(userId);
this.save(target);
return convertToVO(target);
}
/**
* 更新店铺月销量目标
*
* @param updateDTO 更新店铺月销量目标DTO
* @param id 目标ID
* @return 店铺月销量目标VO
*/
@Override
@Transactional
public ShopMonthlyTargetVO updateShopMonthlyTarget(UpdateShopMonthlyTargetDTO updateDTO, Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
ShopMonthlyTargetPO existingTarget = this.getById(id);
if (existingTarget == null || !existingTarget.getCompanyId().equals(companyId)) {
throw new BusinessException("目标不存在");
}
// 验证目标月份格式(确保是每月的第一天)
LocalDate targetMonth = updateDTO.getTargetMonth();
if (targetMonth.getDayOfMonth() != 1) {
throw new BusinessException("目标月份必须是每月的第一天(格式:YYYY-MM-01)");
}
// 如果月份改变了,检查新月份是否已存在目标(排除当前记录)
if (!targetMonth.equals(existingTarget.getTargetMonth())) {
LambdaQueryWrapper<ShopMonthlyTargetPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShopMonthlyTargetPO::getShopId, existingTarget.getShopId())
.eq(ShopMonthlyTargetPO::getTargetMonth, targetMonth)
.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
.ne(ShopMonthlyTargetPO::getId, id);
if (this.count(wrapper) > 0) {
throw new BusinessException("该店铺该月份的目标已存在");
}
}
// 更新目标记录
ShopMonthlyTargetPO target = new ShopMonthlyTargetPO();
BeanUtils.copyProperties(updateDTO, target);
target.setId(id);
target.setCompanyId(companyId);
target.setShopId(existingTarget.getShopId()); // 保持店铺ID不变
target.setUpdateBy(userId);
this.updateById(target);
return convertToVO(target);
}
/**
* 删除店铺月销量目标
*
* @param id 目标ID
*/
@Override
@Transactional
public void deleteShopMonthlyTarget(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
ShopMonthlyTargetPO existingTarget = this.getById(id);
if (existingTarget == null || !existingTarget.getCompanyId().equals(companyId)) {
throw new BusinessException("目标不存在");
}
this.removeById(id);
}
/**
* 分页获取店铺月销量目标列表
*
* @param pageQueryDTO 分页查询DTO
* @return 分页结果VO
*/
@Override
public PageResultVO<ShopMonthlyTargetVO> getShopMonthlyTargetPage(PageQueryDTO<ShopMonthlyTargetFilterDTO> pageQueryDTO) {
Long companyId = currentUserContext.getCurrentCompanyId();
Page<ShopMonthlyTargetPO> page = new Page<>(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
LambdaQueryWrapper<ShopMonthlyTargetPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId);
ShopMonthlyTargetFilterDTO filter = pageQueryDTO.getFilters();
if (filter != null) {
if (filter.getShopId() != null) {
wrapper.eq(ShopMonthlyTargetPO::getShopId, filter.getShopId());
}
if (filter.getStartTargetMonth() != null) {
wrapper.ge(ShopMonthlyTargetPO::getTargetMonth, filter.getStartTargetMonth());
}
if (filter.getEndTargetMonth() != null) {
wrapper.le(ShopMonthlyTargetPO::getTargetMonth, filter.getEndTargetMonth());
}
}
wrapper.orderByDesc(ShopMonthlyTargetPO::getTargetMonth)
.orderByDesc(ShopMonthlyTargetPO::getCreateTime);
IPage<ShopMonthlyTargetPO> pageResult = this.page(page, wrapper);
List<ShopMonthlyTargetVO> 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 ShopMonthlyTargetVO getShopMonthlyTargetById(Long id) {
Long companyId = currentUserContext.getCurrentCompanyId();
ShopMonthlyTargetPO target = this.getById(id);
if (target == null || !target.getCompanyId().equals(companyId)) {
throw new BusinessException("目标不存在");
}
return convertToVO(target);
}
/**
* 转换为VO
*/
private ShopMonthlyTargetVO convertToVO(ShopMonthlyTargetPO target) {
ShopMonthlyTargetVO vo = new ShopMonthlyTargetVO();
BeanUtils.copyProperties(target, vo);
// 设置店铺名称
if (target.getShopId() != null) {
ShopPO shop = shopService.getById(target.getShopId());
if (shop != null) {
vo.setShopName(shop.getName());
}
}
return vo;
}
}
@@ -327,3 +327,30 @@ CREATE TABLE `ec_brush_order` (
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='电商-刷单记录表';
-- 店铺月销量目标表
CREATE TABLE `ec_shop_monthly_target` (
`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',
`target_month` DATE NOT NULL COMMENT '目标月份(格式:YYYY-MM-01)',
`target_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '目标销售额',
`target_order_count` INT NOT NULL DEFAULT 0 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_target_month` (`target_month`),
KEY `idx_company_shop_month` (`company_id`, `shop_id`, `target_month`),
KEY `fk_ec_shop_monthly_target_creator` (`create_by`),
KEY `fk_ec_shop_monthly_target_updater` (`update_by`),
UNIQUE KEY `uk_shop_month` (`shop_id`, `target_month`),
CONSTRAINT `fk_ec_shop_monthly_target_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_shop_monthly_target_shop` FOREIGN KEY (`shop_id`) REFERENCES `ec_shop` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ec_shop_monthly_target_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_ec_shop_monthly_target_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='电商-店铺月销量目标表';