mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
refactor: 完全迁移店铺概览和商品概览到bi层
This commit is contained in:
+94
-1
@@ -4,8 +4,9 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
@@ -33,6 +34,96 @@ public class BiOrderStatQueryService {
|
||||
return repository.listProductDocs(companyId, shopIds, start, end);
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
Long productId,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listProductDocs(companyId, shopIds, productId, start, end);
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocs(Long companyId, Long productId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listSkuDocs(companyId, productId, shopIds, start, end);
|
||||
}
|
||||
|
||||
/** 商品日文档按日历日合并(单商品趋势)。 */
|
||||
public List<OverviewAggRows.DailyRow> toDailyRowsFromProductDocs(
|
||||
List<BiOrderStatDailyProductDoc> productDocs) {
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
|
||||
for (BiOrderStatDailyProductDoc doc : productDocs) {
|
||||
if (doc == null || doc.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> {
|
||||
OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow();
|
||||
r.setStatDate(d);
|
||||
r.setSalesAmount(BigDecimal.ZERO);
|
||||
r.setRefundAmount(BigDecimal.ZERO);
|
||||
r.setProductCost(BigDecimal.ZERO);
|
||||
r.setFreightCost(BigDecimal.ZERO);
|
||||
r.setOtherCost(BigDecimal.ZERO);
|
||||
r.setOrderCount(0L);
|
||||
return r;
|
||||
});
|
||||
row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount())));
|
||||
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
|
||||
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
|
||||
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
|
||||
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
|
||||
row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount()));
|
||||
}
|
||||
return new ArrayList<>(byDay.values());
|
||||
}
|
||||
|
||||
/** SKU 日文档按 productSkuId 合并区间。 */
|
||||
public List<SkuPeriodMetrics> sumSkuDocsBySku(List<BiOrderStatDailySkuDoc> skuDocs) {
|
||||
Map<Long, SkuPeriodMetrics> merged = new HashMap<>();
|
||||
for (BiOrderStatDailySkuDoc doc : skuDocs) {
|
||||
if (doc == null) {
|
||||
continue;
|
||||
}
|
||||
long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L;
|
||||
SkuPeriodMetrics cur = merged.get(skuId);
|
||||
if (cur == null) {
|
||||
merged.put(skuId, new SkuPeriodMetrics(
|
||||
skuId,
|
||||
nz(doc.getSalesAmount()),
|
||||
nz(doc.getRefundAmount()),
|
||||
nz(doc.getProductCost()),
|
||||
nz(doc.getFreightCost()),
|
||||
nz(doc.getOtherCost()),
|
||||
nzInt(doc.getSalesOrderCount()),
|
||||
nzInt(doc.getSalesQuantitySum())));
|
||||
} else {
|
||||
merged.put(skuId, new SkuPeriodMetrics(
|
||||
skuId,
|
||||
cur.salesAmount().add(nz(doc.getSalesAmount())),
|
||||
cur.refundAmount().add(nz(doc.getRefundAmount())),
|
||||
cur.productCost().add(nz(doc.getProductCost())),
|
||||
cur.freightCost().add(nz(doc.getFreightCost())),
|
||||
cur.otherCost().add(nz(doc.getOtherCost())),
|
||||
cur.salesOrderCount() + nzInt(doc.getSalesOrderCount()),
|
||||
cur.salesQuantitySum() + nzInt(doc.getSalesQuantitySum())));
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(merged.values());
|
||||
}
|
||||
|
||||
public record SkuPeriodMetrics(
|
||||
long productSkuId,
|
||||
BigDecimal salesAmount,
|
||||
BigDecimal refundAmount,
|
||||
BigDecimal productCost,
|
||||
BigDecimal freightCost,
|
||||
BigDecimal otherCost,
|
||||
int salesOrderCount,
|
||||
int salesQuantitySum
|
||||
) {
|
||||
public BigDecimal orderCost() {
|
||||
return nz(productCost).add(nz(freightCost)).add(nz(otherCost));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品日文档按 (shopId, productId, categoryId) 合并区间后,转为工作台多维/四表所需行。
|
||||
* platformCode 由店铺主数据补齐(商品日文档无平台字段)。
|
||||
@@ -94,6 +185,7 @@ public class BiOrderStatQueryService {
|
||||
r.setProductCost(BigDecimal.ZERO);
|
||||
r.setFreightCost(BigDecimal.ZERO);
|
||||
r.setOtherCost(BigDecimal.ZERO);
|
||||
r.setOrderCount(0L);
|
||||
return r;
|
||||
});
|
||||
row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount())));
|
||||
@@ -101,6 +193,7 @@ public class BiOrderStatQueryService {
|
||||
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
|
||||
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
|
||||
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
|
||||
row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount()));
|
||||
}
|
||||
return new ArrayList<>(byDay.values());
|
||||
}
|
||||
|
||||
+39
-5
@@ -48,13 +48,47 @@ public class BiOrderStatDailyRepository {
|
||||
/** 区间内商品日文档(闭区间)。shopIds 为空返回空列表。 */
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || shopIds == null || shopIds.isEmpty() || start == null || end == null) {
|
||||
return listProductDocs(companyId, shopIds, null, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间内商品日文档。{@code productId} 非空时仅该商品;
|
||||
* {@code shopIds} 为空时不按店过滤(商品概览未指定店铺时用)。
|
||||
*/
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
Long productId,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").in(shopIds)
|
||||
.and("statDate").gte(start).lte(end));
|
||||
return mongoTemplate.find(q, BiOrderStatDailyProductDoc.class);
|
||||
Criteria c = Criteria.where("companyId").is(companyId)
|
||||
.and("statDate").gte(start).lte(end);
|
||||
if (shopIds != null && !shopIds.isEmpty()) {
|
||||
c = c.and("shopId").in(shopIds);
|
||||
}
|
||||
if (productId != null) {
|
||||
c = c.and("productId").is(productId);
|
||||
}
|
||||
return mongoTemplate.find(Query.query(c), BiOrderStatDailyProductDoc.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间内 SKU 日文档。{@code productId} 必填;
|
||||
* {@code shopIds} 为空时不按店过滤。
|
||||
*/
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocs(Long companyId, Long productId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || productId == null || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Criteria c = Criteria.where("companyId").is(companyId)
|
||||
.and("productId").is(productId)
|
||||
.and("statDate").gte(start).lte(end);
|
||||
if (shopIds != null && !shopIds.isEmpty()) {
|
||||
c = c.and("shopId").in(shopIds);
|
||||
}
|
||||
return mongoTemplate.find(Query.query(c), BiOrderStatDailySkuDoc.class);
|
||||
}
|
||||
|
||||
public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc,
|
||||
|
||||
+3
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@@ -39,6 +39,8 @@ public final class OverviewAggRows {
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
/** 当日销售单量合计(店铺/商品日汇聚 salesOrderCount) */
|
||||
private Long orderCount;
|
||||
}
|
||||
|
||||
@Data
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
+5
-10
@@ -1,21 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现)
|
||||
* 按品类维度导出 Excel(店铺品类汇总、工作台品类/商品维表)。
|
||||
*/
|
||||
public interface CategoryExportExcelService {
|
||||
|
||||
/** 店铺维度:按店铺 ID 导出品类汇总。 */
|
||||
byte[] exportCategoryOverview(CategoryExportDTO dto);
|
||||
|
||||
/**
|
||||
* 全店按品类:与 {@link top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService#getCompanyOverview} 同源,
|
||||
* 生成「品类汇总 + 销售趋势」两表。
|
||||
*/
|
||||
byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:品类/商品维度表已由调用方按筛选口径汇总,仅写「汇总」Sheet(无趋势表)。
|
||||
*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 工作台汇总表构建(原全店概览服务收口后仅保留聚合读路径)。
|
||||
*/
|
||||
public interface CompanyOverviewService {
|
||||
|
||||
/**
|
||||
* 基于 Mongo/SQL 聚合行构建工作台底部四表。
|
||||
*/
|
||||
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 工作台等多维表导出(按已汇总好的表写入 Excel)。
|
||||
*/
|
||||
public interface ExportService {
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按店铺」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按平台」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle);
|
||||
}
|
||||
+13
-130
@@ -1,16 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ShopOverviewStatisticsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
@@ -43,73 +43,23 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
|
||||
}
|
||||
|
||||
private final ExportStatusRangeHelper exportStatusRangeHelper;
|
||||
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
|
||||
public CategoryExportExcelServiceImpl(
|
||||
ExportStatusRangeHelper exportStatusRangeHelper,
|
||||
ShopOverviewStatisticsService shopOverviewStatisticsService) {
|
||||
BiShopOverviewService biShopOverviewService) {
|
||||
this.exportStatusRangeHelper = exportStatusRangeHelper;
|
||||
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCategoryOverview(CategoryExportDTO dto) {
|
||||
if (dto.getShopId() == null) {
|
||||
throw new BusinessException("全店按品类导出请使用 ExportService.exportCategoryOverview");
|
||||
throw new BusinessException("按品类导出必须指定店铺");
|
||||
}
|
||||
return exportShopCategoryViaOverview(dto);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
|
||||
LocalDate startDate = dateRange[0];
|
||||
LocalDate endDate = dateRange[1];
|
||||
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
|
||||
|
||||
CompanyOverviewVO.CategoryOverview co = overview.getCategorySummary();
|
||||
List<CompanyOverviewVO.CategorySummary> catRows = (co != null && co.getCategories() != null)
|
||||
? new ArrayList<>(co.getCategories())
|
||||
: new ArrayList<>();
|
||||
|
||||
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
|
||||
Set<Long> allowed = new HashSet<>(dto.getCategoryIds());
|
||||
catRows = catRows.stream()
|
||||
.filter(c -> allowed.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> shopRows = catRows.stream()
|
||||
.map(this::toShopCategorySummary)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
boolean categoryFiltered = dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty();
|
||||
ShopOverviewStatisticsVO.CategorySummary totalRow = categoryFiltered
|
||||
? aggregateCategoryTotals(shopRows, taxRate)
|
||||
: (co != null && co.getTotal() != null
|
||||
? toShopCategorySummary(co.getTotal())
|
||||
: aggregateCategoryTotals(shopRows, taxRate));
|
||||
|
||||
try (Workbook workbook = new XSSFWorkbook()) {
|
||||
Sheet sheet = workbook.createSheet("汇总");
|
||||
writeCategoryMultidimensionalSheet(
|
||||
sheet, "全店 - 品类多维度损益汇总", dateRangeLabel, shopRows, totalRow, taxRate, "品类名称");
|
||||
if (overview.getSalesAmountTrend() != null
|
||||
&& overview.getSalesAmountTrend().getDailyDataList() != null
|
||||
&& !overview.getSalesAmountTrend().getDailyDataList().isEmpty()) {
|
||||
Sheet trendSheet = workbook.createSheet("销售趋势");
|
||||
writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, overview);
|
||||
}
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("导出品类Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCategoryDimensionsFromTable(
|
||||
CategoryExportDTO dto,
|
||||
@@ -158,7 +108,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺侧导出:与 {@link ShopOverviewStatisticsService#getShopOverviewStatistics} 同源,
|
||||
* 店铺侧导出:与 {@link BiShopOverviewService#getShopOverview} 同源,
|
||||
* 保证订单状态参与统计、推广费/刷单费分摊与前端「品类多维度损益汇总」一致。
|
||||
*/
|
||||
private byte[] exportShopCategoryViaOverview(CategoryExportDTO dto) {
|
||||
@@ -173,7 +123,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
|
||||
query.setDateRange(dto.getDateRange());
|
||||
query.setTaxRate(taxRate);
|
||||
|
||||
ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(query);
|
||||
ShopOverviewStatisticsVO vo = biShopOverviewService.getShopOverview(query);
|
||||
ShopOverviewStatisticsVO.CategoryOverview co = vo.getCategoryOverview();
|
||||
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> rows = (co != null && co.getCategories() != null)
|
||||
@@ -280,73 +230,6 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
|
||||
sheet.setColumnWidth(2, 3200);
|
||||
}
|
||||
|
||||
/** 全店概览 {@link CompanyOverviewVO} 的日销售额、日单量趋势(与 /ec/store/overview 同源)。 */
|
||||
private void writeCompanyOverviewTrendSheet(
|
||||
Sheet sheet, String contextTitle, String dateRangeLabel, CompanyOverviewVO vo) {
|
||||
Workbook wb = sheet.getWorkbook();
|
||||
CellStyle headerStyle = createHeaderStyle(wb);
|
||||
CellStyle dataStyle = createDataStyle(wb);
|
||||
|
||||
Row titleRow = sheet.createRow(0);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellValue(contextTitle + " - 销售趋势 | " + dateRangeLabel);
|
||||
titleCell.setCellStyle(createTitleStyle(wb));
|
||||
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
|
||||
|
||||
String[] headers = {"日期", "销售额", "单量"};
|
||||
Row headerRow = sheet.createRow(1);
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
}
|
||||
|
||||
List<CompanyOverviewVO.TrendDataItem> dailySales = vo.getSalesAmountTrend().getDailyDataList();
|
||||
List<CompanyOverviewVO.TrendDataItem> dailyOrders = vo.getOrderCountTrend() != null
|
||||
? vo.getOrderCountTrend().getDailyDataList()
|
||||
: null;
|
||||
|
||||
Map<LocalDate, BigDecimal> salesMap = dailySales.stream()
|
||||
.collect(Collectors.toMap(
|
||||
CompanyOverviewVO.TrendDataItem::getDate,
|
||||
CompanyOverviewVO.TrendDataItem::getValue,
|
||||
(a, b) -> a));
|
||||
Map<LocalDate, BigDecimal> ordersMap = dailyOrders != null
|
||||
? dailyOrders.stream()
|
||||
.collect(Collectors.toMap(
|
||||
CompanyOverviewVO.TrendDataItem::getDate,
|
||||
CompanyOverviewVO.TrendDataItem::getValue,
|
||||
(a, b) -> a))
|
||||
: Collections.emptyMap();
|
||||
|
||||
LocalDate startDate = dailySales.stream()
|
||||
.map(CompanyOverviewVO.TrendDataItem::getDate)
|
||||
.min(LocalDate::compareTo)
|
||||
.orElse(null);
|
||||
LocalDate endDate = dailySales.stream()
|
||||
.map(CompanyOverviewVO.TrendDataItem::getDate)
|
||||
.max(LocalDate::compareTo)
|
||||
.orElse(null);
|
||||
|
||||
int rowIdx = 2;
|
||||
if (startDate != null && endDate != null) {
|
||||
LocalDate current = startDate;
|
||||
while (!current.isAfter(endDate)) {
|
||||
Row row = sheet.createRow(rowIdx++);
|
||||
BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
setCell(row, 0, current.format(DATE_FMT), dataStyle);
|
||||
setCell(row, 1, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
current = current.plusDays(1);
|
||||
}
|
||||
}
|
||||
|
||||
sheet.setColumnWidth(0, 3200);
|
||||
sheet.setColumnWidth(1, 3200);
|
||||
sheet.setColumnWidth(2, 3200);
|
||||
}
|
||||
|
||||
private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) {
|
||||
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
|
||||
s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L);
|
||||
+775
@@ -0,0 +1,775 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 工作台汇总表构建(聚合行读路径)。
|
||||
*/
|
||||
@Service
|
||||
public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private BigDecimal taxRate = DEFAULT_TAX_RATE;
|
||||
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final CategoryService categoryService;
|
||||
|
||||
public CompanyOverviewServiceImpl(
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ProductMapper productMapper,
|
||||
CategoryService categoryService) {
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.productMapper = productMapper;
|
||||
this.categoryService = categoryService;
|
||||
}
|
||||
|
||||
private BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount) {
|
||||
BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO;
|
||||
BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO;
|
||||
BigDecimal base = sales.subtract(refund);
|
||||
if (base.compareTo(BigDecimal.ZERO) < 0) {
|
||||
base = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
|
||||
return base.multiply(rate).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
/** 计算ROI:(销售额 - 退款金额)/ 推广费用 */
|
||||
private BigDecimal calculateSalesROI(BigDecimal netSales, BigDecimal promotionFee) {
|
||||
if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
return netSales.divide(promotionFee, 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
/** 计算店铺汇总的合计行 */
|
||||
private CompanyOverviewVO.ShopSummary computeShopTotal(List<CompanyOverviewVO.ShopSummary> shops) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
int totalOrders = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrders = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalGmv = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.ShopSummary s : shops) {
|
||||
totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalGmv = totalGmv.add(s.getGmv() != null ? s.getGmv() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(s.getGrossProfit() != null ? s.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalOrders += s.getOrderCount() != null ? s.getOrderCount() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal avgOrderValue = totalOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrders > 0
|
||||
? new BigDecimal(totalOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.ShopSummary total = new CompanyOverviewVO.ShopSummary();
|
||||
total.setShopId(0L);
|
||||
total.setShopName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setGmv(totalGmv);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setOrderCount(totalOrders);
|
||||
total.setAverageOrderValue(avgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrders);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 计算品类汇总的合计行 */
|
||||
private CompanyOverviewVO.CategorySummary computeCategoryTotal(List<CompanyOverviewVO.CategorySummary> categories) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
int totalOrders = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalGmv = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.CategorySummary c : categories) {
|
||||
totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalGmv = totalGmv.add(c.getGmv() != null ? c.getGmv() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(c.getGrossProfit() != null ? c.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalOrders += c.getOrderCount() != null ? c.getOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal avgOrderValue = totalOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetSales(totalSales, totalRefund);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.CategorySummary total = new CompanyOverviewVO.CategorySummary();
|
||||
total.setCategoryId(0L);
|
||||
total.setCategoryName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setGmv(totalGmv);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setOrderCount(totalOrders);
|
||||
total.setAverageOrderValue(avgOrderValue);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 计算平台汇总的合计行 */
|
||||
private CompanyOverviewVO.PlatformSummary computePlatformTotal(List<CompanyOverviewVO.PlatformSummary> platforms) {
|
||||
BigDecimal totalSalesAmount = BigDecimal.ZERO;
|
||||
int totalOrderCount = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrderCount = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefundAmount = BigDecimal.ZERO;
|
||||
BigDecimal totalPromotionFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalGmv = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.PlatformSummary p : platforms) {
|
||||
totalSalesAmount = totalSalesAmount.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalGmv = totalGmv.add(p.getGmv() != null ? p.getGmv() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(p.getGrossProfit() != null ? p.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalOrderCount += p.getOrderCount() != null ? p.getOrderCount() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(p.getTargetAmount() != null ? p.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrderCount += p.getTargetOrderCount() != null ? p.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(p.getProductCost() != null ? p.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(p.getShippingCost() != null ? p.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(p.getOtherCost() != null ? p.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefundAmount = totalRefundAmount.add(p.getRefundAmount() != null ? p.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromotionFee = totalPromotionFee.add(p.getTotalPromotionFee() != null ? p.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(p.getBrushFee() != null ? p.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal avgOrderValue = totalOrderCount > 0
|
||||
? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount)
|
||||
.subtract(totalPromotionFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrderCount > 0
|
||||
? new BigDecimal(totalOrderCount).divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalOrderCount > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.PlatformSummary total = new CompanyOverviewVO.PlatformSummary();
|
||||
total.setPlatformCode(null);
|
||||
total.setPlatformName("合计");
|
||||
total.setSalesAmount(totalSalesAmount);
|
||||
total.setGmv(totalGmv);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setOrderCount(totalOrderCount);
|
||||
total.setAverageOrderValue(avgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrderCount);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefundAmount);
|
||||
total.setTotalPromotionFee(totalPromotionFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate) {
|
||||
synchronized (this) {
|
||||
BigDecimal saved = this.taxRate;
|
||||
try {
|
||||
this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
|
||||
return buildWorkbenchTablesFromAggInternal(companyId, shops, orderRows, promotionRows, brushRows, startDate, endDate);
|
||||
} finally {
|
||||
this.taxRate = saved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** SQL 聚合行 → 四表(推广/刷单分摊规则与明细版一致) */
|
||||
private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal(
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate) {
|
||||
|
||||
Map<Long, AggMetrics> byShop = new HashMap<>();
|
||||
Map<Long, AggMetrics> byCategory = new HashMap<>();
|
||||
Map<Long, AggMetrics> byProduct = new HashMap<>();
|
||||
Map<Long, Map<Long, BigDecimal>> categorySalesByShop = new HashMap<>();
|
||||
Map<Long, Map<Long, BigDecimal>> productSalesByShop = new HashMap<>();
|
||||
Map<Long, Long> productCategoryMap = new HashMap<>();
|
||||
|
||||
for (OverviewAggRows.ShopProductRow row : orderRows) {
|
||||
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
long categoryKey = productId <= 0 ? -1L
|
||||
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
|
||||
if (productId > 0) {
|
||||
productCategoryMap.put(productId, categoryKey <= 0 ? null : categoryKey);
|
||||
}
|
||||
mergeAgg(byShop, shopId, row);
|
||||
mergeAgg(byCategory, categoryKey, row);
|
||||
mergeAgg(byProduct, productId, row);
|
||||
BigDecimal sales = nz(row.getSalesAmount());
|
||||
categorySalesByShop.computeIfAbsent(categoryKey, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
|
||||
productSalesByShop.computeIfAbsent(productId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
|
||||
}
|
||||
|
||||
Map<Long, BigDecimal> promoByShop = new HashMap<>();
|
||||
Map<Long, BigDecimal> directPromoByProduct = new HashMap<>();
|
||||
Map<Long, BigDecimal> directPromoByCategory = new HashMap<>();
|
||||
BigDecimal ratioPool = BigDecimal.ZERO;
|
||||
for (OverviewAggRows.PromotionRow fee : promotionRows) {
|
||||
BigDecimal amt = nz(fee.getFeeAmount());
|
||||
promoByShop.merge(fee.getShopId(), amt, BigDecimal::add);
|
||||
if (fee.getProductId() != null) {
|
||||
directPromoByProduct.merge(fee.getProductId(), amt, BigDecimal::add);
|
||||
} else if (fee.getCategoryId() != null) {
|
||||
directPromoByCategory.merge(fee.getCategoryId(), amt, BigDecimal::add);
|
||||
} else {
|
||||
ratioPool = ratioPool.add(amt);
|
||||
}
|
||||
}
|
||||
Map<Long, BigDecimal> brushByShop = new HashMap<>();
|
||||
for (OverviewAggRows.BrushRow b : brushRows) {
|
||||
brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add);
|
||||
}
|
||||
BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = loadTargetsByShop(companyId, startDate, endDate);
|
||||
|
||||
CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle();
|
||||
bundle.setShopTable(buildShopOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop));
|
||||
bundle.setPlatformTable(buildPlatformOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop));
|
||||
bundle.setCategoryTable(buildCategoryOverviewFromAgg(byCategory, categorySalesByShop, brushByShop,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
|
||||
bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
|
||||
return bundle;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.ShopOverview buildShopOverviewFromAgg(
|
||||
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
List<CompanyOverviewVO.ShopSummary> list = new ArrayList<>();
|
||||
for (ShopPO shop : shops) {
|
||||
AggMetrics m = byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY);
|
||||
list.add(toShopSummaryFromAgg(shop, m, promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
|
||||
brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
|
||||
targetsByShop.getOrDefault(shop.getId(), List.of())));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.ShopOverview o = new CompanyOverviewVO.ShopOverview();
|
||||
o.setShops(list);
|
||||
o.setTotal(computeShopTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformOverview buildPlatformOverviewFromAgg(
|
||||
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
Map<String, List<ShopPO>> byPlatform = shops.stream()
|
||||
.filter(s -> s.getPlatformCode() != null && !s.getPlatformCode().isBlank())
|
||||
.collect(Collectors.groupingBy(ShopPO::getPlatformCode));
|
||||
List<CompanyOverviewVO.PlatformSummary> list = new ArrayList<>();
|
||||
for (Map.Entry<String, List<ShopPO>> e : byPlatform.entrySet()) {
|
||||
list.add(rollupPlatformFromAgg(e.getKey(), PlatformCode.labelOf(e.getKey()),
|
||||
e.getValue(), byShop, promoByShop, brushByShop, targetsByShop));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.PlatformOverview o = new CompanyOverviewVO.PlatformOverview();
|
||||
o.setPlatforms(list);
|
||||
o.setTotal(computePlatformTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategoryOverview buildCategoryOverviewFromAgg(
|
||||
Map<Long, AggMetrics> byCategory, Map<Long, Map<Long, BigDecimal>> categorySalesByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
|
||||
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
|
||||
Map<Long, Long> productCategoryMap, Long companyId) {
|
||||
Map<Long, String> categoryNames = loadCategoryNameMap(companyId);
|
||||
Map<Long, BigDecimal> salesByCategory = byCategory.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().sales));
|
||||
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byCategory.entrySet()) {
|
||||
Long key = e.getKey();
|
||||
AggMetrics m = e.getValue();
|
||||
BigDecimal promo = resolveCategoryPromo(key, m.sales, salesByCategory, productCategoryMap,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
|
||||
BigDecimal brush = allocBrushShare(categorySalesByShop.get(key), brushByShop);
|
||||
list.add(toCategorySummaryFromAgg(key, categoryAggName(key, categoryNames), m, promo, brush));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
|
||||
o.setCategories(list);
|
||||
o.setTotal(computeCategoryTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategoryOverview buildProductOverviewFromAgg(
|
||||
Map<Long, AggMetrics> byProduct, Map<Long, Map<Long, BigDecimal>> productSalesByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
|
||||
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
|
||||
Map<Long, Long> productCategoryMap, Long companyId) {
|
||||
Map<Long, BigDecimal> salesByCategory = new HashMap<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
|
||||
if (e.getKey() > 0) {
|
||||
Long cid = productCategoryMap.get(e.getKey());
|
||||
if (cid != null && cid > 0) {
|
||||
salesByCategory.merge(cid, e.getValue().sales, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<Long, String> productNames = loadProductNameMap(byProduct.keySet());
|
||||
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
|
||||
Long pid = e.getKey();
|
||||
AggMetrics m = e.getValue();
|
||||
BigDecimal promo = resolveProductPromo(pid, m.sales, productCategoryMap, salesByCategory,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
|
||||
BigDecimal brush = allocBrushShare(productSalesByShop.get(pid), brushByShop);
|
||||
String name = pid <= 0 ? "未匹配商品" : productNames.getOrDefault(pid, "商品" + pid);
|
||||
list.add(toCategorySummaryFromAgg(pid, name, m, promo, brush));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
|
||||
o.setCategories(list);
|
||||
o.setTotal(computeCategoryTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformSummary rollupPlatformFromAgg(
|
||||
String platformCode, String platformName, List<ShopPO> platformShops,
|
||||
Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop, Map<Long, BigDecimal> brushByShop,
|
||||
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
AggMetrics merged = AggMetrics.EMPTY;
|
||||
BigDecimal promo = BigDecimal.ZERO;
|
||||
BigDecimal brush = BigDecimal.ZERO;
|
||||
BigDecimal targetAmt = BigDecimal.ZERO;
|
||||
int targetOrders = 0;
|
||||
for (ShopPO shop : platformShops) {
|
||||
merged = merged.merge(byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY));
|
||||
promo = promo.add(promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
|
||||
brush = brush.add(brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
|
||||
for (ShopMonthlyTargetPO t : targetsByShop.getOrDefault(shop.getId(), List.of())) {
|
||||
targetAmt = targetAmt.add(nz(t.getTargetAmount()));
|
||||
targetOrders += t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0;
|
||||
}
|
||||
}
|
||||
return toPlatformSummaryFromAgg(platformCode, platformName, merged, promo, brush, targetAmt, targetOrders);
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.ShopSummary toShopSummaryFromAgg(
|
||||
ShopPO shop, AggMetrics m, BigDecimal promo, BigDecimal brush,
|
||||
List<ShopMonthlyTargetPO> targets) {
|
||||
BigDecimal targetAmt = targets.stream().map(t -> nz(t.getTargetAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int targetOrders = targets.stream().mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0).sum();
|
||||
CompanyOverviewVO.ShopSummary s = new CompanyOverviewVO.ShopSummary();
|
||||
s.setShopId(shop.getId());
|
||||
s.setShopName(shop.getName());
|
||||
s.setPlatform(shop.getPlatformCode() != null ? PlatformCode.labelOf(shop.getPlatformCode()) : null);
|
||||
fillSummaryMetrics(s, m, promo, brush, targetAmt, targetOrders);
|
||||
return s;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformSummary toPlatformSummaryFromAgg(
|
||||
String platformCode, String name, AggMetrics m, BigDecimal promo, BigDecimal brush,
|
||||
BigDecimal targetAmt, int targetOrders) {
|
||||
CompanyOverviewVO.PlatformSummary s = new CompanyOverviewVO.PlatformSummary();
|
||||
s.setPlatformCode(platformCode != null && !platformCode.isBlank() ? platformCode : null);
|
||||
s.setPlatformName(name);
|
||||
fillPlatformLikeMetrics(s, m, promo, brush, targetAmt, targetOrders);
|
||||
return s;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategorySummary toCategorySummaryFromAgg(
|
||||
Long key, String name, AggMetrics m, BigDecimal promo, BigDecimal brush) {
|
||||
CompanyOverviewVO.CategorySummary s = new CompanyOverviewVO.CategorySummary();
|
||||
s.setCategoryId(key != null && key > 0 ? key : null);
|
||||
s.setCategoryName(name);
|
||||
fillCategoryLikeMetrics(s, m, promo, brush);
|
||||
return s;
|
||||
}
|
||||
|
||||
private void fillSummaryMetrics(CompanyOverviewVO.ShopSummary s, AggMetrics m, BigDecimal promo,
|
||||
BigDecimal brush, BigDecimal targetAmt, int targetOrders) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setGmv(m.gmv);
|
||||
s.setOrderCount(m.orderCount);
|
||||
s.setAverageOrderValue(aov(m.sales, m.orderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo, m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
|
||||
s.setTargetAmount(targetAmt);
|
||||
s.setTargetOrderCount(targetOrders);
|
||||
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
|
||||
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
/** 品类/商品/平台汇总行:填充 GMV、毛利与净利字段 */
|
||||
private void fillCategoryLikeMetrics(CompanyOverviewVO.CategorySummary s, AggMetrics m,
|
||||
BigDecimal promo, BigDecimal brush) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setGmv(m.gmv);
|
||||
s.setOrderCount(m.orderCount);
|
||||
s.setAverageOrderValue(aov(m.sales, m.orderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo, m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
|
||||
}
|
||||
|
||||
private void fillPlatformLikeMetrics(CompanyOverviewVO.PlatformSummary s, AggMetrics m,
|
||||
BigDecimal promo, BigDecimal brush,
|
||||
BigDecimal targetAmt, int targetOrders) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setGmv(m.gmv);
|
||||
s.setOrderCount(m.orderCount);
|
||||
s.setAverageOrderValue(aov(m.sales, m.orderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo.add(brush), m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnNetSales(m.sales, m.refund));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales.subtract(m.refund), promo));
|
||||
s.setTargetAmount(targetAmt);
|
||||
s.setTargetOrderCount(targetOrders);
|
||||
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
|
||||
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
private static void mergeAgg(Map<Long, AggMetrics> map, long key, OverviewAggRows.ShopProductRow row) {
|
||||
map.merge(key, AggMetrics.from(row), AggMetrics::merge);
|
||||
}
|
||||
|
||||
private static BigDecimal resolveCategoryPromo(Long categoryKey, BigDecimal sales,
|
||||
Map<Long, BigDecimal> salesByCategory, Map<Long, Long> productCategoryMap,
|
||||
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
|
||||
BigDecimal ratioPool, BigDecimal totalPool) {
|
||||
BigDecimal direct = BigDecimal.ZERO;
|
||||
for (Map.Entry<Long, Long> e : productCategoryMap.entrySet()) {
|
||||
if (matchesCategory(categoryKey, e.getValue())) {
|
||||
direct = direct.add(directByProduct.getOrDefault(e.getKey(), BigDecimal.ZERO));
|
||||
}
|
||||
}
|
||||
if (categoryKey != null && categoryKey > 0) {
|
||||
direct = direct.add(directByCategory.getOrDefault(categoryKey, BigDecimal.ZERO));
|
||||
}
|
||||
return addPoolShare(direct, sales, ratioPool, totalPool);
|
||||
}
|
||||
|
||||
private static BigDecimal resolveProductPromo(Long productId, BigDecimal sales,
|
||||
Map<Long, Long> productCategoryMap, Map<Long, BigDecimal> salesByCategory,
|
||||
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
|
||||
BigDecimal ratioPool, BigDecimal totalPool) {
|
||||
if (productId == null || productId <= 0) {
|
||||
return addPoolShare(BigDecimal.ZERO, sales, ratioPool, totalPool);
|
||||
}
|
||||
BigDecimal direct = directByProduct.getOrDefault(productId, BigDecimal.ZERO);
|
||||
Long cid = productCategoryMap.get(productId);
|
||||
if (cid != null && cid > 0) {
|
||||
BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO);
|
||||
if (catSales.compareTo(BigDecimal.ZERO) > 0) {
|
||||
direct = direct.add(directByCategory.getOrDefault(cid, BigDecimal.ZERO)
|
||||
.multiply(sales).divide(catSales, 4, RoundingMode.HALF_UP));
|
||||
}
|
||||
}
|
||||
return addPoolShare(direct, sales, ratioPool, totalPool);
|
||||
}
|
||||
|
||||
private static boolean matchesCategory(Long categoryKey, Long productCat) {
|
||||
if (categoryKey == -1L) {
|
||||
return productCat == null;
|
||||
}
|
||||
return Objects.equals(categoryKey, productCat);
|
||||
}
|
||||
|
||||
private static BigDecimal addPoolShare(BigDecimal base, BigDecimal sales, BigDecimal pool, BigDecimal total) {
|
||||
if (pool.compareTo(BigDecimal.ZERO) > 0 && total.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return base.add(pool.multiply(sales).divide(total, 4, RoundingMode.HALF_UP));
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
private static BigDecimal allocBrushShare(Map<Long, BigDecimal> salesByShop, Map<Long, BigDecimal> brushByShop) {
|
||||
if (salesByShop == null || salesByShop.isEmpty()) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal total = salesByShop.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
if (total.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal brush = BigDecimal.ZERO;
|
||||
for (Map.Entry<Long, BigDecimal> e : salesByShop.entrySet()) {
|
||||
brush = brush.add(brushByShop.getOrDefault(e.getKey(), BigDecimal.ZERO)
|
||||
.multiply(e.getValue()).divide(total, 6, RoundingMode.HALF_UP));
|
||||
}
|
||||
return brush;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCategoryNameMap(Long companyId) {
|
||||
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().eq(CategoryPO::getCompanyId, companyId))
|
||||
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private Map<Long, String> loadProductNameMap(java.util.Set<Long> productKeys) {
|
||||
List<Long> ids = productKeys.stream().filter(id -> id != null && id > 0).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, ids))
|
||||
.stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private Map<Long, List<ShopMonthlyTargetPO>> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) {
|
||||
List<LocalDate> months = new ArrayList<>();
|
||||
LocalDate cur = start.withDayOfMonth(1);
|
||||
LocalDate endMonth = end.withDayOfMonth(1);
|
||||
while (!cur.isAfter(endMonth)) {
|
||||
months.add(cur);
|
||||
cur = cur.plusMonths(1);
|
||||
}
|
||||
if (months.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
LambdaQueryWrapper<ShopMonthlyTargetPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ShopMonthlyTargetPO::getCompanyId, companyId).in(ShopMonthlyTargetPO::getTargetMonth, months);
|
||||
return shopMonthlyTargetMapper.selectList(w).stream()
|
||||
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
|
||||
}
|
||||
|
||||
private static String categoryAggName(Long key, Map<Long, String> names) {
|
||||
if (key == null || key == -1L) {
|
||||
return "其他品类";
|
||||
}
|
||||
if (key == 0L) {
|
||||
return "未分类";
|
||||
}
|
||||
return names.getOrDefault(key, "类目" + key);
|
||||
}
|
||||
|
||||
private static BigDecimal aov(BigDecimal sales, int count) {
|
||||
return count > 0 ? sales.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal safeDivide(BigDecimal a, BigDecimal b) {
|
||||
return b.compareTo(BigDecimal.ZERO) > 0 ? a.divide(b, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal achievementRate(BigDecimal actual, BigDecimal target) {
|
||||
if (target.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return actual.divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
|
||||
}
|
||||
return actual.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static final class AggMetrics {
|
||||
static final AggMetrics EMPTY = new AggMetrics();
|
||||
BigDecimal sales = BigDecimal.ZERO;
|
||||
/** 全订单状态 GMV(商家实收合计) */
|
||||
BigDecimal gmv = BigDecimal.ZERO;
|
||||
int orderCount;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
BigDecimal productCost = BigDecimal.ZERO;
|
||||
BigDecimal freightCost = BigDecimal.ZERO;
|
||||
BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
/** 订单成本合计(商品+运费+其他,不含推广/刷单) */
|
||||
BigDecimal orderCost() {
|
||||
return productCost.add(freightCost).add(otherCost);
|
||||
}
|
||||
|
||||
/** 订单维度毛利:未扣推广/刷单/税 */
|
||||
BigDecimal grossProfit() {
|
||||
return sales.subtract(orderCost()).subtract(refund);
|
||||
}
|
||||
|
||||
static AggMetrics from(OverviewAggRows.ShopProductRow row) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = nz(row.getSalesAmount());
|
||||
a.gmv = nz(row.getGmvAllStatus());
|
||||
a.orderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
|
||||
a.refund = nz(row.getRefundAmount());
|
||||
a.productCost = nz(row.getProductCost());
|
||||
a.freightCost = nz(row.getFreightCost());
|
||||
a.otherCost = nz(row.getOtherCost());
|
||||
return a;
|
||||
}
|
||||
|
||||
AggMetrics merge(AggMetrics o) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = sales.add(o.sales);
|
||||
a.gmv = gmv.add(o.gmv);
|
||||
a.orderCount = orderCount + o.orderCount;
|
||||
a.refund = refund.add(o.refund);
|
||||
a.productCost = productCost.add(o.productCost);
|
||||
a.freightCost = freightCost.add(o.freightCost);
|
||||
a.otherCost = otherCost.add(o.otherCost);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
-162
@@ -1,18 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.ExportService;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
@@ -24,7 +20,7 @@ import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 概览导出服务实现类
|
||||
* 工作台等多维表导出(按已汇总好的表写入 Excel)。
|
||||
*/
|
||||
@Service
|
||||
public class ExportServiceImpl implements ExportService {
|
||||
@@ -33,38 +29,20 @@ public class ExportServiceImpl implements ExportService {
|
||||
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
private final ExportStatusRangeHelper exportStatusRangeHelper;
|
||||
private final CategoryExportExcelService categoryExportExcelService;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
|
||||
public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper,
|
||||
CategoryExportExcelService categoryExportExcelService,
|
||||
CompanyOverviewService companyOverviewService) {
|
||||
public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper) {
|
||||
this.exportStatusRangeHelper = exportStatusRangeHelper;
|
||||
this.categoryExportExcelService = categoryExportExcelService;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCompanyOverview(CompanyExportDTO dto) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO();
|
||||
query.setDateRange(dto.getDateRange());
|
||||
query.setTaxRate(taxRate);
|
||||
CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query);
|
||||
return buildShopOverviewExcelBytes(dto, vo.getShopSummary(), vo, "全店 - 按店铺汇总", true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle) {
|
||||
return buildShopOverviewExcelBytes(dto, shopOverview, null, summaryTitle, false);
|
||||
return buildShopOverviewExcelBytes(dto, shopOverview, summaryTitle);
|
||||
}
|
||||
|
||||
private byte[] buildShopOverviewExcelBytes(
|
||||
CompanyExportDTO dto,
|
||||
CompanyOverviewVO.ShopOverview shopOv,
|
||||
CompanyOverviewVO voForTrend,
|
||||
String summarySheetTitle,
|
||||
boolean appendTrendIfPossible) {
|
||||
String summarySheetTitle) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
|
||||
List<CompanyOverviewVO.ShopSummary> shops = (shopOv != null && shopOv.getShops() != null)
|
||||
@@ -91,14 +69,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
Sheet summarySheet = workbook.createSheet("汇总");
|
||||
createCompanyDetailSheet(
|
||||
summarySheet, summarySheetTitle, dateRangeLabel, shopRows, taxRate, totalRowMap);
|
||||
if (appendTrendIfPossible
|
||||
&& voForTrend != null
|
||||
&& voForTrend.getSalesAmountTrend() != null
|
||||
&& voForTrend.getSalesAmountTrend().getDailyDataList() != null
|
||||
&& !voForTrend.getSalesAmountTrend().getDailyDataList().isEmpty()) {
|
||||
Sheet trendSheet = workbook.createSheet("销售趋势");
|
||||
writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, voForTrend);
|
||||
}
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
@@ -108,20 +78,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCategoryOverview(CategoryExportDTO dto) {
|
||||
if (dto.getShopId() != null) {
|
||||
return categoryExportExcelService.exportCategoryOverview(dto);
|
||||
}
|
||||
CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO();
|
||||
query.setDateRange(dto.getDateRange());
|
||||
query.setTaxRate(dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE);
|
||||
CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query);
|
||||
return categoryExportExcelService.exportStoreCategoryFromOverview(dto, vo);
|
||||
}
|
||||
|
||||
// ==================== Sheet 构建方法 ====================
|
||||
|
||||
private void createCompanyDetailSheet(
|
||||
Sheet sheet,
|
||||
String summaryTitle,
|
||||
@@ -282,7 +238,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 与全店概览一致:税额 = max(0, 销售额 − 退款) × 税率,两位小数。 */
|
||||
private static BigDecimal salesTaxOnNetForExport(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) {
|
||||
BigDecimal s = sales != null ? sales : BigDecimal.ZERO;
|
||||
BigDecimal rfd = refund != null ? refund : BigDecimal.ZERO;
|
||||
@@ -467,97 +422,32 @@ public class ExportServiceImpl implements ExportService {
|
||||
return total;
|
||||
}
|
||||
|
||||
private void writeCompanyOverviewTrendSheet(
|
||||
Sheet sheet, String contextTitle, String dateRangeLabel, CompanyOverviewVO vo) {
|
||||
Workbook wb = sheet.getWorkbook();
|
||||
CellStyle headerStyle = createHeaderStyle(wb);
|
||||
CellStyle dataStyle = createDataStyle(wb);
|
||||
|
||||
Row titleRow = sheet.createRow(0);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellValue(contextTitle + " - 销售趋势 | " + dateRangeLabel);
|
||||
titleCell.setCellStyle(createTitleStyle(wb));
|
||||
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
|
||||
|
||||
String[] headers = {"日期", "销售额", "单量"};
|
||||
Row headerRow = sheet.createRow(1);
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
}
|
||||
|
||||
List<CompanyOverviewVO.TrendDataItem> dailySales = vo.getSalesAmountTrend().getDailyDataList();
|
||||
List<CompanyOverviewVO.TrendDataItem> dailyOrders = vo.getOrderCountTrend() != null
|
||||
? vo.getOrderCountTrend().getDailyDataList()
|
||||
: null;
|
||||
|
||||
Map<LocalDate, BigDecimal> salesMap = dailySales.stream()
|
||||
.collect(Collectors.toMap(
|
||||
CompanyOverviewVO.TrendDataItem::getDate,
|
||||
CompanyOverviewVO.TrendDataItem::getValue,
|
||||
(a, b) -> a));
|
||||
Map<LocalDate, BigDecimal> ordersMap = dailyOrders != null
|
||||
? dailyOrders.stream()
|
||||
.collect(Collectors.toMap(
|
||||
CompanyOverviewVO.TrendDataItem::getDate,
|
||||
CompanyOverviewVO.TrendDataItem::getValue,
|
||||
(a, b) -> a))
|
||||
: Collections.emptyMap();
|
||||
|
||||
LocalDate startDate = dailySales.stream()
|
||||
.map(CompanyOverviewVO.TrendDataItem::getDate)
|
||||
.min(LocalDate::compareTo)
|
||||
.orElse(null);
|
||||
LocalDate endDate = dailySales.stream()
|
||||
.map(CompanyOverviewVO.TrendDataItem::getDate)
|
||||
.max(LocalDate::compareTo)
|
||||
.orElse(null);
|
||||
|
||||
int rowIdx = 2;
|
||||
if (startDate != null && endDate != null) {
|
||||
LocalDate current = startDate;
|
||||
while (!current.isAfter(endDate)) {
|
||||
Row row = sheet.createRow(rowIdx++);
|
||||
BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
setCell(row, 0, current.format(DATE_FMT), dataStyle);
|
||||
setCell(row, 1, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
current = current.plusDays(1);
|
||||
}
|
||||
}
|
||||
|
||||
sheet.setColumnWidth(0, 3200);
|
||||
sheet.setColumnWidth(1, 3200);
|
||||
sheet.setColumnWidth(2, 3200);
|
||||
}
|
||||
|
||||
private double objToDouble(Object val) {
|
||||
if (val == null) return 0.0;
|
||||
if (val instanceof BigDecimal) return ((BigDecimal) val).setScale(2, RoundingMode.HALF_UP).doubleValue();
|
||||
if (val instanceof Integer) return ((Integer) val).doubleValue();
|
||||
return 0.0;
|
||||
if (val == null) {
|
||||
return 0;
|
||||
}
|
||||
if (val instanceof Number) {
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private double objToPct(Object val) {
|
||||
if (val == null) return 0.0;
|
||||
if (val instanceof BigDecimal) return ((BigDecimal) val).setScale(2, RoundingMode.HALF_UP).doubleValue();
|
||||
if (val instanceof Double) return BigDecimal.valueOf((Double) val).setScale(2, RoundingMode.HALF_UP).doubleValue();
|
||||
if (val instanceof Integer) return ((Integer) val).doubleValue();
|
||||
return 0.0;
|
||||
if (val == null) {
|
||||
return 0;
|
||||
}
|
||||
if (val instanceof Number) {
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ==================== Excel 样式工具 ====================
|
||||
|
||||
private CellStyle createTitleStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
font.setFontHeightInPoints((short) 14);
|
||||
style.setFont(font);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
|
||||
@@ -572,8 +462,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
|
||||
@@ -583,10 +471,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
DataFormat format = workbook.createDataFormat();
|
||||
style.setDataFormat(format.getFormat("#,##0.00"));
|
||||
return style;
|
||||
}
|
||||
|
||||
@@ -610,27 +494,15 @@ public class ExportServiceImpl implements ExportService {
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportPlatformOverview(PlatformExportDTO dto) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
CompanyOverviewQueryDTO query = new CompanyOverviewQueryDTO();
|
||||
query.setDateRange(dto.getDateRange());
|
||||
query.setTaxRate(taxRate);
|
||||
CompanyOverviewVO vo = companyOverviewService.getCompanyOverview(query);
|
||||
return buildPlatformOverviewExcelBytes(dto, vo.getPlatformSummary(), vo, "全店 - 按平台汇总", true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle) {
|
||||
return buildPlatformOverviewExcelBytes(dto, platformOverview, null, summaryTitle, false);
|
||||
return buildPlatformOverviewExcelBytes(dto, platformOverview, summaryTitle);
|
||||
}
|
||||
|
||||
private byte[] buildPlatformOverviewExcelBytes(
|
||||
PlatformExportDTO dto,
|
||||
CompanyOverviewVO.PlatformOverview platformOv,
|
||||
CompanyOverviewVO voForTrend,
|
||||
String summarySheetTitle,
|
||||
boolean appendTrendIfPossible) {
|
||||
String summarySheetTitle) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
|
||||
List<CompanyOverviewVO.PlatformSummary> platforms = (platformOv != null && platformOv.getPlatforms() != null)
|
||||
@@ -661,14 +533,6 @@ public class ExportServiceImpl implements ExportService {
|
||||
Sheet summarySheet = workbook.createSheet("汇总");
|
||||
createPlatformSummarySheet(
|
||||
summarySheet, summarySheetTitle, dateRangeLabel, platformRows, taxRate, totalRowMap);
|
||||
if (appendTrendIfPossible
|
||||
&& voForTrend != null
|
||||
&& voForTrend.getSalesAmountTrend() != null
|
||||
&& voForTrend.getSalesAmountTrend().getDailyDataList() != null
|
||||
&& !voForTrend.getSalesAmountTrend().getDailyDataList().isEmpty()) {
|
||||
Sheet trendSheet = workbook.createSheet("销售趋势");
|
||||
writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, voForTrend);
|
||||
}
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
@@ -677,4 +541,4 @@ public class ExportServiceImpl implements ExportService {
|
||||
throw new BusinessException("导出平台Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.util;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.util;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.productoverview.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.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
|
||||
|
||||
@Tag(name = "BI-商品概览", description = "商品概览(Mongo 订单/SKU 日汇聚)")
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/product")
|
||||
public class BiProductOverviewController {
|
||||
|
||||
private final BiProductOverviewService biProductOverviewService;
|
||||
|
||||
public BiProductOverviewController(BiProductOverviewService biProductOverviewService) {
|
||||
this.biProductOverviewService = biProductOverviewService;
|
||||
}
|
||||
|
||||
@Operation(summary = "商品概览", description = "KPI、趋势、规格汇总;订单/SKU 读 Mongo,推广/目标读 MySQL")
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "ecom:product:read", description = "查询商品概览", allowSuper = true)
|
||||
public ApiResponse<ProductOverviewVO> overview(@Valid @RequestBody ProductOverviewQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取商品总览成功", biProductOverviewService.getProductOverview(queryDTO));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.productoverview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
|
||||
|
||||
/**
|
||||
* BI 商品概览:订单/SKU 读 Mongo 日汇聚,推广/目标读 MySQL。
|
||||
*/
|
||||
public interface BiProductOverviewService {
|
||||
|
||||
ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO);
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.productoverview.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.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品概览:Mongo product/sku 日汇聚 + MySQL 推广/目标。
|
||||
* 推广分摊复用工作台四表(按店全量商品行作分母),不再扫订单明细。
|
||||
*/
|
||||
@Service
|
||||
public class BiProductOverviewServiceImpl implements BiProductOverviewService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ProductService productService;
|
||||
private final ShopService shopService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
private final BiWorkbenchFeeLoader feeLoader;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
|
||||
public BiProductOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
ProductService productService,
|
||||
ShopService shopService,
|
||||
BiOrderStatQueryService orderStatQueryService,
|
||||
BiWorkbenchFeeLoader feeLoader,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ProductSkuMapper productSkuMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.productService = productService;
|
||||
this.shopService = shopService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.feeLoader = feeLoader;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ProductPO product = productService.getById(queryDTO.getProductId());
|
||||
if (product == null || !Objects.equals(product.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) {
|
||||
throw new BusinessException("开始日期不能晚于结束日期");
|
||||
}
|
||||
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
LocalDate start = queryDTO.getStartDate();
|
||||
LocalDate end = queryDTO.getEndDate();
|
||||
|
||||
Long filterShopId = queryDTO.getShopId();
|
||||
if (filterShopId != null) {
|
||||
ShopPO shop = shopService.getById(filterShopId);
|
||||
if (shop == null || !Objects.equals(shop.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 先拉本商品日文档,确定涉及店铺
|
||||
List<Long> shopIdFilter = filterShopId != null ? List.of(filterShopId) : null;
|
||||
List<BiOrderStatDailyProductDoc> thisProductDocs =
|
||||
orderStatQueryService.listProductDocs(companyId, shopIdFilter, product.getId(), start, end);
|
||||
|
||||
List<Long> shopIds;
|
||||
if (filterShopId != null) {
|
||||
shopIds = List.of(filterShopId);
|
||||
} else {
|
||||
shopIds = thisProductDocs.stream()
|
||||
.map(BiOrderStatDailyProductDoc::getShopId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<ShopPO> shops = shopIds.isEmpty() ? List.of()
|
||||
: shopService.listByIds(shopIds).stream()
|
||||
.filter(s -> s != null && Objects.equals(s.getCompanyId(), companyId))
|
||||
.collect(Collectors.toList());
|
||||
Map<Long, String> platformByShopId = shops.stream()
|
||||
.collect(Collectors.toMap(ShopPO::getId,
|
||||
s -> s.getPlatformCode() != null ? s.getPlatformCode() : "",
|
||||
(a, b) -> a));
|
||||
|
||||
// 店内全量商品行:推广分摊分母(替代 allShopOrdersForPromo)
|
||||
List<BiOrderStatDailyProductDoc> allProductDocs = shopIds.isEmpty()
|
||||
? List.of()
|
||||
: orderStatQueryService.listProductDocs(companyId, shopIds, start, end);
|
||||
BiWorkbenchFeeLoader.FeeBundle fees = shopIds.isEmpty()
|
||||
? new BiWorkbenchFeeLoader.FeeBundle(List.of(), List.of())
|
||||
: feeLoader.load(companyId, shopIds, start, end);
|
||||
|
||||
List<OverviewAggRows.ShopProductRow> orderRows =
|
||||
orderStatQueryService.toShopProductRows(allProductDocs, platformByShopId);
|
||||
CompanyOverviewVO.WorkbenchTableBundle tables = shops.isEmpty()
|
||||
? emptyTables()
|
||||
: companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, orderRows,
|
||||
fees.promotionRows(), fees.brushRows(), start, end);
|
||||
|
||||
CompanyOverviewVO.CategorySummary productRow = findProductRow(tables.getProductTable(), product.getId());
|
||||
|
||||
BigDecimal sales = productRow != null ? nz(productRow.getSalesAmount()) : sumSales(thisProductDocs);
|
||||
int orderCount = productRow != null && productRow.getOrderCount() != null
|
||||
? productRow.getOrderCount()
|
||||
: sumOrders(thisProductDocs);
|
||||
BigDecimal refund = productRow != null ? nz(productRow.getRefundAmount()) : sumRefund(thisProductDocs);
|
||||
BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO;
|
||||
BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost())
|
||||
: sumCost(thisProductDocs);
|
||||
BigDecimal tax = salesTax(sales, refund, taxRate);
|
||||
BigDecimal net = sales.subtract(orderCost).subtract(refund).subtract(promo).subtract(tax);
|
||||
|
||||
ProductOverviewVO vo = new ProductOverviewVO();
|
||||
vo.setProductId(product.getId());
|
||||
vo.setProductName(product.getName());
|
||||
vo.setTotalSalesAmount(sales.setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setTotalOrderCount(orderCount);
|
||||
vo.setAverageFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0
|
||||
? promo.divide(sales, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
vo.setTotalTaxAmount(tax);
|
||||
vo.setTotalNetProfitAfterTax(net.setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setTotalROI(roi(sales.subtract(refund), promo));
|
||||
vo.setMonthOverMonthGrowth(calcPrevPeriodGrowth(companyId, product.getId(), shopIdFilter,
|
||||
start, end, sales));
|
||||
|
||||
fillTargets(vo, companyId, shopIds, start, end, sales, orderCount);
|
||||
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> daily =
|
||||
orderStatQueryService.toDailyRowsFromProductDocs(thisProductDocs).stream()
|
||||
.filter(d -> d.getStatDate() != null)
|
||||
.collect(Collectors.toMap(OverviewAggRows.DailyRow::getStatDate, d -> d, (a, b) -> a));
|
||||
vo.setSalesAmountTrend(buildTrend(start, end, daily, true));
|
||||
vo.setOrderCountTrend(buildTrend(start, end, daily, false));
|
||||
|
||||
List<BiOrderStatDailySkuDoc> skuDocs =
|
||||
orderStatQueryService.listSkuDocs(companyId, product.getId(), shopIdFilter, start, end);
|
||||
List<BiOrderStatQueryService.SkuPeriodMetrics> skuMetrics =
|
||||
orderStatQueryService.sumSkuDocsBySku(skuDocs);
|
||||
vo.setSpecSummaries(buildSpecSummary(skuMetrics, taxRate, promo));
|
||||
vo.setSpecSalesTop10(buildSpecTop10(vo.getSpecSummaries()));
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
private BigDecimal calcPrevPeriodGrowth(Long companyId, Long productId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end, BigDecimal curSales) {
|
||||
long dayCount = ChronoUnit.DAYS.between(start, end) + 1;
|
||||
LocalDate prevStart = start.minusDays(dayCount);
|
||||
LocalDate prevEnd = start.minusDays(1);
|
||||
List<BiOrderStatDailyProductDoc> prevDocs =
|
||||
orderStatQueryService.listProductDocs(companyId, shopIds, productId, prevStart, prevEnd);
|
||||
BigDecimal last = sumSales(prevDocs);
|
||||
if (last.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return curSales.subtract(last)
|
||||
.divide(last, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
return curSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private void fillTargets(ProductOverviewVO vo, Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end, BigDecimal sales, int orderCount) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
LocalDate first = start.withDayOfMonth(1);
|
||||
LocalDate last = end.withDayOfMonth(end.lengthOfMonth());
|
||||
List<ShopMonthlyTargetPO> targets = shopMonthlyTargetMapper.selectList(
|
||||
new LambdaQueryWrapper<ShopMonthlyTargetPO>()
|
||||
.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
|
||||
.in(ShopMonthlyTargetPO::getShopId, shopIds)
|
||||
.ge(ShopMonthlyTargetPO::getTargetMonth, first)
|
||||
.le(ShopMonthlyTargetPO::getTargetMonth, last));
|
||||
BigDecimal targetAmt = targets.stream()
|
||||
.map(ShopMonthlyTargetPO::getTargetAmount)
|
||||
.filter(Objects::nonNull)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int targetOrders = targets.stream()
|
||||
.map(ShopMonthlyTargetPO::getTargetOrderCount)
|
||||
.filter(Objects::nonNull)
|
||||
.mapToInt(Integer::intValue)
|
||||
.sum();
|
||||
if (targetAmt.compareTo(BigDecimal.ZERO) > 0) {
|
||||
vo.setSalesAmountAchievementRate(sales.divide(targetAmt, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
if (targetOrders > 0) {
|
||||
vo.setOrderCountAchievementRate(BigDecimal.valueOf(orderCount)
|
||||
.divide(BigDecimal.valueOf(targetOrders), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
}
|
||||
|
||||
private ProductOverviewVO.SpecSummary buildSpecSummary(
|
||||
List<BiOrderStatQueryService.SkuPeriodMetrics> metrics,
|
||||
BigDecimal taxRate,
|
||||
BigDecimal totalPromo) {
|
||||
BigDecimal salesPool = metrics.stream()
|
||||
.map(BiOrderStatQueryService.SkuPeriodMetrics::salesAmount)
|
||||
.map(BiProductOverviewServiceImpl::nz)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
Set<Long> skuIds = metrics.stream()
|
||||
.map(BiOrderStatQueryService.SkuPeriodMetrics::productSkuId)
|
||||
.filter(id -> id > 0)
|
||||
.collect(Collectors.toCollection(HashSet::new));
|
||||
Map<Long, ProductSkuPO> skuMap = new HashMap<>();
|
||||
if (!skuIds.isEmpty()) {
|
||||
for (ProductSkuPO sku : productSkuMapper.selectBatchIds(skuIds)) {
|
||||
if (sku != null && sku.getId() != null) {
|
||||
skuMap.put(sku.getId(), sku);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<ProductOverviewVO.SpecSummaryItem> list = new ArrayList<>();
|
||||
for (BiOrderStatQueryService.SkuPeriodMetrics m : metrics) {
|
||||
BigDecimal sales = nz(m.salesAmount());
|
||||
BigDecimal sharePromo = salesPool.compareTo(BigDecimal.ZERO) > 0
|
||||
? nz(totalPromo).multiply(sales).divide(salesPool, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal refund = nz(m.refundAmount());
|
||||
BigDecimal cost = m.orderCost();
|
||||
BigDecimal tax = salesTax(sales, refund, taxRate);
|
||||
BigDecimal pbt = sales.subtract(cost).subtract(refund).subtract(sharePromo);
|
||||
BigDecimal pat = pbt.subtract(tax);
|
||||
|
||||
ProductSkuPO sku = m.productSkuId() > 0 ? skuMap.get(m.productSkuId()) : null;
|
||||
ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem();
|
||||
item.setSkuId(m.productSkuId() > 0 ? m.productSkuId() : null);
|
||||
item.setSkuName(sku != null ? sku.getName()
|
||||
: (m.productSkuId() > 0 ? "规格" + m.productSkuId() : "未绑定规格"));
|
||||
item.setSkuCode(sku != null ? sku.getSkuCode() : null);
|
||||
item.setSalesAmount(sales.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setOrderCount(m.salesOrderCount());
|
||||
item.setQuantity(m.salesQuantitySum());
|
||||
item.setAverageOrderValue(m.salesOrderCount() > 0
|
||||
? sales.divide(BigDecimal.valueOf(m.salesOrderCount()), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
item.setProductCost(nz(m.productCost()).setScale(2, RoundingMode.HALF_UP));
|
||||
item.setShippingCost(nz(m.freightCost()).setScale(2, RoundingMode.HALF_UP));
|
||||
item.setOtherCost(nz(m.otherCost()).setScale(2, RoundingMode.HALF_UP));
|
||||
item.setOrderCost(cost.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setRefundAmount(refund.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setPromotionFee(sharePromo.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0
|
||||
? sharePromo.divide(sales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO);
|
||||
item.setProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setSalesTaxAmount(tax);
|
||||
item.setRoi(roi(sales.subtract(refund), sharePromo));
|
||||
item.setProfitAfterTax(pat.setScale(2, RoundingMode.HALF_UP));
|
||||
list.add(item);
|
||||
}
|
||||
list.sort(Comparator.comparing(ProductOverviewVO.SpecSummaryItem::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
|
||||
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
|
||||
total.setSalesAmount(list.stream().map(i -> nz(i.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOrderCount(list.stream().mapToInt(i -> i.getOrderCount() != null ? i.getOrderCount() : 0).sum());
|
||||
total.setQuantity(list.stream().mapToInt(i -> i.getQuantity() != null ? i.getQuantity() : 0).sum());
|
||||
total.setProductCost(list.stream().map(i -> nz(i.getProductCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setShippingCost(list.stream().map(i -> nz(i.getShippingCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOtherCost(list.stream().map(i -> nz(i.getOtherCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOrderCost(list.stream().map(i -> nz(i.getOrderCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setRefundAmount(list.stream().map(i -> nz(i.getRefundAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setPromotionFee(list.stream().map(i -> nz(i.getPromotionFee())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setFeeRatio(total.getSalesAmount().compareTo(BigDecimal.ZERO) > 0
|
||||
? total.getPromotionFee().divide(total.getSalesAmount(), 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
total.setProfitBeforeTax(list.stream().map(i -> nz(i.getProfitBeforeTax())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setSalesTaxAmount(list.stream().map(i -> nz(i.getSalesTaxAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setRoi(roi(total.getSalesAmount().subtract(total.getRefundAmount()), total.getPromotionFee()));
|
||||
total.setProfitAfterTax(list.stream().map(i -> nz(i.getProfitAfterTax())).reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
|
||||
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
|
||||
summary.setList(list);
|
||||
summary.setTotal(total);
|
||||
return summary;
|
||||
}
|
||||
|
||||
private static List<ProductOverviewVO.SpecSalesRankItem> buildSpecTop10(
|
||||
ProductOverviewVO.SpecSummary summary) {
|
||||
if (summary == null || summary.getList() == null) {
|
||||
return List.of();
|
||||
}
|
||||
return summary.getList().stream()
|
||||
.sorted(Comparator.comparing(
|
||||
(ProductOverviewVO.SpecSummaryItem i) ->
|
||||
i.getOrderCount() != null ? i.getOrderCount() : 0,
|
||||
Comparator.reverseOrder()))
|
||||
.limit(10)
|
||||
.map(i -> {
|
||||
ProductOverviewVO.SpecSalesRankItem r = new ProductOverviewVO.SpecSalesRankItem();
|
||||
r.setSkuId(i.getSkuId());
|
||||
r.setSkuName(i.getSkuName());
|
||||
r.setSkuCode(i.getSkuCode());
|
||||
r.setOrderCount(i.getOrderCount());
|
||||
r.setSalesAmount(i.getSalesAmount());
|
||||
return r;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static ProductOverviewVO.TrendData buildTrend(
|
||||
LocalDate start, LocalDate end,
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> daily,
|
||||
boolean sales) {
|
||||
List<ProductOverviewVO.TrendDataItem> items = new ArrayList<>();
|
||||
BigDecimal total = BigDecimal.ZERO;
|
||||
for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
|
||||
OverviewAggRows.DailyRow row = daily.get(d);
|
||||
BigDecimal value = sales
|
||||
? (row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO)
|
||||
: BigDecimal.valueOf(row != null && row.getOrderCount() != null ? row.getOrderCount() : 0L);
|
||||
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
|
||||
item.setDate(d);
|
||||
item.setValue(value);
|
||||
items.add(item);
|
||||
total = total.add(value);
|
||||
}
|
||||
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
|
||||
trend.setTotal(total);
|
||||
trend.setDailyDataList(items);
|
||||
return trend;
|
||||
}
|
||||
|
||||
private static CompanyOverviewVO.CategorySummary findProductRow(
|
||||
CompanyOverviewVO.CategoryOverview table, Long productId) {
|
||||
if (table == null || table.getCategories() == null || productId == null) {
|
||||
return null;
|
||||
}
|
||||
return table.getCategories().stream()
|
||||
.filter(c -> Objects.equals(c.getCategoryId(), productId))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static CompanyOverviewVO.WorkbenchTableBundle emptyTables() {
|
||||
CompanyOverviewVO.WorkbenchTableBundle b = new CompanyOverviewVO.WorkbenchTableBundle();
|
||||
CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview();
|
||||
empty.setCategories(List.of());
|
||||
b.setProductTable(empty);
|
||||
b.setCategoryTable(empty);
|
||||
return b;
|
||||
}
|
||||
|
||||
private static BigDecimal sumSales(List<BiOrderStatDailyProductDoc> docs) {
|
||||
return docs.stream().map(d -> nz(d.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
|
||||
private static BigDecimal sumRefund(List<BiOrderStatDailyProductDoc> docs) {
|
||||
return docs.stream().map(d -> nz(d.getRefundAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
|
||||
private static BigDecimal sumCost(List<BiOrderStatDailyProductDoc> docs) {
|
||||
return docs.stream()
|
||||
.map(d -> nz(d.getProductCost()).add(nz(d.getFreightCost())).add(nz(d.getOtherCost())))
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
|
||||
private static int sumOrders(List<BiOrderStatDailyProductDoc> docs) {
|
||||
return docs.stream().mapToInt(d -> d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0).sum();
|
||||
}
|
||||
|
||||
private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) {
|
||||
BigDecimal base = nz(sales).subtract(nz(refund));
|
||||
if (base.compareTo(BigDecimal.ZERO) < 0) {
|
||||
base = BigDecimal.ZERO;
|
||||
}
|
||||
return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) {
|
||||
if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
return nz(netSales).divide(promo, 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.shop.controller;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -11,25 +11,25 @@ import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.util.ExportFilenameUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
|
||||
/**
|
||||
* 店铺侧 Excel 导出:{@code /ec/shop/export/summary-by-product}、{@code /ec/shop/export/summary-by-category}
|
||||
* 店铺 Excel 导出:{@code /bi/shop/export/summary-by-product}、{@code /bi/shop/export/summary-by-category}
|
||||
*/
|
||||
@Tag(name = "电商-店铺导出", description = "店铺数据按商品/按品类汇总导出")
|
||||
@Tag(name = "BI-店铺导出", description = "店铺概览按商品/按品类汇总导出(Mongo 同源)")
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/shop/export")
|
||||
public class ShopExportController {
|
||||
@RequestMapping("/api/bi/shop/export")
|
||||
public class BiShopExportController {
|
||||
|
||||
private final ShopExportService shopExportService;
|
||||
private final BiShopExportService shopExportService;
|
||||
private final ShopService shopService;
|
||||
|
||||
public ShopExportController(ShopExportService shopExportService, ShopService shopService) {
|
||||
public BiShopExportController(BiShopExportService shopExportService, ShopService shopService) {
|
||||
this.shopExportService = shopExportService;
|
||||
this.shopService = shopService;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.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.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
|
||||
@Tag(name = "BI-店铺概览", description = "单店概览(Mongo 订单日汇聚)")
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/shop")
|
||||
public class BiShopOverviewController {
|
||||
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
|
||||
public BiShopOverviewController(BiShopOverviewService biShopOverviewService) {
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
}
|
||||
|
||||
@Operation(summary = "店铺概览", description = "KPI、趋势、商品/品类汇总;订单读 Mongo,推广/刷单/目标读 MySQL")
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "ecom:shop:read", description = "查询店铺概览", allowSuper = true)
|
||||
public ApiResponse<ShopOverviewStatisticsVO> overview(@Valid @RequestBody ShopOverviewQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取店铺概览成功", biShopOverviewService.getShopOverview(queryDTO));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
|
||||
/**
|
||||
* BI 店铺概览 Excel 导出(按商品 / 按品类)。
|
||||
*/
|
||||
public interface BiShopExportService {
|
||||
|
||||
byte[] exportShopSummaryByProduct(ShopExportDTO dto);
|
||||
|
||||
byte[] exportShopSummaryByCategory(CategoryExportDTO dto);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
|
||||
/**
|
||||
* BI 单店概览:订单读 Mongo 日汇聚,推广/刷单/目标读 MySQL。
|
||||
*/
|
||||
public interface BiShopOverviewService {
|
||||
|
||||
ShopOverviewStatisticsVO getShopOverview(ShopOverviewQueryDTO queryDTO);
|
||||
}
|
||||
+14
-14
@@ -1,17 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.shop.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.impl;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ShopOverviewStatisticsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopExportService;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
@@ -24,7 +24,7 @@ import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class ShopExportServiceImpl implements ShopExportService {
|
||||
public class BiShopExportServiceImpl implements BiShopExportService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
@@ -41,13 +41,13 @@ public class ShopExportServiceImpl implements ShopExportService {
|
||||
return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private final ShopOverviewStatisticsService shopOverviewStatisticsService;
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
private final CategoryExportExcelService categoryExportExcelService;
|
||||
|
||||
public ShopExportServiceImpl(
|
||||
ShopOverviewStatisticsService shopOverviewStatisticsService,
|
||||
public BiShopExportServiceImpl(
|
||||
BiShopOverviewService biShopOverviewService,
|
||||
CategoryExportExcelService categoryExportExcelService) {
|
||||
this.shopOverviewStatisticsService = shopOverviewStatisticsService;
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
this.categoryExportExcelService = categoryExportExcelService;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ public class ShopExportServiceImpl implements ShopExportService {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
queryDTO.setTaxRate(taxRate);
|
||||
|
||||
ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(queryDTO);
|
||||
ShopOverviewStatisticsVO vo = biShopOverviewService.getShopOverview(queryDTO);
|
||||
|
||||
String dateRangeLabel = dto.getDateRange().get(0).format(DATE_FMT)
|
||||
+ " 至 " + dto.getDateRange().get(dto.getDateRange().size() - 1).format(DATE_FMT);
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.shopoverview.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.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 单店概览:Mongo shop/product 日汇聚 + MySQL 推广/刷单/目标;表结构复用工作台四表构建。
|
||||
*/
|
||||
@Service
|
||||
public class BiShopOverviewServiceImpl implements BiShopOverviewService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopService shopService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
private final BiWorkbenchFeeLoader feeLoader;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ProductMapper productMapper;
|
||||
|
||||
public BiShopOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
BiOrderStatQueryService orderStatQueryService,
|
||||
BiWorkbenchFeeLoader feeLoader,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ProductMapper productMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.feeLoader = feeLoader;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.productMapper = productMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ShopOverviewStatisticsVO getShopOverview(ShopOverviewQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
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("开始日期不能晚于结束日期");
|
||||
}
|
||||
}
|
||||
|
||||
ShopPO shop = shopService.getById(queryDTO.getShopId());
|
||||
if (shop == null || !Objects.equals(shop.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
|
||||
List<Long> shopIds = List.of(shop.getId());
|
||||
List<ShopPO> shops = List.of(shop);
|
||||
Map<Long, String> platformByShopId = Map.of(shop.getId(),
|
||||
shop.getPlatformCode() != null ? shop.getPlatformCode() : "");
|
||||
|
||||
List<BiOrderStatDailyShopDoc> shopDocs =
|
||||
orderStatQueryService.listShopDocs(companyId, shopIds, startDate, endDate);
|
||||
List<BiOrderStatDailyProductDoc> productDocs =
|
||||
orderStatQueryService.listProductDocs(companyId, shopIds, startDate, endDate);
|
||||
BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, startDate, endDate);
|
||||
|
||||
List<OverviewAggRows.ShopProductRow> orderRows =
|
||||
orderStatQueryService.toShopProductRows(productDocs, platformByShopId);
|
||||
CompanyOverviewVO.WorkbenchTableBundle tables =
|
||||
companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, orderRows,
|
||||
fees.promotionRows(), fees.brushRows(), startDate, endDate);
|
||||
|
||||
BiOrderStatQueryService.ShopPeriodMetrics m = orderStatQueryService.sumShopDocs(shopDocs);
|
||||
BigDecimal promo = fees.promoTotal();
|
||||
BigDecimal brush = fees.brushTotal();
|
||||
BigDecimal orderCost = nz(m.productCost()).add(nz(m.freightCost())).add(nz(m.otherCost()));
|
||||
BigDecimal gross = nz(m.salesAmount()).subtract(orderCost).subtract(nz(m.refundAmount()));
|
||||
BigDecimal pbt = gross.subtract(promo).subtract(brush);
|
||||
BigDecimal tax = salesTax(m.salesAmount(), m.refundAmount(), taxRate);
|
||||
|
||||
ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO();
|
||||
vo.setShopId(shop.getId());
|
||||
vo.setShopName(shop.getName());
|
||||
vo.setTotalSalesAmount(nz(m.salesAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setTotalOrderCount(m.salesOrderCount());
|
||||
vo.setRefundAmount(nz(m.refundAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setAverageOrderValue(m.salesOrderCount() > 0
|
||||
? nz(m.salesAmount()).divide(BigDecimal.valueOf(m.salesOrderCount()), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
vo.setTotalPromotionFee(promo.setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setAverageFeeRatio(nz(m.salesAmount()).compareTo(BigDecimal.ZERO) > 0
|
||||
? promo.divide(nz(m.salesAmount()), 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
vo.setTotalProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setTotalTaxAmount(tax);
|
||||
vo.setTotalNetProfitAfterTax(pbt.subtract(tax).setScale(2, RoundingMode.HALF_UP));
|
||||
vo.setTotalROI(roi(nz(m.salesAmount()).subtract(nz(m.refundAmount())), promo));
|
||||
vo.setMonthOverMonthGrowth(calcMomGrowth(companyId, shopIds, startDate, endDate, m.salesAmount()));
|
||||
|
||||
fillTargets(vo, companyId, shop.getId(), startDate, endDate, m.salesAmount(), m.salesOrderCount());
|
||||
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> daily =
|
||||
orderStatQueryService.toDailyRows(shopDocs).stream()
|
||||
.filter(d -> d.getStatDate() != null)
|
||||
.collect(Collectors.toMap(OverviewAggRows.DailyRow::getStatDate, d -> d, (a, b) -> a));
|
||||
vo.setSalesAmountTrend(buildTrend(startDate, endDate, daily, true));
|
||||
vo.setOrderCountTrend(buildTrend(startDate, endDate, daily, false));
|
||||
|
||||
Map<Long, ProductPO> products = loadProducts(tables.getProductTable());
|
||||
vo.setProductOverview(mapProductOverview(tables.getProductTable(), products));
|
||||
vo.setCategoryOverview(mapCategoryOverview(tables.getCategoryTable()));
|
||||
fillProductSalesTop10(vo);
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
private BigDecimal calcMomGrowth(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end, BigDecimal curSales) {
|
||||
LocalDate prevStart = start.minusMonths(1);
|
||||
LocalDate prevEnd = end.minusMonths(1);
|
||||
BiOrderStatQueryService.ShopPeriodMetrics prev =
|
||||
orderStatQueryService.sumShopDocs(
|
||||
orderStatQueryService.listShopDocs(companyId, shopIds, prevStart, prevEnd));
|
||||
BigDecimal last = nz(prev.salesAmount());
|
||||
if (last.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return nz(curSales).subtract(last)
|
||||
.divide(last, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"));
|
||||
}
|
||||
return nz(curSales).compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private void fillTargets(ShopOverviewStatisticsVO vo, Long companyId, Long shopId,
|
||||
LocalDate startDate, LocalDate endDate,
|
||||
BigDecimal sales, int orderCount) {
|
||||
List<LocalDate> months = new ArrayList<>();
|
||||
LocalDate cur = startDate.withDayOfMonth(1);
|
||||
LocalDate endMonth = endDate.withDayOfMonth(1);
|
||||
while (!cur.isAfter(endMonth)) {
|
||||
months.add(cur);
|
||||
cur = cur.plusMonths(1);
|
||||
}
|
||||
List<ShopMonthlyTargetPO> targets = months.isEmpty() ? List.of()
|
||||
: shopMonthlyTargetMapper.selectList(new LambdaQueryWrapper<ShopMonthlyTargetPO>()
|
||||
.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
|
||||
.eq(ShopMonthlyTargetPO::getShopId, shopId)
|
||||
.in(ShopMonthlyTargetPO::getTargetMonth, months));
|
||||
|
||||
BigDecimal targetAmt = targets.stream()
|
||||
.map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int targetOrders = targets.stream()
|
||||
.mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0)
|
||||
.sum();
|
||||
vo.setTotalTargetAmount(targetAmt);
|
||||
vo.setTotalTargetOrderCount(targetOrders);
|
||||
vo.setSalesAmountAchievementRate(achievement(sales, targetAmt));
|
||||
vo.setOrderCountAchievementRate(achievement(BigDecimal.valueOf(orderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
private static BigDecimal achievement(BigDecimal actual, BigDecimal target) {
|
||||
if (target != null && target.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return nz(actual).divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
|
||||
}
|
||||
return nz(actual).compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private ShopOverviewStatisticsVO.TrendData buildTrend(
|
||||
LocalDate start, LocalDate end,
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> daily,
|
||||
boolean sales) {
|
||||
List<ShopOverviewStatisticsVO.TrendDataItem> items = new ArrayList<>();
|
||||
BigDecimal total = BigDecimal.ZERO;
|
||||
for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
|
||||
OverviewAggRows.DailyRow row = daily.get(d);
|
||||
BigDecimal value = sales
|
||||
? (row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO)
|
||||
: BigDecimal.valueOf(row != null && row.getOrderCount() != null ? row.getOrderCount() : 0L);
|
||||
ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem();
|
||||
item.setDate(d);
|
||||
item.setValue(value);
|
||||
items.add(item);
|
||||
total = total.add(value);
|
||||
}
|
||||
ShopOverviewStatisticsVO.TrendData trend = new ShopOverviewStatisticsVO.TrendData();
|
||||
trend.setTotal(total);
|
||||
trend.setDailyDataList(items);
|
||||
return trend;
|
||||
}
|
||||
|
||||
private Map<Long, ProductPO> loadProducts(CompanyOverviewVO.CategoryOverview productTable) {
|
||||
if (productTable == null || productTable.getCategories() == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Set<Long> ids = productTable.getCategories().stream()
|
||||
.map(CompanyOverviewVO.CategorySummary::getCategoryId)
|
||||
.filter(Objects::nonNull)
|
||||
.filter(id -> id > 0)
|
||||
.collect(Collectors.toSet());
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, ProductPO> map = new HashMap<>();
|
||||
for (ProductPO p : productMapper.selectBatchIds(ids)) {
|
||||
if (p != null && p.getId() != null) {
|
||||
map.put(p.getId(), p);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static ShopOverviewStatisticsVO.ProductOverview mapProductOverview(
|
||||
CompanyOverviewVO.CategoryOverview table, Map<Long, ProductPO> products) {
|
||||
ShopOverviewStatisticsVO.ProductOverview po = new ShopOverviewStatisticsVO.ProductOverview();
|
||||
if (table == null) {
|
||||
po.setProducts(List.of());
|
||||
return po;
|
||||
}
|
||||
po.setTotal(mapToProductSummary(table.getTotal(), null, products));
|
||||
if (table.getCategories() != null) {
|
||||
po.setProducts(table.getCategories().stream()
|
||||
.map(c -> mapToProductSummary(c, c.getCategoryId(), products))
|
||||
.collect(Collectors.toList()));
|
||||
} else {
|
||||
po.setProducts(List.of());
|
||||
}
|
||||
return po;
|
||||
}
|
||||
|
||||
private static ShopOverviewStatisticsVO.ProductSummary mapToProductSummary(
|
||||
CompanyOverviewVO.CategorySummary c, Long productId, Map<Long, ProductPO> products) {
|
||||
ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary();
|
||||
if (c == null) {
|
||||
return p;
|
||||
}
|
||||
p.setProductId(productId);
|
||||
ProductPO product = productId != null ? products.get(productId) : null;
|
||||
p.setProductName(product != null ? product.getName() : c.getCategoryName());
|
||||
p.setProductCode(product != null ? product.getProductCode() : null);
|
||||
copyMetrics(p, c);
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void copyMetrics(ShopOverviewStatisticsVO.ProductSummary p,
|
||||
CompanyOverviewVO.CategorySummary c) {
|
||||
p.setSalesAmount(c.getSalesAmount());
|
||||
p.setOrderCount(c.getOrderCount());
|
||||
p.setAverageOrderValue(c.getAverageOrderValue());
|
||||
p.setProductCost(c.getProductCost());
|
||||
p.setShippingCost(c.getShippingCost());
|
||||
p.setOtherCost(c.getOtherCost());
|
||||
p.setOrderCost(c.getOrderCost());
|
||||
p.setRefundAmount(c.getRefundAmount());
|
||||
p.setTotalPromotionFee(c.getTotalPromotionFee());
|
||||
p.setBrushFee(c.getBrushFee());
|
||||
p.setFeeRatio(c.getFeeRatio());
|
||||
p.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax());
|
||||
p.setSalesTaxAmount(c.getSalesTaxAmount());
|
||||
p.setProfitAfterTax(c.getProfitAfterTax());
|
||||
p.setRoi(c.getRoi());
|
||||
}
|
||||
|
||||
private static ShopOverviewStatisticsVO.CategoryOverview mapCategoryOverview(
|
||||
CompanyOverviewVO.CategoryOverview table) {
|
||||
ShopOverviewStatisticsVO.CategoryOverview co = new ShopOverviewStatisticsVO.CategoryOverview();
|
||||
if (table == null) {
|
||||
co.setCategories(List.of());
|
||||
return co;
|
||||
}
|
||||
co.setTotal(mapToCategorySummary(table.getTotal()));
|
||||
if (table.getCategories() != null) {
|
||||
co.setCategories(table.getCategories().stream()
|
||||
.map(BiShopOverviewServiceImpl::mapToCategorySummary)
|
||||
.collect(Collectors.toList()));
|
||||
} else {
|
||||
co.setCategories(List.of());
|
||||
}
|
||||
return co;
|
||||
}
|
||||
|
||||
private static ShopOverviewStatisticsVO.CategorySummary mapToCategorySummary(
|
||||
CompanyOverviewVO.CategorySummary c) {
|
||||
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
|
||||
if (c == null) {
|
||||
return s;
|
||||
}
|
||||
s.setCategoryId(c.getCategoryId());
|
||||
s.setCategoryName(c.getCategoryName());
|
||||
s.setSalesAmount(c.getSalesAmount());
|
||||
s.setOrderCount(c.getOrderCount());
|
||||
s.setAverageOrderValue(c.getAverageOrderValue());
|
||||
s.setProductCost(c.getProductCost());
|
||||
s.setShippingCost(c.getShippingCost());
|
||||
s.setOtherCost(c.getOtherCost());
|
||||
s.setOrderCost(c.getOrderCost());
|
||||
s.setRefundAmount(c.getRefundAmount());
|
||||
s.setTotalPromotionFee(c.getTotalPromotionFee());
|
||||
s.setBrushFee(c.getBrushFee());
|
||||
s.setFeeRatio(c.getFeeRatio());
|
||||
s.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax());
|
||||
s.setSalesTaxAmount(c.getSalesTaxAmount());
|
||||
s.setProfitAfterTax(c.getProfitAfterTax());
|
||||
s.setRoi(c.getRoi());
|
||||
return s;
|
||||
}
|
||||
|
||||
private static void fillProductSalesTop10(ShopOverviewStatisticsVO vo) {
|
||||
ShopOverviewStatisticsVO.ProductOverview po = vo.getProductOverview();
|
||||
if (po == null || po.getProducts() == null || po.getProducts().isEmpty()) {
|
||||
vo.setProductSalesTop10(Collections.emptyList());
|
||||
return;
|
||||
}
|
||||
vo.setProductSalesTop10(po.getProducts().stream()
|
||||
.sorted(Comparator.comparing(
|
||||
(ShopOverviewStatisticsVO.ProductSummary p) ->
|
||||
p.getOrderCount() != null ? p.getOrderCount() : 0,
|
||||
Comparator.reverseOrder()))
|
||||
.limit(10)
|
||||
.map(p -> {
|
||||
ShopOverviewStatisticsVO.ProductSalesRankItem item =
|
||||
new ShopOverviewStatisticsVO.ProductSalesRankItem();
|
||||
item.setProductId(p.getProductId());
|
||||
item.setProductName(p.getProductName());
|
||||
item.setProductCode(p.getProductCode());
|
||||
item.setOrderCount(p.getOrderCount());
|
||||
item.setSalesAmount(p.getSalesAmount());
|
||||
return item;
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) {
|
||||
BigDecimal base = nz(sales).subtract(nz(refund));
|
||||
if (base.compareTo(BigDecimal.ZERO) < 0) {
|
||||
base = BigDecimal.ZERO;
|
||||
}
|
||||
return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) {
|
||||
if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
return nz(netSales).divide(promo, 2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.util.ExportFilenameUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO;
|
||||
|
||||
@Tag(name = "BI-工作台导出", description = "多维度经营明细 Excel 导出(Mongo 订单日汇聚)")
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 工作台「经营概览」Tab 专用:KPI/趋势/饼图 + 底部四张汇总表。
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
|
||||
+6
-6
@@ -3,12 +3,12 @@ package top.xyquan.ecomdmbbackend.modules.bi.workbench.service.impl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.ExportService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
+3
-3
@@ -5,11 +5,11 @@ import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.brushorder.mapper.BrushOrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
|
||||
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.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.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.CompanyOverviewService;
|
||||
|
||||
/**
|
||||
* 全店铺概览控制器
|
||||
*/
|
||||
@Tag(name = "电商-全店铺概览", description = "全店铺概览统计接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/store")
|
||||
public class CompanyOverviewController {
|
||||
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
|
||||
public CompanyOverviewController(CompanyOverviewService companyOverviewService) {
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取全店铺概览统计数据", description = "获取当前公司所有店铺的概览统计数据,包括销售额、单量、推广费、利润、ROI等")
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "ecom:shop:read", description = "查询全店铺概览", allowSuper = true)
|
||||
public ApiResponse<CompanyOverviewVO> getCompanyOverview(@Valid @RequestBody CompanyOverviewQueryDTO queryDTO) {
|
||||
CompanyOverviewVO overviewVO = companyOverviewService.getCompanyOverview(queryDTO);
|
||||
return ApiResponse.success("获取全店铺概览成功", overviewVO);
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.service.ExportService;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.util.ExportFilenameUtils;
|
||||
|
||||
/**
|
||||
* 全店概览导出:{@code POST /ec/store-overview/export/{by-shop|by-category|by-platform}}
|
||||
*/
|
||||
@Tag(name = "电商-全店概览导出", description = "全店概览:按店铺 / 按品类 / 按平台汇总 Excel 导出")
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/store-overview/export")
|
||||
public class ExportController {
|
||||
|
||||
private final ExportService exportService;
|
||||
|
||||
public ExportController(ExportService exportService) {
|
||||
this.exportService = exportService;
|
||||
}
|
||||
|
||||
@Operation(summary = "全店概览-按店铺汇总", description = "导出全店按店铺维度的汇总数据为 Excel,可按店铺筛选")
|
||||
@PostMapping("/by-shop")
|
||||
@RequirePermission(value = "data:export", description = "导出全店概览(按店铺汇总)", allowSuper = true)
|
||||
public void exportCompanyOverview(@Valid @RequestBody CompanyExportDTO dto, HttpServletResponse response) {
|
||||
byte[] data = exportService.exportCompanyOverview(dto);
|
||||
String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按店铺汇总", dto.getDateRange());
|
||||
writeExcel(response, filename, data);
|
||||
}
|
||||
|
||||
@Operation(summary = "全店概览-按品类汇总", description = "导出全店按品类维度的汇总数据为 Excel,支持指定品类或导出全部")
|
||||
@PostMapping("/by-category")
|
||||
@RequirePermission(value = "data:export", description = "导出全店概览(按品类汇总)", allowSuper = true)
|
||||
public void exportCategoryOverview(@Valid @RequestBody CategoryExportDTO dto, HttpServletResponse response) {
|
||||
byte[] data = exportService.exportCategoryOverview(dto);
|
||||
String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按品类汇总", dto.getDateRange());
|
||||
writeExcel(response, filename, data);
|
||||
}
|
||||
|
||||
@Operation(summary = "全店概览-按平台汇总", description = "导出全店按平台维度的汇总数据为 Excel,支持指定平台或导出全部")
|
||||
@PostMapping("/by-platform")
|
||||
@RequirePermission(value = "data:export", description = "导出全店概览(按平台汇总)", allowSuper = true)
|
||||
public void exportPlatformOverview(@Valid @RequestBody PlatformExportDTO dto, HttpServletResponse response) {
|
||||
byte[] data = exportService.exportPlatformOverview(dto);
|
||||
String filename = ExportFilenameUtils.buildFullStoreOverviewXlsxName("按平台汇总", dto.getDateRange());
|
||||
writeExcel(response, filename, data);
|
||||
}
|
||||
|
||||
private void writeExcel(HttpServletResponse response, String filename, byte[] data) {
|
||||
try {
|
||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
|
||||
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
|
||||
response.getOutputStream().write(data);
|
||||
response.getOutputStream().flush();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("写入Excel文件失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店铺概览查询DTO
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@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;
|
||||
|
||||
/**
|
||||
* 税率(默认4%)
|
||||
*/
|
||||
@Schema(description = "税率,默认为0.04(即4%)", example = "0.04")
|
||||
private BigDecimal taxRate = new BigDecimal("0.04");
|
||||
}
|
||||
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.brushorder.model.po.BrushOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店铺概览服务接口
|
||||
*/
|
||||
public interface CompanyOverviewService {
|
||||
|
||||
/**
|
||||
* 获取全店铺概览统计数据
|
||||
*
|
||||
* @param queryDTO 查询DTO
|
||||
* @return 全店铺概览VO
|
||||
*/
|
||||
CompanyOverviewVO getCompanyOverview(CompanyOverviewQueryDTO queryDTO);
|
||||
|
||||
/**
|
||||
* 构建工作台底部四张汇总表:与 {@link #getCompanyOverview(CompanyOverviewQueryDTO)} 中
|
||||
* shopSummary / platformSummary / categorySummary 同源(另含按商品聚合表)。
|
||||
* 入参订单、推广费、刷单费须已按工作台筛选(店铺、日期等)准备好。
|
||||
*
|
||||
* @param taxRate 请求税率(与概览接口一致)
|
||||
* @param companyId 当前公司
|
||||
* @param shops 参与汇总的店铺列表(须属于该公司)
|
||||
* @param orders 已筛选订单
|
||||
* @param promotionFees 已筛选推广费
|
||||
* @param brushOrders 已筛选刷单费
|
||||
* @param stat 订单状态统计集合
|
||||
* @param startDate 开始日期
|
||||
* @param endDate 结束日期
|
||||
*/
|
||||
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTables(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OrderPO> orders,
|
||||
List<PromotionFeePO> promotionFees,
|
||||
List<BrushOrderPO> brushOrders,
|
||||
OrderStatusStatSets stat,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate);
|
||||
|
||||
/**
|
||||
* 基于 SQL 聚合行构建四表(与 {@link #buildWorkbenchSummaryTables} 口径一致,不拉订单明细)。
|
||||
*/
|
||||
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate);
|
||||
}
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 全店概览导出服务(按店铺 / 按品类 / 按平台)
|
||||
*/
|
||||
public interface ExportService {
|
||||
|
||||
/**
|
||||
* 全店概览:按店铺汇总 Excel
|
||||
*/
|
||||
byte[] exportCompanyOverview(CompanyExportDTO dto);
|
||||
|
||||
/**
|
||||
* 全店概览:按品类汇总 Excel
|
||||
*/
|
||||
byte[] exportCategoryOverview(CategoryExportDTO dto);
|
||||
|
||||
/**
|
||||
* 全店概览:按平台汇总 Excel
|
||||
*/
|
||||
byte[] exportPlatformOverview(PlatformExportDTO dto);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按店铺」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按平台」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle);
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.vo.ShopOverviewStatisticsVO;
|
||||
|
||||
/**
|
||||
* 单店铺概览统计服务接口
|
||||
*/
|
||||
public interface ShopOverviewStatisticsService {
|
||||
|
||||
/**
|
||||
* 获取单店铺概览统计数据
|
||||
*
|
||||
* @param queryDTO 查询DTO
|
||||
* @return 单店铺概览统计VO
|
||||
*/
|
||||
ShopOverviewStatisticsVO getShopOverviewStatistics(ShopOverviewQueryDTO queryDTO);
|
||||
}
|
||||
|
||||
-2333
File diff suppressed because it is too large
Load Diff
-1072
File diff suppressed because it is too large
Load Diff
-39
@@ -1,39 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.overview.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.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.service.ProductOverviewService;
|
||||
|
||||
/**
|
||||
* 商品概览控制器
|
||||
*/
|
||||
@Tag(name = "电商-商品概览", description = "商品统计概览接口")
|
||||
@RestController
|
||||
@RequestMapping("/ec/product")
|
||||
public class ProductOverviewController {
|
||||
|
||||
private final ProductOverviewService productOverviewService;
|
||||
|
||||
public ProductOverviewController(ProductOverviewService productOverviewService) {
|
||||
this.productOverviewService = productOverviewService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取商品总览", description = "获取指定商品在日期范围内的销售额、订单数、客单价、成本、退款金额、推广费、费比等统计数据")
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "ecom:product:read", description = "查询商品总览", allowSuper = true)
|
||||
public ApiResponse<ProductOverviewVO> getProductOverview(
|
||||
@Valid @RequestBody ProductOverviewQueryDTO queryDTO) {
|
||||
ProductOverviewVO overview = productOverviewService.getProductOverview(queryDTO);
|
||||
return ApiResponse.success("获取商品总览成功", overview);
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO;
|
||||
|
||||
/**
|
||||
* 商品概览服务接口
|
||||
*/
|
||||
public interface ProductOverviewService {
|
||||
|
||||
/**
|
||||
* 获取商品总览统计数据
|
||||
*
|
||||
* @param queryDTO 查询参数(商品ID + 日期范围)
|
||||
* @return 商品总览数据
|
||||
*/
|
||||
ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO);
|
||||
}
|
||||
-834
@@ -1,834 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.overview.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.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.support.OrderOverviewSupport;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.model.vo.ProductOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.overview.service.ProductOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.promotion.model.po.PromotionFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.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.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品概览服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final PromotionFeeMapper promotionFeeMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ProductService productService;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ShopService shopService;
|
||||
|
||||
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
OrderMapper orderMapper,
|
||||
OrderItemMapper orderItemMapper,
|
||||
PromotionFeeMapper promotionFeeMapper,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ProductService productService,
|
||||
ProductSkuMapper productSkuMapper,
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ShopService shopService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.orderMapper = orderMapper;
|
||||
this.orderItemMapper = orderItemMapper;
|
||||
this.promotionFeeMapper = promotionFeeMapper;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.productService = productService;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.shopService = shopService;
|
||||
}
|
||||
|
||||
private void applyProductOverviewOrderScope(LambdaQueryWrapper<OrderPO> wrapper,
|
||||
Long companyId,
|
||||
Long productId,
|
||||
Long shopId,
|
||||
LocalDateTime startDateTime,
|
||||
LocalDateTime endDateTime,
|
||||
List<String> unionStatusCodes) {
|
||||
wrapper.eq(OrderPO::getCompanyId, companyId)
|
||||
.apply("EXISTS (SELECT 1 FROM ec_order_item i WHERE i.order_id = ec_order.id AND i.product_id = {0})",
|
||||
productId)
|
||||
.ge(OrderPO::getOrderTime, startDateTime)
|
||||
.le(OrderPO::getOrderTime, endDateTime);
|
||||
if (shopId != null) {
|
||||
wrapper.eq(OrderPO::getShopId, shopId);
|
||||
}
|
||||
if (!unionStatusCodes.isEmpty()) {
|
||||
wrapper.in(OrderPO::getStatus, unionStatusCodes);
|
||||
} else {
|
||||
wrapper.isNull(OrderPO::getId);
|
||||
}
|
||||
}
|
||||
|
||||
/** 税额 = max(0, 销售额 − 退款) × 税率,保留两位小数。 */
|
||||
private static BigDecimal salesTaxOnNetSales(BigDecimal salesAmount, BigDecimal refundAmount, BigDecimal taxRate) {
|
||||
BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO;
|
||||
BigDecimal refund = refundAmount != null ? refundAmount : BigDecimal.ZERO;
|
||||
BigDecimal rate = taxRate != null ? taxRate : new BigDecimal("0.04");
|
||||
BigDecimal base = sales.subtract(refund);
|
||||
if (base.compareTo(BigDecimal.ZERO) < 0) {
|
||||
base = BigDecimal.ZERO;
|
||||
}
|
||||
return base.multiply(rate).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProductOverviewVO getProductOverview(ProductOverviewQueryDTO queryDTO) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
|
||||
// 验证商品是否存在
|
||||
ProductPO product = productService.getById(queryDTO.getProductId());
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
|
||||
// 验证日期范围
|
||||
if (queryDTO.getStartDate().isAfter(queryDTO.getEndDate())) {
|
||||
throw new BusinessException("开始日期不能晚于结束日期");
|
||||
}
|
||||
|
||||
Long filterShopId = queryDTO.getShopId();
|
||||
if (filterShopId != null) {
|
||||
ShopPO shop = shopService.getById(filterShopId);
|
||||
if (shop == null || !shop.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
}
|
||||
|
||||
LocalDate startDate = queryDTO.getStartDate();
|
||||
LocalDate endDate = queryDTO.getEndDate();
|
||||
LocalDateTime startDateTime = startDate.atStartOfDay();
|
||||
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
|
||||
|
||||
// 税率
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null
|
||||
? queryDTO.getTaxRate()
|
||||
: new BigDecimal("0.04");
|
||||
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
List<String> unionStatusCodes = stat.getUnionStatusCodes();
|
||||
|
||||
// 查询订单数据
|
||||
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
|
||||
applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId,
|
||||
startDateTime, endDateTime, unionStatusCodes);
|
||||
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
|
||||
|
||||
// 推广费/达成率所用店铺:指定店铺时固定该店,否则取订单涉及店铺
|
||||
List<Long> shopIds;
|
||||
if (filterShopId != null) {
|
||||
shopIds = List.of(filterShopId);
|
||||
} else {
|
||||
shopIds = orders.stream()
|
||||
.map(OrderPO::getShopId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// 查询推广费(相关店铺 + 日期)
|
||||
List<PromotionFeePO> promotionFees = new ArrayList<>();
|
||||
if (!shopIds.isEmpty()) {
|
||||
LambdaQueryWrapper<PromotionFeePO> promoWrapper = new LambdaQueryWrapper<>();
|
||||
promoWrapper.eq(PromotionFeePO::getCompanyId, companyId)
|
||||
.in(PromotionFeePO::getShopId, shopIds)
|
||||
.ge(PromotionFeePO::getFeeDate, startDate)
|
||||
.le(PromotionFeePO::getFeeDate, endDate);
|
||||
promotionFees = promotionFeeMapper.selectList(promoWrapper);
|
||||
}
|
||||
|
||||
// 店铺维度全部订单(推广费按商品/类目/全店口径分摊,与店铺概览商品汇总一致)
|
||||
List<OrderPO> allShopOrdersForPromo = new ArrayList<>();
|
||||
if (!shopIds.isEmpty()) {
|
||||
LambdaQueryWrapper<OrderPO> allOrdersWrapper = new LambdaQueryWrapper<>();
|
||||
allOrdersWrapper.eq(OrderPO::getCompanyId, companyId)
|
||||
.in(OrderPO::getShopId, shopIds)
|
||||
.ge(OrderPO::getOrderTime, startDateTime)
|
||||
.le(OrderPO::getOrderTime, endDateTime);
|
||||
if (!unionStatusCodes.isEmpty()) {
|
||||
allOrdersWrapper.in(OrderPO::getStatus, unionStatusCodes);
|
||||
} else {
|
||||
allOrdersWrapper.isNull(OrderPO::getId);
|
||||
}
|
||||
allShopOrdersForPromo = orderMapper.selectList(allOrdersWrapper);
|
||||
}
|
||||
|
||||
// 查询上月同期数据(用于环比计算)
|
||||
long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1;
|
||||
LocalDate lastStartDate = startDate.minusDays(dayCount);
|
||||
LocalDate lastEndDate = startDate.minusDays(1);
|
||||
LocalDateTime lastStartTime = lastStartDate.atStartOfDay();
|
||||
LocalDateTime lastEndTime = lastEndDate.atTime(23, 59, 59);
|
||||
|
||||
LambdaQueryWrapper<OrderPO> lastPeriodWrapper = new LambdaQueryWrapper<>();
|
||||
applyProductOverviewOrderScope(lastPeriodWrapper, companyId, queryDTO.getProductId(), filterShopId,
|
||||
lastStartTime, lastEndTime, unionStatusCodes);
|
||||
List<OrderPO> lastPeriodOrders = orderMapper.selectList(lastPeriodWrapper);
|
||||
|
||||
// ========== 构建返回对象 ==========
|
||||
ProductOverviewVO vo = new ProductOverviewVO();
|
||||
vo.setProductId(product.getId());
|
||||
vo.setProductName(product.getName());
|
||||
|
||||
// ---------- KPI 汇总指标 ----------
|
||||
// 总销售额(按状态「计入销售额」维度)
|
||||
BigDecimal totalSalesAmount = orders.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
vo.setTotalSalesAmount(totalSalesAmount);
|
||||
|
||||
// 总订单量(按状态「计入销售额」维度计单,与店铺概览一致)
|
||||
int totalOrderCount = (int) orders.stream()
|
||||
.filter(o -> stat.includesSales(o.getStatus()))
|
||||
.count();
|
||||
vo.setTotalOrderCount(totalOrderCount);
|
||||
|
||||
// 总退款金额(用于 ROI 计算)
|
||||
BigDecimal totalRefundAmount = orders.stream()
|
||||
.map(stat::receivedForRefund)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
// 订单成本(商品/运费/其他成本按各维度开关,含数量)
|
||||
BigDecimal totalCostAmount = orders.stream()
|
||||
.map(stat::totalCostForStats)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
vo.setAverageFeeRatio(null); // 由 spec 维度均化,待后面补充
|
||||
|
||||
// 总推广费(与 ShopOverviewStatisticsServiceImpl 商品维度推广费归属一致)
|
||||
BigDecimal totalPromotionFee = computeAttributedPromotionForProduct(
|
||||
queryDTO.getProductId(),
|
||||
product,
|
||||
allShopOrdersForPromo,
|
||||
promotionFees,
|
||||
stat);
|
||||
|
||||
// 费比
|
||||
BigDecimal avgFeeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromotionFee.divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
vo.setAverageFeeRatio(avgFeeRatio.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP)); // 转为百分比
|
||||
|
||||
BigDecimal totalTaxAmount = salesTaxOnNetSales(totalSalesAmount, totalRefundAmount, taxRate);
|
||||
vo.setTotalTaxAmount(totalTaxAmount);
|
||||
|
||||
// 税后盈亏
|
||||
BigDecimal totalProfitAfterTax = totalSalesAmount
|
||||
.subtract(totalCostAmount)
|
||||
.subtract(totalRefundAmount)
|
||||
.subtract(totalPromotionFee)
|
||||
.subtract(totalTaxAmount);
|
||||
vo.setTotalNetProfitAfterTax(totalProfitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
|
||||
// ROI = (销售额 - 退款金额) / 推广费(与店铺概览 calculateSalesROI 口径一致)
|
||||
BigDecimal totalROI = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmount.subtract(totalRefundAmount)
|
||||
.divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
vo.setTotalROI(totalROI);
|
||||
|
||||
// ---------- 环比增长(上月同期) ----------
|
||||
BigDecimal lastPeriodSales = lastPeriodOrders.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal monthOverMonthGrowth = BigDecimal.ZERO;
|
||||
if (lastPeriodSales.compareTo(BigDecimal.ZERO) > 0) {
|
||||
monthOverMonthGrowth = totalSalesAmount
|
||||
.subtract(lastPeriodSales)
|
||||
.divide(lastPeriodSales, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
} else if (totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||
monthOverMonthGrowth = new BigDecimal("100.00");
|
||||
}
|
||||
vo.setMonthOverMonthGrowth(monthOverMonthGrowth);
|
||||
|
||||
// ---------- 达成率(简化:按店铺月度目标计算) ----------
|
||||
if (!shopIds.isEmpty()) {
|
||||
LocalDate firstDayOfMonth = startDate.withDayOfMonth(1);
|
||||
LocalDate lastDayOfMonth = endDate.withDayOfMonth(endDate.lengthOfMonth());
|
||||
|
||||
LambdaQueryWrapper<ShopMonthlyTargetPO> targetWrapper = new LambdaQueryWrapper<>();
|
||||
targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
|
||||
.in(ShopMonthlyTargetPO::getShopId, shopIds)
|
||||
.ge(ShopMonthlyTargetPO::getTargetMonth, firstDayOfMonth)
|
||||
.le(ShopMonthlyTargetPO::getTargetMonth, lastDayOfMonth);
|
||||
List<ShopMonthlyTargetPO> shopTargets = shopMonthlyTargetMapper.selectList(targetWrapper);
|
||||
|
||||
BigDecimal totalTargetAmount = shopTargets.stream()
|
||||
.map(ShopMonthlyTargetPO::getTargetAmount)
|
||||
.filter(Objects::nonNull)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int totalTargetOrderCount = shopTargets.stream()
|
||||
.map(ShopMonthlyTargetPO::getTargetOrderCount)
|
||||
.filter(Objects::nonNull)
|
||||
.mapToInt(Integer::intValue)
|
||||
.sum();
|
||||
|
||||
if (totalTargetAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||
BigDecimal salesRate = totalSalesAmount
|
||||
.divide(totalTargetAmount, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
vo.setSalesAmountAchievementRate(salesRate);
|
||||
}
|
||||
if (totalTargetOrderCount > 0) {
|
||||
BigDecimal orderRate = BigDecimal.valueOf((long) totalOrderCount)
|
||||
.divide(BigDecimal.valueOf(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
vo.setOrderCountAchievementRate(orderRate);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 趋势数据 ----------
|
||||
vo.setSalesAmountTrend(buildTrend(orders, dateList -> dateList.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add), startDate, endDate));
|
||||
|
||||
vo.setOrderCountTrend(buildOrderCountTrend(orders, stat, startDate, endDate));
|
||||
|
||||
// ---------- 规格销售汇总 ----------
|
||||
vo.setSpecSummaries(buildSpecSummary(orders, stat, taxRate, totalPromotionFee));
|
||||
|
||||
// ---------- 各规格销量 Top10 ----------
|
||||
vo.setSpecSalesTop10(buildSpecSalesTop10(orders, stat, shopIds));
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建销售趋势
|
||||
*/
|
||||
private ProductOverviewVO.TrendData buildTrend(List<OrderPO> orders,
|
||||
java.util.function.Function<List<OrderPO>, BigDecimal> reducer,
|
||||
LocalDate startDate, LocalDate endDate) {
|
||||
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
|
||||
.collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate()));
|
||||
|
||||
List<ProductOverviewVO.TrendDataItem> dailyList = new ArrayList<>();
|
||||
LocalDate current = startDate;
|
||||
while (!current.isAfter(endDate)) {
|
||||
List<OrderPO> dayOrders = ordersByDate.getOrDefault(current, List.of());
|
||||
BigDecimal value = reducer.apply(dayOrders);
|
||||
|
||||
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
|
||||
item.setDate(current);
|
||||
item.setValue(value);
|
||||
dailyList.add(item);
|
||||
current = current.plusDays(1);
|
||||
}
|
||||
|
||||
BigDecimal total = dailyList.stream()
|
||||
.map(ProductOverviewVO.TrendDataItem::getValue)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
|
||||
trend.setTotal(total);
|
||||
trend.setDailyDataList(dailyList);
|
||||
return trend;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建订单数趋势
|
||||
*/
|
||||
private ProductOverviewVO.TrendData buildOrderCountTrend(List<OrderPO> orders,
|
||||
OrderStatusStatSets stat,
|
||||
LocalDate startDate, LocalDate endDate) {
|
||||
Map<LocalDate, List<OrderPO>> ordersByDate = orders.stream()
|
||||
.collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate()));
|
||||
|
||||
List<ProductOverviewVO.TrendDataItem> dailyList = new ArrayList<>();
|
||||
LocalDate current = startDate;
|
||||
while (!current.isAfter(endDate)) {
|
||||
List<OrderPO> dayOrders = ordersByDate.getOrDefault(current, List.of());
|
||||
long count = dayOrders.stream()
|
||||
.filter(o -> stat.includesSales(o.getStatus()))
|
||||
.count();
|
||||
|
||||
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
|
||||
item.setDate(current);
|
||||
item.setValue(BigDecimal.valueOf(count));
|
||||
dailyList.add(item);
|
||||
current = current.plusDays(1);
|
||||
}
|
||||
|
||||
long sumDaily = dailyList.stream().mapToLong(i -> i.getValue().longValue()).sum();
|
||||
BigDecimal total = BigDecimal.valueOf(sumDaily);
|
||||
|
||||
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
|
||||
trend.setTotal(total);
|
||||
trend.setDailyDataList(dailyList);
|
||||
return trend;
|
||||
}
|
||||
|
||||
private Map<Long, Long> orderSpecIdToProductIdMapForOverview(List<OrderPO> orders) {
|
||||
return OrderOverviewSupport.orderSpecIdToProductIdMap(productSkuMapper, orderItemMapper, orders);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将店铺范围内推广费归属到指定商品(与店铺概览「按商品汇总」推广费口径一致)
|
||||
*/
|
||||
private BigDecimal computeAttributedPromotionForProduct(
|
||||
Long productId,
|
||||
ProductPO product,
|
||||
List<OrderPO> allShopOrders,
|
||||
List<PromotionFeePO> promotionFees,
|
||||
OrderStatusStatSets stat) {
|
||||
if (productId == null || allShopOrders == null || allShopOrders.isEmpty()) {
|
||||
return promotionFees.stream()
|
||||
.filter(f -> productId != null && productId.equals(f.getProductId()))
|
||||
.map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
|
||||
Map<Long, Long> skuToProduct = orderSpecIdToProductIdMapForOverview(allShopOrders);
|
||||
Map<Long, OrderItemPO> firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, allShopOrders);
|
||||
Map<Long, List<OrderPO>> ordersByProduct = allShopOrders.stream()
|
||||
.collect(Collectors.groupingBy(o ->
|
||||
OrderOverviewSupport.productIdOfOrder(o, firstItems, skuToProduct)));
|
||||
|
||||
Map<Long, BigDecimal> directPromotionByProduct = promotionFees.stream()
|
||||
.filter(fee -> fee.getProductId() != null)
|
||||
.collect(Collectors.groupingBy(
|
||||
PromotionFeePO::getProductId,
|
||||
Collectors.reducing(
|
||||
BigDecimal.ZERO,
|
||||
fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO,
|
||||
BigDecimal::add)));
|
||||
|
||||
Map<Long, BigDecimal> categoryOnlyPool = promotionFees.stream()
|
||||
.filter(fee -> fee.getProductId() == null && fee.getCategoryId() != null)
|
||||
.collect(Collectors.groupingBy(
|
||||
PromotionFeePO::getCategoryId,
|
||||
Collectors.reducing(
|
||||
BigDecimal.ZERO,
|
||||
fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO,
|
||||
BigDecimal::add)));
|
||||
|
||||
BigDecimal globalRatioPool = promotionFees.stream()
|
||||
.filter(fee -> fee.getProductId() == null && fee.getCategoryId() == null)
|
||||
.map(fee -> fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
Map<Long, BigDecimal> productPromotionFromCategory = new HashMap<>();
|
||||
for (Map.Entry<Long, BigDecimal> catEntry : categoryOnlyPool.entrySet()) {
|
||||
Long catId = catEntry.getKey();
|
||||
BigDecimal pool = catEntry.getValue();
|
||||
if (catId == null || pool == null || pool.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
continue;
|
||||
}
|
||||
Map<Long, BigDecimal> eligibleSalesByProduct = new HashMap<>();
|
||||
for (Map.Entry<Long, List<OrderPO>> e : ordersByProduct.entrySet()) {
|
||||
Long pid = e.getKey();
|
||||
if (pid == null || pid < 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal direct = directPromotionByProduct.getOrDefault(pid, BigDecimal.ZERO);
|
||||
if (direct.compareTo(BigDecimal.ZERO) > 0) {
|
||||
continue;
|
||||
}
|
||||
ProductPO p = productService.getById(pid);
|
||||
if (p == null || !Objects.equals(p.getCategoryId(), catId)) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal sal = e.getValue().stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
eligibleSalesByProduct.put(pid, sal);
|
||||
}
|
||||
BigDecimal totalElig = eligibleSalesByProduct.values().stream()
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
if (totalElig.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
globalRatioPool = globalRatioPool.add(pool);
|
||||
continue;
|
||||
}
|
||||
for (Map.Entry<Long, BigDecimal> pe : eligibleSalesByProduct.entrySet()) {
|
||||
BigDecimal share = pool.multiply(pe.getValue())
|
||||
.divide(totalElig, 4, RoundingMode.HALF_UP);
|
||||
productPromotionFromCategory.merge(pe.getKey(), share, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
|
||||
Map<Long, BigDecimal> salesByProduct = ordersByProduct.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> e.getValue().stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add)));
|
||||
BigDecimal totalSalesAmount = salesByProduct.values().stream()
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
List<OrderPO> productOrders = ordersByProduct.getOrDefault(productId, Collections.emptyList());
|
||||
BigDecimal salesAmount = productOrders.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
BigDecimal productPromotionFee = directPromotionByProduct.getOrDefault(productId, BigDecimal.ZERO)
|
||||
.add(productPromotionFromCategory.getOrDefault(productId, BigDecimal.ZERO));
|
||||
if (productPromotionFee.compareTo(BigDecimal.ZERO) == 0
|
||||
&& globalRatioPool.compareTo(BigDecimal.ZERO) > 0
|
||||
&& totalSalesAmount.compareTo(BigDecimal.ZERO) > 0) {
|
||||
BigDecimal ratio = salesAmount.divide(totalSalesAmount, 4, RoundingMode.HALF_UP);
|
||||
productPromotionFee = globalRatioPool.multiply(ratio);
|
||||
}
|
||||
return productPromotionFee;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建规格销售汇总(推广费总额为已归属到本商品的金额,再按规格订单数比例拆到各规格)
|
||||
*/
|
||||
private ProductOverviewVO.SpecSummary buildSpecSummary(List<OrderPO> orders,
|
||||
OrderStatusStatSets stat,
|
||||
BigDecimal taxRate,
|
||||
BigDecimal attributedPromotionForProduct) {
|
||||
// 查询商品所有规格
|
||||
if (orders.isEmpty()) {
|
||||
return buildEmptySpecSummary();
|
||||
}
|
||||
|
||||
OrderPO firstOrder = orders.get(0);
|
||||
Long companyId = firstOrder.getCompanyId();
|
||||
Map<Long, OrderItemPO> firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders);
|
||||
OrderItemPO firstItem = firstItems.get(firstOrder.getId());
|
||||
Long productId = firstItem != null ? firstItem.getProductId() : null;
|
||||
if (productId == null && firstItem != null && firstItem.getProductSkuId() != null) {
|
||||
ProductSkuPO firstSpec = productSkuMapper.selectById(firstItem.getProductSkuId());
|
||||
if (firstSpec != null) {
|
||||
productId = firstSpec.getProductId();
|
||||
}
|
||||
}
|
||||
if (productId == null) {
|
||||
return buildEmptySpecSummary();
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<ProductSkuPO> skuWrapper = new LambdaQueryWrapper<>();
|
||||
skuWrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getProductId, productId);
|
||||
List<ProductSkuPO> allSkus = productSkuMapper.selectList(skuWrapper);
|
||||
Map<Long, ProductSkuPO> skuMap = allSkus.stream()
|
||||
.collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
BigDecimal totalAttributed = attributedPromotionForProduct != null
|
||||
? attributedPromotionForProduct
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
// 按规格分组订单
|
||||
Map<Long, List<OrderPO>> ordersBySpec = orders.stream()
|
||||
.collect(Collectors.groupingBy(o -> {
|
||||
OrderItemPO item = firstItems.get(o.getId());
|
||||
Long skuId = item != null ? item.getProductSkuId() : null;
|
||||
return skuId != null ? skuId : 0L;
|
||||
}));
|
||||
|
||||
List<ProductOverviewVO.SpecSummaryItem> specItems = new ArrayList<>();
|
||||
|
||||
for (Map.Entry<Long, List<OrderPO>> entry : ordersBySpec.entrySet()) {
|
||||
Long skuId = entry.getKey();
|
||||
if (skuId == 0L) continue; // 跳过未关联规格的订单
|
||||
|
||||
List<OrderPO> specOrders = entry.getValue();
|
||||
ProductSkuPO spec = skuMap.get(skuId);
|
||||
|
||||
// 该规格的销售额(计入销售额维度)
|
||||
BigDecimal salesAmount = specOrders.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
// 该规格的订单量(计入销售额维度计单)
|
||||
int orderCount = (int) specOrders.stream()
|
||||
.filter(o -> stat.includesSales(o.getStatus()))
|
||||
.count();
|
||||
|
||||
// 总件数
|
||||
int quantity = specOrders.stream()
|
||||
.mapToInt(o -> {
|
||||
OrderItemPO item = firstItems.get(o.getId());
|
||||
return item != null && item.getQuantity() != null ? item.getQuantity() : 1;
|
||||
})
|
||||
.sum();
|
||||
|
||||
// 客单价
|
||||
BigDecimal avgOV = orderCount > 0
|
||||
? salesAmount.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
// 商品 / 运费 / 其他成本(各维度开关 + 数量,与店铺商品对比一致)
|
||||
BigDecimal productCostTotal = specOrders.stream()
|
||||
.map(stat::productCostForStats)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal shippingCostTotal = specOrders.stream()
|
||||
.map(stat::freightCostForStats)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal otherCostTotal = specOrders.stream()
|
||||
.map(stat::otherCostForStats)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
BigDecimal totalCostStat = specOrders.stream()
|
||||
.map(stat::totalCostForStats)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
// 退款金额(计入退款维度)
|
||||
BigDecimal refundAmount = specOrders.stream()
|
||||
.map(stat::receivedForRefund)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
// 推广费分摊(按该规格订单数占所有订单数比例)
|
||||
int totalOrderCountAll = orders.size();
|
||||
BigDecimal specPromotionFee = BigDecimal.ZERO;
|
||||
if (totalOrderCountAll > 0) {
|
||||
BigDecimal proportion = BigDecimal.valueOf((long) orderCount)
|
||||
.divide(BigDecimal.valueOf(totalOrderCountAll), 4, RoundingMode.HALF_UP);
|
||||
specPromotionFee = totalAttributed.multiply(proportion)
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
// 费比
|
||||
BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? specPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
// 税前净利(与店铺商品对比:销售额 - 订单成本 - 退款金额 - 推广费)
|
||||
BigDecimal profitBeforeTax = salesAmount
|
||||
.subtract(totalCostStat)
|
||||
.subtract(refundAmount)
|
||||
.subtract(specPromotionFee);
|
||||
|
||||
BigDecimal salesTaxAmount = salesTaxOnNetSales(salesAmount, refundAmount, taxRate);
|
||||
|
||||
// ROI = (销售额 - 退款) / 推广费
|
||||
BigDecimal roi = specPromotionFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? salesAmount.subtract(refundAmount)
|
||||
.divide(specPromotionFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
// 税后盈亏
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount);
|
||||
|
||||
ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem();
|
||||
item.setSkuId(skuId);
|
||||
item.setSkuName(spec != null ? spec.getName() : "未知规格");
|
||||
item.setSkuCode(spec != null ? spec.getSkuCode() : null);
|
||||
item.setSalesAmount(salesAmount);
|
||||
item.setOrderCount(orderCount);
|
||||
item.setQuantity(quantity);
|
||||
item.setAverageOrderValue(avgOV);
|
||||
item.setProductCost(productCostTotal);
|
||||
item.setShippingCost(shippingCostTotal);
|
||||
item.setOtherCost(otherCostTotal);
|
||||
item.setOrderCost(totalCostStat);
|
||||
item.setRefundAmount(refundAmount);
|
||||
item.setPromotionFee(specPromotionFee);
|
||||
item.setFeeRatio(feeRatio.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP));
|
||||
item.setProfitBeforeTax(profitBeforeTax);
|
||||
item.setSalesTaxAmount(salesTaxAmount);
|
||||
item.setRoi(roi);
|
||||
item.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
|
||||
specItems.add(item);
|
||||
}
|
||||
|
||||
// 构建合计行
|
||||
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
|
||||
total.setSalesAmount(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getSalesAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOrderCount(specItems.stream()
|
||||
.mapToInt(ProductOverviewVO.SpecSummaryItem::getOrderCount).sum());
|
||||
total.setQuantity(specItems.stream()
|
||||
.mapToInt(ProductOverviewVO.SpecSummaryItem::getQuantity).sum());
|
||||
total.setProductCost(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getProductCost)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setShippingCost(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getShippingCost)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOtherCost(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getOtherCost)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setOrderCost(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getOrderCost)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setRefundAmount(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getRefundAmount)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
total.setPromotionFee(specItems.stream()
|
||||
.map(ProductOverviewVO.SpecSummaryItem::getPromotionFee)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add));
|
||||
|
||||
BigDecimal totalSalesAmt = total.getSalesAmount();
|
||||
BigDecimal totalPromoFee = total.getPromotionFee();
|
||||
BigDecimal totalFeeRatio = totalSalesAmt.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.divide(totalSalesAmt, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
total.setFeeRatio(totalFeeRatio.multiply(new BigDecimal("100"))
|
||||
.setScale(2, RoundingMode.HALF_UP));
|
||||
|
||||
BigDecimal totalProfitBT = total.getSalesAmount()
|
||||
.subtract(total.getOrderCost())
|
||||
.subtract(total.getRefundAmount())
|
||||
.subtract(total.getPromotionFee());
|
||||
total.setProfitBeforeTax(totalProfitBT);
|
||||
|
||||
BigDecimal totalRefundAgg = total.getRefundAmount();
|
||||
BigDecimal totalSalesTax = salesTaxOnNetSales(totalSalesAmt, totalRefundAgg, taxRate);
|
||||
total.setSalesTaxAmount(totalSalesTax);
|
||||
|
||||
BigDecimal totalRefundForRoi = totalRefundAgg;
|
||||
BigDecimal totalRoi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmt.subtract(totalRefundForRoi)
|
||||
.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
total.setRoi(totalRoi);
|
||||
|
||||
total.setProfitAfterTax(totalProfitBT.subtract(totalSalesTax).setScale(2, RoundingMode.HALF_UP));
|
||||
|
||||
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
|
||||
summary.setList(specItems);
|
||||
summary.setTotal(total);
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
private ProductOverviewVO.SpecSummary buildEmptySpecSummary() {
|
||||
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
|
||||
total.setSalesAmount(BigDecimal.ZERO);
|
||||
total.setOrderCount(0);
|
||||
total.setQuantity(0);
|
||||
total.setProductCost(BigDecimal.ZERO);
|
||||
total.setShippingCost(BigDecimal.ZERO);
|
||||
total.setOtherCost(BigDecimal.ZERO);
|
||||
total.setOrderCost(BigDecimal.ZERO);
|
||||
total.setRefundAmount(BigDecimal.ZERO);
|
||||
total.setPromotionFee(BigDecimal.ZERO);
|
||||
total.setFeeRatio(BigDecimal.ZERO);
|
||||
total.setProfitBeforeTax(BigDecimal.ZERO);
|
||||
total.setSalesTaxAmount(BigDecimal.ZERO);
|
||||
total.setRoi(BigDecimal.ZERO);
|
||||
total.setProfitAfterTax(BigDecimal.ZERO);
|
||||
|
||||
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
|
||||
summary.setList(new ArrayList<>());
|
||||
summary.setTotal(total);
|
||||
return summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建各规格销量 Top10
|
||||
*/
|
||||
private List<ProductOverviewVO.SpecSalesRankItem> buildSpecSalesTop10(List<OrderPO> orders,
|
||||
OrderStatusStatSets stat,
|
||||
List<Long> shopIds) {
|
||||
if (orders.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
OrderPO firstOrder = orders.get(0);
|
||||
Long companyId = firstOrder.getCompanyId();
|
||||
Map<Long, OrderItemPO> firstItems = OrderOverviewSupport.firstItemsForOrders(orderItemMapper, orders);
|
||||
OrderItemPO firstItem = firstItems.get(firstOrder.getId());
|
||||
Long productId = firstItem != null ? firstItem.getProductId() : null;
|
||||
if (productId == null && firstItem != null && firstItem.getProductSkuId() != null) {
|
||||
ProductSkuPO firstSpec = productSkuMapper.selectById(firstItem.getProductSkuId());
|
||||
if (firstSpec != null) {
|
||||
productId = firstSpec.getProductId();
|
||||
}
|
||||
}
|
||||
if (productId == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<ProductSkuPO> skuWrapper = new LambdaQueryWrapper<>();
|
||||
skuWrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getProductId, productId);
|
||||
List<ProductSkuPO> allSkus = productSkuMapper.selectList(skuWrapper);
|
||||
Map<Long, ProductSkuPO> skuMap = allSkus.stream()
|
||||
.collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
// 按规格分组计算
|
||||
Map<Long, List<OrderPO>> ordersBySpec = orders.stream()
|
||||
.collect(Collectors.groupingBy(o -> {
|
||||
OrderItemPO item = firstItems.get(o.getId());
|
||||
Long skuId = item != null ? item.getProductSkuId() : null;
|
||||
return skuId != null ? skuId : 0L;
|
||||
}));
|
||||
|
||||
List<ProductOverviewVO.SpecSalesRankItem> rankItems = new ArrayList<>();
|
||||
|
||||
for (Map.Entry<Long, List<OrderPO>> entry : ordersBySpec.entrySet()) {
|
||||
Long skuId = entry.getKey();
|
||||
if (skuId == 0L) continue;
|
||||
|
||||
List<OrderPO> specOrders = entry.getValue();
|
||||
ProductSkuPO spec = skuMap.get(skuId);
|
||||
|
||||
// 订单量(计入销售额维度)
|
||||
int orderCount = (int) specOrders.stream()
|
||||
.filter(o -> stat.includesSales(o.getStatus()))
|
||||
.count();
|
||||
|
||||
// 销售额
|
||||
BigDecimal salesAmount = specOrders.stream()
|
||||
.map(stat::receivedForSales)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem();
|
||||
item.setSkuId(skuId);
|
||||
item.setSkuName(spec != null ? spec.getName() : "未知规格");
|
||||
item.setSkuCode(spec != null ? spec.getSkuCode() : null);
|
||||
item.setOrderCount(orderCount);
|
||||
item.setSalesAmount(salesAmount);
|
||||
rankItems.add(item);
|
||||
}
|
||||
|
||||
// 按订单量降序排序,取前10
|
||||
return rankItems.stream()
|
||||
.sorted(Comparator.comparing(ProductOverviewVO.SpecSalesRankItem::getOrderCount).reversed())
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) {
|
||||
if (prev.signum() > 0) {
|
||||
return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100))
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
return cur.signum() > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.shop.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.overview.model.dto.ShopExportDTO;
|
||||
|
||||
/**
|
||||
* 店铺侧 Excel 导出(按商品汇总、按品类汇总)
|
||||
*/
|
||||
public interface ShopExportService {
|
||||
|
||||
/** 单店铺按商品维度汇总 Excel */
|
||||
byte[] exportShopSummaryByProduct(ShopExportDTO dto);
|
||||
|
||||
/** 单店铺按品类维度汇总 Excel(与品类概览导出逻辑一致) */
|
||||
byte[] exportShopSummaryByCategory(CategoryExportDTO dto);
|
||||
}
|
||||
Reference in New Issue
Block a user