refactor: 完全迁移店铺概览和商品概览到bi层

This commit is contained in:
2026-08-13 09:31:07 +08:00
parent 44fb58b878
commit 9af2efaf31
76 changed files with 2020 additions and 7419 deletions
+5 -7
View File
@@ -75,13 +75,11 @@ ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/
| 模块 | 路径 | 说明 |
|------|------|------|
| 全店概览统计 | POST /ec/store/overview | 全店铺汇总统计 |
| 全店概览-按店铺汇总导出 | POST /ec/store-overview/export/by-shop | Excel |
| 全店概览-按品类汇总导出 | POST /ec/store-overview/export/by-category | Excel |
| 全店概览-按平台汇总导出 | POST /ec/store-overview/export/by-platform | Excel |
| 店铺概览 | POST /ec/shop/overview-statistics | 单店铺统计 |
| 店铺按商品汇总导出 | POST /ec/shop/export/summary-by-product | Excel |
| 店铺按品类汇总导出 | POST /ec/shop/export/summary-by-category | Excel |
| 工作台 | /api/bi/workbench/* | 经营工作台 |
| 店铺概览 | POST /api/bi/shop/overview | 单店铺统计 |
| 店铺按商品汇总导出 | POST /api/bi/shop/export/summary-by-product | Excel |
| 店铺按品类汇总导出 | POST /api/bi/shop/export/summary-by-category | Excel |
| 商品概览 | POST /api/bi/product/overview | 单商品统计 |
| 订单 | /ec/order/* | CRUD |
| 推广费 | /ec/promotion-fee/* | CRUD |
| 刷单 | /ec/brush-order/* | CRUD |
@@ -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());
}
@@ -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,
@@ -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,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,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,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,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;
@@ -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(无趋势表)。
*
@@ -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);
}
@@ -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);
}
@@ -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);
@@ -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;
}
}
}
@@ -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,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,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;
@@ -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,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,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;
@@ -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);
}
@@ -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;
}
}
@@ -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;
}
@@ -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,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,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,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;
@@ -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);
}
@@ -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);
}
@@ -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);
@@ -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;
}
}
@@ -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 订单日汇聚)")
@@ -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/趋势/饼图 + 底部四张汇总表。
@@ -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,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;
@@ -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;
@@ -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;
@@ -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;
@@ -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);
}
}
@@ -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());
}
}
}
@@ -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");
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
@@ -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);
}
}
@@ -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);
}
@@ -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;
}
}
@@ -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);
}
@@ -337,10 +337,6 @@ INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `co
SELECT 12010, NULL, 0, '工作台', '工作台', '/dashboard/workbench', '/dashboard/workbench/index', '', 'icon-park-outline:workbench', 'menu', 1, 1, 1, 1
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '工作台');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12011, NULL, 0, '全店概览', '全店概览', '/store-overview', '/dashboard/store-overview/index', '', 'lucide:line-chart', 'menu', 0, 1, 1, 2
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '全店概览');
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 12012, NULL, 0, '订单导入', '订单导入', '/import/order', '/ecommerce/import/order/index', '', 'lucide:upload', 'menu', 1, 1, 0, 3
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `name` = '订单导入');
@@ -11,7 +11,7 @@ import { requestClient } from '#/api/request';
*/
export async function getProductOverviewApi(params: ProductOverviewDTO.Query) {
return requestClient.post<ProductOverviewVO.Overview>(
'/ec/product/overview',
'/bi/product/overview',
params,
);
}
@@ -62,6 +62,20 @@ export async function getShopProductPageApi(
);
}
/**
* 店铺概览统计(BI:Mongo 订单日汇聚)
*/
export async function getShopOverviewApi(params: {
shopId: number;
dateRange: string[];
taxRate?: number;
}) {
return requestClient.post<ShopVO.OverviewStatistics>(
'/bi/shop/overview',
params,
);
}
/**
* 店铺数据统计-按商品汇总(Excel)
*/
@@ -70,20 +84,7 @@ export async function exportShopSummaryByProductApi(params: {
dateRange: string[];
exportType?: string;
}) {
return requestClient.post('/ec/shop/export/summary-by-product', params, {
responseType: 'blob',
});
}
/**
* 全店概览-按店铺汇总(Excel)
*/
export async function exportCompanyOverviewApi(params: {
dateRange: string[];
shopIds?: number[];
exportType?: string;
}) {
return requestClient.post('/ec/store-overview/export/by-shop', params, {
return requestClient.post('/bi/shop/export/summary-by-product', params, {
responseType: 'blob',
});
}
@@ -1,43 +0,0 @@
import type { CompanyOverviewDTO, CompanyOverviewVO } from './types';
import { requestClient } from '#/api/request';
/**
* 全店概览 API(统计与导出)
*/
/**
* 获取全店概览统计数据
*/
export async function getCompanyOverviewApi(data: CompanyOverviewDTO.Query) {
return requestClient.post<CompanyOverviewVO.Info>(
'/ec/store/overview',
data,
);
}
/**
* 全店概览-按品类汇总(Excel)
*/
export async function exportCategoryOverviewApi(params: {
dateRange: string[];
categoryIds?: number[];
taxRate: number;
}) {
return requestClient.post('/ec/store-overview/export/by-category', params, {
responseType: 'blob',
});
}
/**
* 全店概览-按店铺汇总(Excel)
*/
export async function exportCompanyOverviewApi(params: {
dateRange: string[];
shopIds?: number[];
exportType?: string;
}) {
return requestClient.post('/ec/store-overview/export/by-shop', params, {
responseType: 'blob',
});
}
@@ -1,6 +1,4 @@
/**
* 全店铺概览管理模块API导出
* 工作台底表等复用的汇总表类型(原全店概览 VO,页面已下线)。
*/
export * from './apis';
export * from './types';
@@ -1,6 +1,4 @@
/**
* 全店铺概览管理模块类型定义导出
* 工作台汇总表类型(原全店概览 VO 字段,页面已下线)。
*/
export * from './types.dto';
export * from './types.vo';
@@ -1,13 +0,0 @@
/**
* 全店铺概览相关DTO类型定义
*/
export namespace CompanyOverviewDTO {
/** 全店铺概览查询参数 */
export interface Query {
/** 日期范围数组(第一个是开始日期,第二个是结束日期,只有一个日期则返回当天数据) */
dateRange: string[];
/** 税率(默认0.04,即4%) */
taxRate?: number;
}
}
@@ -257,7 +257,7 @@ export namespace CompanyOverviewVO {
categories: CategorySummary[];
}
/** 工作台底部四张汇总表(与全店概览同源字段) */
/** 工作台底部四张汇总表 */
export interface WorkbenchTableBundle {
shopTable?: ShopOverview | null;
platformTable?: PlatformOverview | null;
@@ -20,7 +20,6 @@
"title": "Dashboard",
"analytics": "Analytics",
"workspace": "Workspace",
"storeOverview": "Store overview",
"workbench": "E-commerce operations workbench"
}
}
@@ -20,7 +20,6 @@
"title": "概览",
"analytics": "分析页",
"workspace": "工作台",
"storeOverview": "全店概览",
"workbench": "电商运营工作台"
}
}
@@ -12,34 +12,16 @@ const routes: RouteRecordRaw[] = [
name: 'Dashboard',
path: '/dashboard',
children: [
{
name: 'Analytics',
path: '/store-overview',
component: () => import('#/views/dashboard/store-overview/index.vue'),
meta: {
affixTab: true,
icon: 'lucide:area-chart',
title: $t('page.dashboard.storeOverview'),
},
},
{
name: 'PddWorkbench',
path: '/workbench',
component: () => import('#/views/dashboard/workbench/index.vue'),
meta: {
affixTab: true,
icon: 'lucide:gauge',
title: $t('page.dashboard.workbench'),
},
},
// {
// name: 'Workspace',
// path: '/workspace',
// component: () => import('#/views/dashboard/workspace/index.vue'),
// meta: {
// icon: 'carbon:workspace',
// title: $t('page.dashboard.workspace'),
// },
// },
],
},
];
@@ -53,7 +53,7 @@ export type OverviewRouteQuery = {
shopId?: string;
};
/** 概览页跳转(店铺/商品)时附带的 query,与全店概览一致 */
/** 概览页跳转(店铺/商品)时附带的 query,与工作台筛选一致 */
export function buildOverviewRouteQuery(
dateRange: [Dayjs, Dayjs],
options?: { shopId?: number },
@@ -1,5 +1,5 @@
/**
* 店铺/全店概览接口:费比 feeRatio / averageFeeRatio 为小数(推广费÷销售额,如 0.05 = 5%)。
* 店铺/工作台接口:费比 feeRatio / averageFeeRatio 为小数(推广费÷销售额,如 0.05 = 5%)。
* 达成率等字段后端已为 0–100 的数值,勿用本函数。
*/
export function formatFeeRatioPercent(value: number | undefined | null): string {
@@ -1,322 +0,0 @@
<script lang="ts" setup>
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { computed } from 'vue';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import { formatIntCell, formatNumberCell } from '#/utils/overview-table-cells';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import {
salesTaxColumnHint,
storeOverviewHints,
} from '#/utils/overview-table-hints';
defineOptions({ name: 'CategoryComparisonTable' });
interface Props {
categorySummary?: CompanyOverviewVO.CategoryOverview;
taxRate: number;
categoryExportMode?: boolean;
selectedExportCategoryIds?: number[];
headingTitle?: string;
headingSubtitle?: string;
/** 首列维度名称,如「品类」「商品」 */
firstColumnLabel?: string;
}
interface Emits {
(e: 'update:selectedExportCategoryIds', ids: number[]): void;
(e: 'toggleCategoryExportMode', enabled: boolean): void;
(e: 'export'): void;
}
const props = withDefaults(defineProps<Props>(), {
categoryExportMode: false,
selectedExportCategoryIds: () => [],
headingTitle: '各品类多维度经营明细汇总',
headingSubtitle: '包含:规模、成本及最终损益所有维度',
firstColumnLabel: '品类',
});
const emit = defineEmits<Emits>();
const allCategoriesSelected = computed(() => {
const total = props.categorySummary?.categories?.length || 0;
return total > 0 && props.selectedExportCategoryIds.length === total;
});
const someCategoriesSelected = computed(() => {
return props.selectedExportCategoryIds.length > 0;
});
const formatAmount = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const cellMoney = (v: number | null | undefined) => formatNumberCell(v, formatAmount);
const cellRoi = (v: number | null | undefined) =>
formatNumberCell(v, (n) => n.toFixed(2));
</script>
<template>
<div
class="overflow-hidden rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div
class="flex flex-col items-start justify-between gap-4 border-b border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] p-8 md:flex-row md:items-center"
>
<div>
<h3 class="text-xl font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ props.headingTitle }}
</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ props.headingSubtitle }}
</p>
</div>
<div class="flex items-center gap-3">
<template v-if="categoryExportMode">
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('toggleCategoryExportMode', false)"
>
取消选择
</button>
<button
class="rounded-2xl bg-blue-600 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
:disabled="selectedExportCategoryIds.length === 0"
@click="emit('export')"
>
导出已选品类 ({{ selectedExportCategoryIds.length }})
</button>
</template>
<template v-else>
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('toggleCategoryExportMode', true)"
>
指定品类导出
</button>
<button
class="rounded-2xl bg-slate-900 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
@click="emit('export')"
>
导出全部
</button>
</template>
</div>
</div>
<div class="table-container overflow-x-auto">
<table class="w-full whitespace-nowrap text-left text-sm">
<thead
class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-xs font-black uppercase text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<tr>
<th
v-if="categoryExportMode"
rowspan="2"
class="border-b border-r border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] p-3 text-center"
>
<input
type="checkbox"
:checked="allCategoriesSelected"
:indeterminate="someCategoriesSelected && !allCategoriesSelected"
class="h-4 w-4 cursor-pointer accent-blue-600"
@change="
emit(
'update:selectedExportCategoryIds',
allCategoriesSelected
? []
: (categorySummary?.categories ?? []).map((c) => c.categoryId!)
)
"
/>
</th>
<th
rowspan="2"
class="sticky-col border-b p-6 text-base font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)] border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-sm dark:shadow-none"
>
{{ props.firstColumnLabel }}
</th>
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
经营规模维度
</th>
<th
colspan="8"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50%)] p-3 text-center text-orange-700 dark:text-orange-400"
>
成本费用维度
</th>
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-3 text-center text-emerald-700 dark:text-emerald-400"
>
盈利分析维度
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<th class="border-b border-l px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<th class="border-b border-l px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.totalPromotionFee">推广费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-orange-600 dark:text-orange-400">
<OverviewColumnHint :title="storeOverviewHints.brushFee">刷单费用</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="storeOverviewHints.feeRatioCategoryRow">费比%</OverviewColumnHint>
</th>
<th class="border-b border-l px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
<OverviewColumnHint :title="salesTaxColumnHint(taxRate)">
{{ (taxRate * 100).toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-black text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="storeOverviewHints.roi">ROI</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="cat in (categorySummary?.categories || [])"
:key="cat.categoryId ?? 'uncategorized'"
class="transition-colors hover:bg-blue-50/50 dark:hover:bg-[hsl(217.2deg_32.6%_17.5%/30%)] dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)]"
>
<td
v-if="categoryExportMode"
class="border-b border-r border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-white p-3 text-center dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<input
type="checkbox"
:checked="selectedExportCategoryIds.includes(cat.categoryId!)"
class="h-4 w-4 cursor-pointer accent-blue-600"
@change="
(e) => {
const checked = (e.target as HTMLInputElement).checked;
emit(
'update:selectedExportCategoryIds',
checked
? [...selectedExportCategoryIds, cat.categoryId!]
: selectedExportCategoryIds.filter((id) => id !== cat.categoryId)
);
}
"
/>
</td>
<td class="sticky-col border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 font-bold shadow-sm dark:shadow-none">
<span class="inline-block rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400 transition-colors hover:text-blue-300 hover:underline">
{{ cat.categoryName }}
</span>
</td>
<td class="p-6 font-black">{{ formatAmount(cat.salesAmount) }}</td>
<td class="p-6 font-medium">{{ formatIntCell(cat.orderCount) }}</td>
<td class="p-6 font-medium">
{{ cellMoney(cat.averageOrderValue) }}
</td>
<td class="p-6">{{ cellMoney(cat.productCost) }}</td>
<td class="p-6">{{ cellMoney(cat.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(cat.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(cat.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(cat.refundAmount) }}
</td>
<td class="p-6">{{ cellMoney(cat.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">
{{ cellMoney(cat.brushFee) }}
</td>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cat.feeRatio !== undefined ? formatFeeRatioPercent(cat.feeRatio) : '-' }}
</td>
<td class="p-6 font-bold">
{{ cellMoney(cat.totalProfitBeforeTax) }}
</td>
<td class="p-6 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cellMoney(cat.salesTaxAmount) }}
</td>
<td class="p-6 font-black text-indigo-700 dark:text-indigo-400">
{{ cellRoi(cat.roi) }}
</td>
<td class="bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-6 text-base font-black text-emerald-600">
{{ cellMoney(cat.profitAfterTax) }}
</td>
</tr>
<tr v-if="!categorySummary?.categories?.length">
<td :colspan="categoryExportMode ? 18 : 17" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
</tbody>
<!-- 合计行 -->
<tfoot v-if="categorySummary?.total" class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="p-6 text-base">合计</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(categorySummary?.total?.salesAmount) }}</td>
<td class="p-6">{{ formatIntCell(categorySummary?.total?.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(categorySummary?.total?.averageOrderValue) }}
</td>
<!-- 成本 -->
<td class="p-6">{{ cellMoney(categorySummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(categorySummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(categorySummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(categorySummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(categorySummary?.total?.brushFee) }}</td>
<td class="p-6 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ categorySummary?.total?.feeRatio !== undefined ? formatFeeRatioPercent(categorySummary?.total?.feeRatio) : '-' }}</td>
<!-- 盈利 -->
<td class="p-6">{{ cellMoney(categorySummary?.total?.totalProfitBeforeTax) }}</td>
<td class="p-6 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoney(categorySummary?.total?.salesTaxAmount) }}</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">{{ cellRoi(categorySummary?.total?.roi) }}</td>
<td
class="bg-emerald-100 p-6 text-base dark:bg-emerald-950"
:class="(categorySummary?.total?.profitAfterTax ?? 0) < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-700 dark:text-emerald-300'"
>{{ cellMoney(categorySummary?.total?.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
@@ -1,159 +0,0 @@
<script lang="ts" setup>
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { ref, watch } from 'vue';
import { Segmented } from 'ant-design-vue';
import CategoryComparisonTable from './CategoryComparisonTable.vue';
import PlatformSummaryCard from './PlatformSummaryCard.vue';
import ShopComparisonTable from './ShopComparisonTable.vue';
defineOptions({ name: 'ComparisonSwitcher' });
interface Props {
taxRate: number;
platformSummary?: CompanyOverviewVO.PlatformOverview;
platformExportMode: boolean;
selectedExportPlatformCodes: string[];
shopSummary?: CompanyOverviewVO.ShopOverview;
shopExportMode: boolean;
selectedExportShopIds: number[];
categorySummary?: CompanyOverviewVO.CategoryOverview;
categoryExportMode: boolean;
selectedExportCategoryIds: number[];
}
interface Emits {
(e: 'update:selectedExportPlatformCodes', codes: string[]): void;
(e: 'togglePlatformExportMode', enabled: boolean): void;
(e: 'platformExport'): void;
(e: 'update:selectedExportShopIds', ids: number[]): void;
(e: 'toggleShopExportMode', enabled: boolean): void;
(e: 'shopExport'): void;
(e: 'navigate', shopId: number): void;
(e: 'update:selectedExportCategoryIds', ids: number[]): void;
(e: 'toggleCategoryExportMode', enabled: boolean): void;
(e: 'categoryExport'): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const STORAGE_KEY = 'store-overview-tab';
const getDefaultMode = (): 'platform' | 'shop' | 'category' => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'platform' || stored === 'shop' || stored === 'category') return stored;
return 'shop';
};
const activeMode = ref<'platform' | 'shop' | 'category'>(getDefaultMode());
watch(activeMode, (val) => localStorage.setItem(STORAGE_KEY, val));
const modeOptions = [
{ label: '店铺汇总', value: 'shop' },
{ label: '平台汇总', value: 'platform' },
{ label: '品类汇总', value: 'category' },
];
</script>
<template>
<div class="space-y-4">
<div class="flex justify-end">
<Segmented
v-model:value="activeMode"
:options="modeOptions"
class="comparison-segmented"
/>
</div>
<PlatformSummaryCard
v-if="activeMode === 'platform'"
:platform-summary="props.platformSummary"
:tax-rate="props.taxRate"
:platform-export-mode="props.platformExportMode"
:selected-export-platform-codes="props.selectedExportPlatformCodes"
@update:selected-export-platform-codes="
(codes) => emit('update:selectedExportPlatformCodes', codes)
"
@toggle-platform-export-mode="
(enabled) => emit('togglePlatformExportMode', enabled)
"
@export="emit('platformExport')"
/>
<ShopComparisonTable
v-if="activeMode === 'shop'"
:shop-summary="props.shopSummary"
:tax-rate="props.taxRate"
:shop-export-mode="props.shopExportMode"
:selected-export-shop-ids="props.selectedExportShopIds"
@update:selected-export-shop-ids="
(ids) => emit('update:selectedExportShopIds', ids)
"
@toggle-shop-export-mode="(enabled) => emit('toggleShopExportMode', enabled)"
@export="emit('shopExport')"
@navigate="(shopId) => emit('navigate', shopId)"
/>
<CategoryComparisonTable
v-if="activeMode === 'category'"
:category-summary="props.categorySummary"
:tax-rate="props.taxRate"
:category-export-mode="props.categoryExportMode"
:selected-export-category-ids="props.selectedExportCategoryIds"
@toggle-category-export-mode="
(enabled) => emit('toggleCategoryExportMode', enabled)
"
@update:selected-export-category-ids="
(ids) => emit('update:selectedExportCategoryIds', ids)
"
@export="emit('categoryExport')"
/>
</div>
</template>
<style scoped>
:deep(.ant-segmented-thumb) {
border-radius: 999px !important;
}
:deep(.comparison-segmented) {
background: rgb(148 163 184 / 16%);
border-radius: 999px;
padding: 4px;
}
:deep(.comparison-segmented .ant-segmented-item) {
border-radius: 999px;
}
:deep(.comparison-segmented .ant-segmented-item-label) {
font-weight: 700;
padding: 6px 16px;
border-radius: 999px;
}
:deep(.comparison-segmented .ant-segmented-item-selected) {
background: white;
color: #1d4ed8;
box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
}
:global(html.dark) :deep(.comparison-segmented) {
background: hsl(240deg 3.7% 22% / 70%);
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item) {
border-radius: 999px;
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item) {
color: hsl(240deg 5% 64.9%);
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item-selected) {
background: hsl(220deg 13% 18%);
color: #60a5fa;
box-shadow: 0 1px 3px hsl(0 0 0% / 30%);
}
</style>
@@ -1,142 +0,0 @@
<script lang="ts" setup>
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
defineOptions({ name: 'KpiCards' });
interface Props {
overviewData: CompanyOverviewVO.Info | null;
taxRate: number;
}
const props = defineProps<Props>();
void props; // kept for template compatibility
const formatAmount = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
const formatPercentPlain = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value.toFixed(1)}%`;
};
</script>
<template>
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-4">
<!-- 销售额 -->
<div
class="rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div class="mb-4 flex items-start justify-between">
<span class="text-xs font-black text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
全店总销售额
</span>
<span
v-if="overviewData?.monthOverMonthGrowth !== undefined"
class="rounded bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-2 py-1 text-xs font-bold text-emerald-600"
>
{{ formatPercent(overviewData.monthOverMonthGrowth) }} 较上月
</span>
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{
overviewData?.totalSalesAmount
? formatAmount(overviewData.totalSalesAmount)
: '-'
}}
</div>
<div
v-if="overviewData?.salesAmountAchievementRate !== undefined"
class="mt-6 flex items-center justify-between border-t border-slate-100 dark:border-t-[hsl(240deg_3.7%_22%)] pt-4"
>
<span class="text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
销售额目标达成率
</span>
>
<span class="text-sm font-black text-blue-600 dark:text-blue-400 dark:text-blue-400">
{{
formatPercentPlain(overviewData.salesAmountAchievementRate)
}}
</span>
</div>
</div>
<!-- ROI效率 -->
<div
class="rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div class="mb-4 text-xs font-black text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
投资回报率 (ROI)
</div>
<div class="text-4xl font-black leading-none text-indigo-600 dark:text-indigo-400">
{{ overviewData?.totalROI?.toFixed(2) || '-' }}
</div>
<div
v-if="overviewData?.averageFeeRatio !== undefined"
class="mt-6 flex justify-between border-t border-slate-100 dark:border-t-[hsl(240deg_3.7%_22%)] pt-4 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
<span>全店平均费比</span>
<span class="text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ formatFeeRatioPercent(overviewData.averageFeeRatio) }}
</span>
</div>
</div>
<!-- 订单达成 -->
<div
class="rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div class="mb-4 text-xs font-black text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
销量目标达成率 (订单数)
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{
overviewData?.orderCountAchievementRate !== undefined
? formatPercentPlain(overviewData.orderCountAchievementRate)
: '-'
}}
</div>
<div
v-if="overviewData?.orderCountAchievementRate !== undefined"
class="mt-6 h-2 w-full overflow-hidden rounded-full bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]"
>
<div
class="h-full bg-indigo-500"
:style="{
width: `${Math.min(overviewData.orderCountAchievementRate, 100)}%`,
}"
></div>
</div>
</div>
<!-- 税后利润 -->
<div
class="rounded-2xl border-l-4 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] border-l-emerald-500 dark:border-l-emerald-500 bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div class="mb-4 text-xs font-black text-emerald-600 dark:text-emerald-400">
全店总净利润 (税后)
</div>
<div class="text-4xl font-black leading-none text-emerald-600 dark:text-emerald-400">
{{
overviewData?.totalNetProfitAfterTax
? formatAmount(overviewData.totalNetProfitAfterTax)
: '-'
}}
</div>
<div
v-if="overviewData?.totalTaxAmount !== undefined"
class="mt-6 flex justify-between border-t border-slate-100 dark:border-t-[hsl(240deg_3.7%_22%)] pt-4 text-[11px] font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
<span>已扣除预扣税额 ({{ (taxRate * 100).toFixed(0) }}%)</span>
<span>{{ formatAmount(overviewData.totalTaxAmount) }}</span>
</div>
</div>
</div>
</template>
@@ -1,424 +0,0 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import { formatIntCell, formatNumberCell } from '#/utils/overview-table-cells';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import {
salesTaxColumnHint,
storeOverviewHints,
} from '#/utils/overview-table-hints';
defineOptions({ name: 'PlatformSummaryCard' });
interface Props {
taxRate?: number;
platformSummary?: CompanyOverviewVO.PlatformOverview;
platformExportMode?: boolean;
selectedExportPlatformCodes?: string[];
headingTitle?: string;
headingSubtitle?: string;
}
interface Emits {
(e: 'update:selectedExportPlatformCodes', codes: string[]): void;
(e: 'togglePlatformExportMode', enabled: boolean): void;
(e: 'export'): void;
}
const props = withDefaults(defineProps<Props>(), {
platformExportMode: false,
selectedExportPlatformCodes: () => [],
headingTitle: '各平台多维度经营明细汇总',
headingSubtitle: '目标达成 · 规模 · 成本费用 · 盈利分析,四大维度完整汇总',
});
const emit = defineEmits<Emits>();
const allPlatformsSelected = computed(() => {
const total = platformData.value.length;
return total > 0 && props.selectedExportPlatformCodes.length === total;
});
const somePlatformsSelected = computed(() => {
return props.selectedExportPlatformCodes.length > 0;
});
const formatAmount = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const cellMoney = (v: number | null | undefined) => formatNumberCell(v, formatAmount);
const cellRoi = (v: number | null | undefined) =>
formatNumberCell(v, (n) => n.toFixed(2));
const formatPercentPlain = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value.toFixed(1)}%`;
};
const taxRateNum = computed(() => (props.taxRate ?? 0.04) * 100);
// 使用后端返回的平台列表数据
const platformData = computed(() => {
if (props.platformSummary?.platforms && props.platformSummary.platforms.length > 0) {
return props.platformSummary.platforms.map(p => ({
platformCode: p.platformCode,
platformName: p.platformName,
targetOrderCount: p.targetOrderCount ?? 0,
orderCountAchievementRate: p.orderCountAchievementRate ?? 0,
targetAmount: p.targetAmount ?? 0,
salesAmountAchievementRate: p.salesAmountAchievementRate ?? 0,
salesAmount: p.salesAmount ?? 0,
orderCount: p.orderCount ?? 0,
averageOrderValue: p.averageOrderValue ?? 0,
productCost: p.productCost ?? 0,
shippingCost: p.shippingCost ?? 0,
otherCost: p.otherCost ?? 0,
orderCost: p.orderCost ?? 0,
refundAmount: p.refundAmount ?? 0,
totalPromotionFee: p.totalPromotionFee ?? 0,
brushFee: p.brushFee ?? 0,
feeRatio: p.feeRatio ?? 0,
totalProfitBeforeTax: p.totalProfitBeforeTax ?? 0,
salesTaxAmount: p.salesTaxAmount ?? 0,
roi: p.roi ?? 0,
profitAfterTax: p.profitAfterTax ?? 0,
}));
}
return [];
});
// 后端返回的合计行数据
const totalData = computed(() => props.platformSummary?.total ?? null);
// 表格排序
const sortField = ref<string>('salesAmount');
const sortOrder = ref<'asc' | 'desc'>('desc');
const sortedData = computed(() => {
return [...platformData.value].sort((a: any, b: any) => {
const diff = b[sortField.value] - a[sortField.value];
return sortOrder.value === 'desc' ? diff : -diff;
});
});
</script>
<template>
<div
class="overflow-hidden rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<!-- Header -->
<div
class="flex flex-col items-start justify-between gap-4 border-b border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] p-8 md:flex-row md:items-center"
>
<div>
<h3 class="text-xl font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ props.headingTitle }}
</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ props.headingSubtitle }}
</p>
</div>
<div class="flex items-center gap-3">
<template v-if="platformExportMode">
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('togglePlatformExportMode', false)"
>
取消选择
</button>
<button
class="rounded-2xl bg-blue-600 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
:disabled="selectedExportPlatformCodes.length === 0"
@click="emit('export')"
>
导出已选平台 ({{ selectedExportPlatformCodes.length }})
</button>
</template>
<template v-else>
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('togglePlatformExportMode', true)"
>
指定平台导出
</button>
<button
class="rounded-2xl bg-slate-900 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
@click="emit('export')"
>
导出全部
</button>
</template>
</div>
</div>
<!-- 表格 -->
<div class="overflow-x-auto">
<table class="w-full whitespace-nowrap text-left text-sm">
<thead
class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-xs font-black uppercase text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<tr>
<th
v-if="platformExportMode"
rowspan="2"
class="border-b border-r-2 border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-slate-100 p-3 text-center dark:bg-[hsl(240deg_3.7%_22%)]"
>
<input
type="checkbox"
class="h-4 w-4 cursor-pointer accent-blue-600"
:checked="allPlatformsSelected"
:indeterminate="somePlatformsSelected && !allPlatformsSelected"
@change="
(e) => {
if ((e.target as HTMLInputElement).checked) {
emit(
'update:selectedExportPlatformCodes',
platformData.map((p) => p.platformCode) || [],
);
} else {
emit('update:selectedExportPlatformCodes', []);
}
}
"
/>
</th>
<!-- 平台名著 -->
<th
rowspan="2"
class="sticky-col border-b border-r-2 border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 text-base font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)] shadow-sm dark:shadow-none"
>
平台
</th>
<!-- 目标达成 -->
<th
colspan="4"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] p-3 text-center bg-blue-50/50 dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)] text-blue-700 dark:text-blue-400"
>
目标达成维度
</th>
<!-- 规模 -->
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] p-3 text-center bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)]"
>
经营规模维度
</th>
<!-- 成本 -->
<th
colspan="8"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] p-3 text-center bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50%)] text-orange-700 dark:text-orange-400"
>
成本费用维度
</th>
<!-- 盈利 -->
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] p-3 text-center bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] text-emerald-700 dark:text-emerald-400"
>
盈利分析维度
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<!-- 目标子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.targetOrderCount">
目标单量
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 text-blue-600 dark:text-blue-400">
<OverviewColumnHint :title="storeOverviewHints.orderCountAchievementRate">
单量达成率
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.targetAmount">目标额</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 text-blue-600 dark:text-blue-400">
<OverviewColumnHint :title="storeOverviewHints.salesAmountAchievementRate">
销售达成率
</OverviewColumnHint>
</th>
<!-- 规模子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<!-- 成本子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.totalPromotionFee">推广费</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 text-orange-600 dark:text-orange-400">
<OverviewColumnHint :title="storeOverviewHints.brushFee">刷单费用</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="storeOverviewHints.feeRatioPlatform">费比%</OverviewColumnHint>
</th>
<!-- 盈利子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="salesTaxColumnHint(taxRate ?? 0.04)">
{{ taxRateNum.toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="storeOverviewHints.roi">ROI</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="p in sortedData"
:key="p.platformCode"
class="transition-colors hover:bg-blue-50/50 dark:hover:bg-[hsl(217.2deg_32.6%_17.5%/30%)] dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)]"
>
<td
v-if="platformExportMode"
class="border-r border-slate-100 dark:border-r-[hsl(240deg_3.7%_22%)] bg-slate-50/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
<input
type="checkbox"
class="h-4 w-4 cursor-pointer accent-blue-600"
:checked="selectedExportPlatformCodes.includes(p.platformCode)"
@change="
(e) => {
const checked = (e.target as HTMLInputElement).checked;
const newIds = checked
? [...selectedExportPlatformCodes, p.platformCode]
: selectedExportPlatformCodes.filter((id) => id !== p.platformCode);
emit('update:selectedExportPlatformCodes', newIds);
}
"
/>
</td>
<!-- 平台名 -->
<td
class="sticky-col border-r-2 border-slate-100 dark:border-r-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 font-bold shadow-sm dark:shadow-none"
>
<span class="inline-block rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400">
{{ p.platformName }}
</span>
</td>
<!-- 目标 -->
<td class="p-6 font-medium">{{ p.targetOrderCount.toLocaleString('zh-CN') }}</td>
<td class="p-6 font-black text-blue-600 dark:text-blue-400">{{ formatPercentPlain(p.orderCountAchievementRate) }}</td>
<td class="p-6 font-medium">{{ formatAmount(p.targetAmount) }}</td>
<td class="p-6 font-black text-blue-600 dark:text-blue-400">{{ formatPercentPlain(p.salesAmountAchievementRate) }}</td>
<!-- 规模 -->
<td class="p-6 font-black">{{ formatAmount(p.salesAmount) }}</td>
<td class="p-6 font-medium">{{ p.orderCount.toLocaleString('zh-CN') }}</td>
<td class="p-6 font-medium">{{ formatAmount(p.averageOrderValue) }}</td>
<!-- 成本 -->
<td class="p-6">{{ formatAmount(p.productCost) }}</td>
<td class="p-6">{{ formatAmount(p.shippingCost) }}</td>
<td class="p-6">{{ formatAmount(p.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ formatAmount(p.orderCost) }}</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">{{ formatAmount(p.refundAmount) }}</td>
<td class="p-6">{{ formatAmount(p.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ formatAmount(p.brushFee) }}</td>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatFeeRatioPercent(p.feeRatio) }}</td>
<!-- 盈利 -->
<td class="p-6 font-bold" :class="p.totalProfitBeforeTax >= 0 ? 'text-slate-800 dark:text-[hsl(0deg_0%_95%)]' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(p.totalProfitBeforeTax) }}
</td>
<td class="p-6 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatAmount(p.salesTaxAmount) }}</td>
<td class="p-6 font-black text-indigo-700 dark:text-indigo-400">{{ p.roi.toFixed(2) }}</td>
<td
class="bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-6 text-base font-black"
:class="p.profitAfterTax >= 0 ? 'text-emerald-600' : 'text-rose-600'"
>
{{ formatAmount(p.profitAfterTax) }}
</td>
</tr>
</tbody>
<!-- 合计行 -->
<tfoot v-if="totalData" class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="sticky-col border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] p-6 text-base">合计</td>
<!-- 目标 -->
<td class="p-6">{{ formatIntCell(totalData.targetOrderCount) }}</td>
<td class="p-6 text-blue-600 dark:text-blue-400">
{{ totalData.orderCountAchievementRate !== undefined ? formatPercentPlain(totalData.orderCountAchievementRate) : '-' }}
</td>
<td class="p-6">{{ cellMoney(totalData.targetAmount) }}</td>
<td class="p-6 text-blue-600 dark:text-blue-400">
{{ totalData.salesAmountAchievementRate !== undefined ? formatPercentPlain(totalData.salesAmountAchievementRate) : '-' }}
</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(totalData.salesAmount) }}</td>
<td class="p-6">{{ formatIntCell(totalData.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(totalData.averageOrderValue) }}
</td>
<!-- 成本 -->
<td class="p-6">{{ cellMoney(totalData.productCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(totalData.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(totalData.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(totalData.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(totalData.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(totalData.brushFee) }}</td>
<td class="p-6 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
{{ totalData.feeRatio !== undefined ? formatFeeRatioPercent(totalData.feeRatio) : '-' }}
</td>
<!-- 盈利 -->
<td class="p-6">
{{ cellMoney(totalData.totalProfitBeforeTax) }}
</td>
<td class="p-6 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cellMoney(totalData.salesTaxAmount) }}
</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">
{{ cellRoi(totalData.roi) }}
</td>
<td
class="bg-emerald-100 p-6 text-base dark:bg-emerald-950"
:class="(totalData.profitAfterTax ?? 0) >= 0 ? 'text-emerald-700 dark:text-emerald-300' : 'text-rose-600 dark:text-rose-400'"
>
{{ cellMoney(totalData.profitAfterTax) }}
</td>
</tr>
</tfoot>
<tfoot v-else class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="text-center text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<td :colspan="platformExportMode ? 22 : 21" class="p-6">暂无数据</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
@@ -1,275 +0,0 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { nextTick, onMounted, ref, watch } from 'vue';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import dayjs from 'dayjs';
defineOptions({ name: 'ShopCharts' });
interface Props {
shopSalesRatios?: CompanyOverviewVO.ShopSalesRatio[];
shopSummary?: CompanyOverviewVO.ShopOverview;
salesAmountTrend?: CompanyOverviewVO.TrendData;
orderCountTrend?: CompanyOverviewVO.TrendData;
}
const props = defineProps<Props>();
const barChartRef = ref<EchartsUIType>();
const trendChartRef = ref<EchartsUIType>();
const { renderEcharts: renderBarChart } = useEcharts(barChartRef);
const { renderEcharts: renderTrendChart } = useEcharts(trendChartRef);
const formatAmount = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
// 渲染店铺销售占比排行图表
const renderShopBarChart = () => {
if (!barChartRef.value || !props.shopSalesRatios) return;
const ratios = props.shopSalesRatios;
const shopNames = ratios.map((r) => r.shopName).reverse();
const salesAmounts = ratios.map((r) => r.salesAmount).reverse();
const isDark = document.documentElement.classList.contains('dark');
renderBarChart({
grid: {
left: '3%',
right: '12%',
bottom: '3%',
top: '3%',
containLabel: true,
},
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
textStyle: { color: isDark ? 'hsl(0deg 0% 95%)' : '#000' },
formatter: (params: any) => {
const param = Array.isArray(params) ? params[0] : params;
const index = param.dataIndex;
const shop = ratios[ratios.length - 1 - index];
if (!shop) return '';
return `${shop.shopName}<br/>销售额: ${formatAmount(shop.salesAmount)}<br/>占比: ${shop.ratio.toFixed(2)}%`;
},
},
xAxis: {
type: 'value',
axisLabel: { show: false },
splitLine: { show: false },
},
yAxis: {
type: 'category',
data: shopNames,
axisLine: { show: false },
axisTick: { show: false },
axisLabel: {
fontWeight: 'bold',
color: isDark ? 'hsl(240deg 5% 64.9%)' : '#64748b',
fontSize: 13,
},
},
series: [
{
type: 'bar',
data: salesAmounts,
barWidth: 20,
itemStyle: {
borderRadius: [0, 10, 10, 0],
color: {
type: 'linear',
x: 1,
y: 0,
x2: 0,
y2: 0,
colorStops: [
{ offset: 0, color: '#6366f1' },
{ offset: 1, color: '#a5b4fc' },
],
},
},
label: {
show: true,
position: 'right',
formatter: (params: any) =>
`¥${params.value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
fontWeight: 900,
color: isDark ? 'hsl(0deg 0% 95%)' : '#334155',
},
},
],
});
};
// 渲染销售额与单量趋势平滑曲线
const renderTrendLineChart = () => {
if (!trendChartRef.value) return;
const salesTrend = props.salesAmountTrend;
const orderTrend = props.orderCountTrend;
if (!salesTrend?.dailyDataList?.length && !orderTrend?.dailyDataList?.length) {
const isDark = document.documentElement.classList.contains('dark');
renderTrendChart({
title: {
text: '暂无趋势数据',
left: 'center',
top: 'middle',
textStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : '#64748b',
fontSize: 14,
fontWeight: 'bold',
},
},
xAxis: { show: false },
yAxis: { show: false },
series: [],
});
return;
}
const dates = (salesTrend?.dailyDataList || orderTrend?.dailyDataList || []).map(
(item) => dayjs(item.date).format('MM-DD'),
);
const salesData = (salesTrend?.dailyDataList || []).map((item) => item.value);
const orderData = (orderTrend?.dailyDataList || []).map((item) => item.value);
const isDark = document.documentElement.classList.contains('dark');
renderTrendChart({
grid: {
left: '3%',
right: '3%',
bottom: '3%',
top: '5%',
containLabel: true,
},
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
textStyle: { color: isDark ? 'hsl(0deg 0% 95%)' : '#000' },
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dates,
axisLine: {
lineStyle: { color: isDark ? 'hsl(240deg 3.7% 22%)' : '#e2e8f0' },
},
axisLabel: { color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined },
},
yAxis: [
{
type: 'value',
name: '销售额',
nameTextStyle: { color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined },
axisLabel: { color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined },
splitLine: {
lineStyle: {
type: 'dashed',
color: isDark ? 'hsl(240deg 3.7% 22%)' : undefined,
},
},
},
{
type: 'value',
name: '单量',
position: 'right',
nameTextStyle: { color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined },
axisLabel: { color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined },
splitLine: { show: false },
},
],
series: [
{
name: '销售额',
type: 'line',
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#3b82f6' },
areaStyle: {
color: {
type: 'linear',
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(59, 130, 246, 0.4)' },
{ offset: 1, color: 'rgba(59, 130, 246, 0)' },
],
},
},
data: salesData,
},
{
name: '日单量',
type: 'line',
yAxisIndex: 1,
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#10b981' },
areaStyle: {
color: {
type: 'linear',
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
{ offset: 1, color: 'rgba(16, 185, 129, 0)' },
],
},
},
data: orderData,
},
],
});
};
const rerenderCharts = async () => {
await nextTick();
renderShopBarChart();
renderTrendLineChart();
};
watch(
() => [props.shopSalesRatios, props.salesAmountTrend, props.orderCountTrend],
() => {
rerenderCharts();
},
{ deep: true, immediate: true },
);
onMounted(() => {
rerenderCharts();
});
defineExpose({ renderShopBarChart, renderShopScatterChart: renderTrendLineChart });
</script>
<template>
<div class="grid grid-cols-1 gap-6 xl:grid-cols-2">
<!-- 销售额与单量趋势分析 -->
<div
class="rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px] xl:col-span-1"
>
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
销售额与单量趋势分析
</h3>
<div class="h-[380px] w-full">
<EchartsUI ref="trendChartRef" />
</div>
</div>
<!-- 各店铺销售贡献排行 -->
<div
class="rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
各店铺销售贡献排行
</h3>
<div class="h-[380px] w-full">
<EchartsUI ref="barChartRef" />
</div>
</div>
</div>
</template>
@@ -1,424 +0,0 @@
<script lang="ts" setup>
import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { createIconifyIcon } from '@vben/icons';
import { computed } from 'vue';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import { formatIntCell, formatNumberCell } from '#/utils/overview-table-cells';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import {
salesTaxColumnHint,
storeOverviewHints,
} from '#/utils/overview-table-hints';
const JumpIcon = createIconifyIcon('tdesign:jump');
defineOptions({ name: 'ShopComparisonTable' });
interface Props {
shopSummary?: CompanyOverviewVO.ShopOverview;
taxRate: number;
shopExportMode: boolean;
selectedExportShopIds: number[];
/** 覆盖默认表头主标题(如工作台演示) */
headingTitle?: string;
/** 覆盖默认表头副标题 */
headingSubtitle?: string;
}
interface Emits {
(e: 'update:selectedExportShopIds', ids: number[]): void;
(e: 'toggleShopExportMode', enabled: boolean): void;
(e: 'export'): void;
(e: 'navigate', shopId: number): void;
}
const props = withDefaults(defineProps<Props>(), {
headingTitle: '各店铺多维度经营明细汇总',
headingSubtitle: '包含:目标达成、规模、成本及最终损益所有维度',
});
const emit = defineEmits<Emits>();
const allShopsSelected = computed(() => {
const total = props.shopSummary?.shops?.length || 0;
return total > 0 && props.selectedExportShopIds.length === total;
});
const someShopsSelected = computed(() => {
return props.selectedExportShopIds.length > 0;
});
const formatAmount = (amount: number) => {
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const formatPercentPlain = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value.toFixed(1)}%`;
};
const cellMoney = (v: number | null | undefined) => formatNumberCell(v, formatAmount);
const cellRoi = (v: number | null | undefined) =>
formatNumberCell(v, (n) => n.toFixed(2));
</script>
<template>
<div
class="overflow-hidden rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px]"
>
<div
class="flex flex-col items-start justify-between gap-4 border-b border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] p-8 md:flex-row md:items-center"
>
<div>
<h3 class="text-xl font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ props.headingTitle }}
</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ props.headingSubtitle }}
</p>
</div>
<div class="flex items-center gap-3">
<template v-if="shopExportMode">
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('toggleShopExportMode', false)"
>
取消选择
</button>
<button
class="rounded-2xl bg-blue-600 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
:disabled="selectedExportShopIds.length === 0"
@click="emit('export')"
>
导出已选店铺 ({{ selectedExportShopIds.length }})
</button>
</template>
<template v-else>
<button
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
@click="emit('toggleShopExportMode', true)"
>
指定店铺导出
</button>
<button
class="rounded-2xl bg-slate-900 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 dark:shadow-none"
@click="emit('export')"
>
导出全部
</button>
</template>
</div>
</div>
<div class="table-container overflow-x-auto">
<table class="w-full whitespace-nowrap text-left text-sm">
<thead
class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-xs font-black uppercase text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<tr>
<th
v-if="shopExportMode"
rowspan="2"
class="sticky-col border-b border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] p-3 text-center"
>
<input
type="checkbox"
class="h-4 w-4 cursor-pointer accent-blue-600"
:checked="allShopsSelected"
:indeterminate="someShopsSelected && !allShopsSelected"
@change="
(e) => {
if ((e.target as HTMLInputElement).checked) {
emit(
'update:selectedExportShopIds',
shopSummary?.shops?.map((s) => s.shopId) || [],
);
} else {
emit('update:selectedExportShopIds', []);
}
}
"
/>
</th>
<th
rowspan="2"
class="sticky-col border-b p-6 text-base font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)] shadow-sm"
:class="
shopExportMode
? 'border-l-0 bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)]'
: 'border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)]'
"
>
店铺
</th>
<th
colspan="4"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-blue-50/50 dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)] p-3 text-center text-blue-700 dark:text-blue-400"
>
目标达成维度
</th>
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
经营规模维度
</th>
<th
colspan="8"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50%)] p-3 text-center text-orange-700 dark:text-orange-400"
>
成本费用维度
</th>
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] dark:border-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-3 text-center text-emerald-700 dark:text-emerald-400"
>
盈利分析维度
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<!-- 目标 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.targetOrderCount">
目标单量
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-blue-600 dark:text-blue-400">
<OverviewColumnHint :title="storeOverviewHints.orderCountAchievementRate">
单量达成率
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.targetAmount">目标额</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-blue-600 dark:text-blue-400">
<OverviewColumnHint :title="storeOverviewHints.salesAmountAchievementRate">
销售达成率
</OverviewColumnHint>
</th>
<!-- 规模 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.orderCount">单量</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<!-- 成本 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="storeOverviewHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="storeOverviewHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="storeOverviewHints.totalPromotionFee">推广费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-orange-600 dark:text-orange-400">
<OverviewColumnHint :title="storeOverviewHints.brushFee">刷单费用</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="storeOverviewHints.feeRatioShopRow">费比%</OverviewColumnHint>
</th>
<!-- 盈利 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-bold">
<OverviewColumnHint :title="storeOverviewHints.totalProfitBeforeTax">
税前盈亏
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
<OverviewColumnHint :title="salesTaxColumnHint(taxRate)">
{{ (taxRate * 100).toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-black text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="storeOverviewHints.roi">ROI</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="storeOverviewHints.profitAfterTax">
税后盈亏
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="shop in (shopSummary?.shops || [])"
:key="shop.shopId"
class="transition-colors hover:bg-blue-50/50 dark:hover:bg-[hsl(217.2deg_32.6%_17.5%/30%)] dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)]"
>
<td
v-if="shopExportMode"
class="sticky-col border-r border-slate-100 dark:border-r-[hsl(240deg_3.7%_22%)] bg-slate-50/50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
<input
type="checkbox"
:value="shop.shopId"
class="h-4 w-4 cursor-pointer accent-blue-600"
@change="
(e) => {
const checked = (e.target as HTMLInputElement).checked;
const newIds = checked
? [...selectedExportShopIds, shop.shopId]
: selectedExportShopIds.filter((id) => id !== shop.shopId);
emit('update:selectedExportShopIds', newIds);
}
"
/>
</td>
<td
class="sticky-col border-r-2 border-slate-100 dark:border-r-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 font-bold shadow-sm dark:shadow-none"
:class="shopExportMode ? 'border-l-0' : ''"
>
<span
class="inline-flex cursor-pointer items-center gap-1 rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400 transition-colors hover:text-blue-300 hover:underline"
@click="emit('navigate', shop.shopId)"
>
{{ shop.shopName }}
<JumpIcon class="text-xs" />
</span>
</td>
<!-- 目标 -->
<td class="p-6 font-medium">
{{ formatIntCell(shop.targetOrderCount) }}
</td>
<td class="p-6 font-black text-blue-600 dark:text-blue-400">
{{
shop.orderCountAchievementRate !== undefined
? formatPercentPlain(shop.orderCountAchievementRate)
: '-'
}}
</td>
<td class="p-6 font-medium">
{{ cellMoney(shop.targetAmount) }}
</td>
<td class="p-6 font-black text-blue-600 dark:text-blue-400">
{{
shop.salesAmountAchievementRate !== undefined
? formatPercentPlain(shop.salesAmountAchievementRate)
: '-'
}}
</td>
<!-- 规模 -->
<td class="p-6 font-black">
{{ formatAmount(shop.salesAmount) }}
</td>
<td class="p-6 font-medium">
{{ formatIntCell(shop.orderCount) }}
</td>
<td class="p-6 font-medium">
{{ cellMoney(shop.averageOrderValue) }}
</td>
<!-- 成本 -->
<td class="p-6">
{{ cellMoney(shop.productCost) }}
</td>
<td class="p-6">
{{ cellMoney(shop.shippingCost) }}
</td>
<td class="p-6">
{{ cellMoney(shop.otherCost) }}
</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(shop.orderCost) }}
</td>
<td class="p-6 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(shop.refundAmount) }}
</td>
<td class="p-6">
{{ cellMoney(shop.totalPromotionFee) }}
</td>
<td class="p-6 text-orange-600 dark:text-orange-400">
{{ cellMoney(shop.brushFee) }}
</td>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{
shop.feeRatio !== undefined
? formatFeeRatioPercent(shop.feeRatio)
: '-'
}}
</td>
<!-- 盈利 -->
<td class="p-6 font-bold">
{{ cellMoney(shop.totalProfitBeforeTax) }}
</td>
<td class="p-6 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cellMoney(shop.salesTaxAmount) }}
</td>
<td class="p-6 font-black text-indigo-700 dark:text-indigo-400">
{{ cellRoi(shop.roi) }}
</td>
<td class="bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-6 text-base font-black text-emerald-600">
{{ cellMoney(shop.profitAfterTax) }}
</td>
</tr>
<tr v-if="!shopSummary?.shops?.length">
<td :colspan="shopExportMode ? 22 : 21" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
</tbody>
<!-- 合计行 -->
<tfoot v-if="shopSummary?.total" class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="p-6 text-base" :class="shopExportMode ? 'border-l-0' : ''">合计</td>
<!-- 目标 -->
<td class="p-6">{{ formatIntCell(shopSummary?.total?.targetOrderCount) }}</td>
<td class="p-6 text-blue-600 dark:text-blue-400">
{{
shopSummary?.total?.orderCountAchievementRate !== undefined
? formatPercentPlain(shopSummary?.total?.orderCountAchievementRate)
: '-'
}}
</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.targetAmount) }}</td>
<td class="p-6 text-blue-600 dark:text-blue-400">
{{
shopSummary?.total?.salesAmountAchievementRate !== undefined
? formatPercentPlain(shopSummary?.total?.salesAmountAchievementRate)
: '-'
}}
</td>
<!-- 规模 -->
<td class="p-6">{{ cellMoney(shopSummary?.total?.salesAmount) }}</td>
<td class="p-6">{{ formatIntCell(shopSummary?.total?.orderCount) }}</td>
<td class="p-6">
{{ cellMoney(shopSummary?.total?.averageOrderValue) }}
</td>
<!-- 成本 -->
<td class="p-6">{{ cellMoney(shopSummary?.total?.productCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.shippingCost) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoney(shopSummary?.total?.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoney(shopSummary?.total?.refundAmount) }}</td>
<td class="p-6">{{ cellMoney(shopSummary?.total?.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoney(shopSummary?.total?.brushFee) }}</td>
<td class="p-6 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ shopSummary?.total?.feeRatio !== undefined ? formatFeeRatioPercent(shopSummary?.total?.feeRatio) : '-' }}</td>
<!-- 盈利 -->
<td class="p-6">{{ cellMoney(shopSummary?.total?.totalProfitBeforeTax) }}</td>
<td class="p-6 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoney(shopSummary?.total?.salesTaxAmount) }}</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">{{ cellRoi(shopSummary?.total?.roi) }}</td>
<td
class="bg-emerald-100 p-6 text-base dark:bg-emerald-950"
:class="(shopSummary?.total?.profitAfterTax ?? 0) < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-700 dark:text-emerald-300'"
>{{ cellMoney(shopSummary?.total?.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
@@ -1,615 +0,0 @@
<script lang="ts" setup>
import type {
CompanyOverviewDTO,
CompanyOverviewVO,
} from '#/api/ecommerce/store-overview';
import {
onActivated,
onMounted,
onUnmounted,
ref,
watch,
} from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Button, DatePicker, InputNumber, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getCompanyOverviewApi } from '#/api/ecommerce/store-overview/apis';
import { exportByPost } from '#/utils/export';
import {
applyOverviewDateRangeFromUrl,
buildOverviewRouteQuery,
normalizeOverviewRangePickerChange,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
import ComparisonSwitcher from './components/ComparisonSwitcher.vue';
import KpiCards from './components/KpiCards.vue';
import ShopCharts from './components/ShopCharts.vue';
defineOptions({ name: 'CompanyOverview' });
// 路由
const router = useRouter();
// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const overviewData = ref<CompanyOverviewVO.Info | null>(null);
// 指定店铺导出模式
const shopExportMode = ref(false);
const selectedExportShopIds = ref<number[]>([]);
// 指定平台导出模式
const platformExportMode = ref(false);
const selectedExportPlatformCodes = ref<string[]>([]);
// 日期范围(默认:本月至今日)
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().startOf('month'),
dayjs(),
]);
// 品类导出相关
const categoryExportMode = ref(false);
const selectedExportCategoryIds = ref<number[]>([]);
const handleCategoryExportToggle = (enabled: boolean) => {
categoryExportMode.value = enabled;
selectedExportCategoryIds.value = [];
};
const handleCategoryExport = async () => {
const params = {
dateRange: dateRange.value.map((d) => d.format('YYYY-MM-DD')),
taxRate: taxRate.value,
};
if (selectedExportCategoryIds.value.length > 0) {
Object.assign(params, { categoryIds: selectedExportCategoryIds.value });
}
const [cStart, cEnd] = dateRange.value;
await exportByPost(
'/ec/store-overview/export/by-category',
params,
`全店概览_按品类汇总_${cStart.format('YYYYMMDD')}-${cEnd.format('YYYYMMDD')}.xlsx`,
);
};
// 税率(公司/店铺概览共用持久化)
const TAX_RATE_KEY = 'overview-tax-rate';
const taxRate = ref<number>(0.04);
taxRate.value = Number(localStorage.getItem(TAX_RATE_KEY)) || 0.04;
watch(taxRate, (val) => {
localStorage.setItem(TAX_RATE_KEY, String(val));
loadOverviewData();
});
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${num * 100}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday'
>('thisMonth');
// 自定义日期范围
const customDateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>([
dateRange.value[0],
dateRange.value[1],
]);
const lastRequestKey = ref('');
const isRequesting = ref(false);
// 图表引用
const shopChartsRef = ref<{ renderShopBarChart: () => void; renderShopScatterChart: () => void }>();
// 切换时间范围
const switchTimeRange = async (
type: '7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday',
) => {
activeTimeRange.value = type;
let startDate: dayjs.Dayjs;
let endDate: dayjs.Dayjs = dayjs();
switch (type) {
case '7days': {
startDate = dayjs().subtract(7, 'day');
break;
}
case '30days': {
startDate = dayjs().subtract(30, 'day');
break;
}
case 'thisMonth': {
startDate = dayjs().startOf('month');
endDate = dayjs();
break;
}
case 'custom': {
if (customDateRange.value) {
dateRange.value = customDateRange.value;
}
return;
}
case 'today': {
startDate = dayjs();
endDate = dayjs();
break;
}
case 'yesterday': {
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
}
dateRange.value = [startDate, endDate];
customDateRange.value = [startDate, endDate];
// 手动切换时间时清除请求缓存,确保强制刷新
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
// 自定义日期范围变化(同一天点两次时,antd 可能只给出开始日、结束为 null,dayjs(undefined) 会变成「今天」)
const handleCustomDateRangeChange = async (
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
dateStrings?: [string, string],
) => {
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) {
return;
}
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
const setTimeRangeTypeByDates = (
startDate: dayjs.Dayjs,
endDate: dayjs.Dayjs,
) => {
const today = dayjs();
const daysDiff = endDate.diff(startDate, 'day');
const isEndDateToday = endDate.isSame(today, 'day');
const isStartDate7DaysAgo = startDate.isSame(
dayjs().subtract(7, 'day'),
'day',
);
const isStartDate30DaysAgo = startDate.isSame(
dayjs().subtract(30, 'day'),
'day',
);
if (
isEndDateToday &&
startDate.isSame(today.startOf('month'), 'day')
) {
activeTimeRange.value = 'thisMonth';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(today, 'day')) {
activeTimeRange.value = 'today';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(dayjs().subtract(1, 'day'), 'day')) {
activeTimeRange.value = 'yesterday';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate7DaysAgo) {
activeTimeRange.value = '7days';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate30DaysAgo) {
activeTimeRange.value = '30days';
customDateRange.value = [startDate, endDate];
return;
}
activeTimeRange.value = 'custom';
customDateRange.value = [startDate, endDate];
};
const applyDateRangeFromRouteQuery = () =>
applyOverviewDateRangeFromUrl(dateRange, setTimeRangeTypeByDates);
const syncDateRangeToRouteQuery = () => {
syncOverviewDateRangeToUrl(dateRange.value);
};
// 加载概览数据
const loadOverviewData = async () => {
if (isRequesting.value) return;
isRequesting.value = true;
try {
loading.value = true;
const params: CompanyOverviewDTO.Query = {
dateRange: [
dateRange.value[0].format('YYYY-MM-DD'),
dateRange.value[1].format('YYYY-MM-DD'),
],
taxRate: taxRate.value,
};
const data = await getCompanyOverviewApi(params);
overviewData.value = data;
} catch (error) {
console.error('获取全店概览数据失败:', error);
} finally {
loading.value = false;
isRequesting.value = false;
}
};
const refreshOverviewByCurrentParams = async (force = false) => {
applyDateRangeFromRouteQuery();
const requestKey = `${dateRange.value[0].format('YYYY-MM-DD')}_${dateRange.value[1].format('YYYY-MM-DD')}`;
if (!force && lastRequestKey.value === requestKey) {
return;
}
lastRequestKey.value = requestKey;
await loadOverviewData();
};
// 监听数据变化,重新渲染图表
watch(
() => overviewData.value,
() => {
if (overviewData.value) {
setTimeout(() => {
shopChartsRef.value?.renderShopBarChart();
shopChartsRef.value?.renderShopScatterChart();
}, 100);
}
},
{ deep: true },
);
// 深色模式 class 变化时重绘图表
let darkThemeObserver: MutationObserver | null = null;
onMounted(async () => {
await refreshOverviewByCurrentParams(true);
darkThemeObserver = new MutationObserver(() => {
if (overviewData.value) {
shopChartsRef.value?.renderShopBarChart();
shopChartsRef.value?.renderShopScatterChart();
}
});
darkThemeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
});
onUnmounted(() => {
darkThemeObserver?.disconnect();
darkThemeObserver = null;
});
onActivated(async () => {
await refreshOverviewByCurrentParams(true);
});
// 全店概览-按店铺汇总导出
const handleExportCompanyOverview = async () => {
try {
exportLoading.value = true;
const [startDate, endDate] = dateRange.value;
let dataToExport: CompanyOverviewVO.ShopSummary[] = [];
if (overviewData.value?.shopSummary) {
const shops = overviewData.value.shopSummary.shops;
dataToExport =
selectedExportShopIds.value.length > 0
? shops.filter((s) =>
selectedExportShopIds.value.includes(s.shopId),
)
: shops;
}
let shopIds: number[] | undefined;
if (dataToExport.length === 0) {
shopIds =
selectedExportShopIds.value.length > 0
? selectedExportShopIds.value
: undefined;
}
const filename = `全店概览_按店铺汇总_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/store-overview/export/by-shop',
{
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
shopIds,
taxRate: taxRate.value,
},
filename,
);
shopExportMode.value = false;
} finally {
exportLoading.value = false;
}
};
// 切换行选择模式
const toggleShopExportMode = (enabled: boolean) => {
shopExportMode.value = enabled;
if (!enabled) {
selectedExportShopIds.value = [];
}
};
// 切换平台导出模式
const togglePlatformExportMode = (enabled: boolean) => {
platformExportMode.value = enabled;
if (!enabled) {
selectedExportPlatformCodes.value = [];
}
};
// 全店概览-按平台汇总导出
const handlePlatformExport = async () => {
try {
exportLoading.value = true;
const [startDate, endDate] = dateRange.value;
const filename = `全店概览_按平台汇总_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/store-overview/export/by-platform',
{
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
platformCodes: selectedExportPlatformCodes.value.length > 0
? selectedExportPlatformCodes.value
: undefined,
taxRate: taxRate.value,
},
filename,
);
platformExportMode.value = false;
} finally {
exportLoading.value = false;
}
};
// 跳转到店铺详情页
const navigateToShopOverview = (shopId: number) => {
router.push({
path: `/ecom/shop/overview/${shopId}`,
query: buildOverviewRouteQuery(dateRange.value),
});
};
</script>
<template>
<Page
auto-content-height
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
header-class="store-overview-page-header"
>
<template #title>
<div
class="text-xl font-black tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_98%)] sm:text-2xl md:text-3xl"
>
全店铺经营概览大盘
</div>
</template>
<template #extra>
<!-- 税率 + 时间选择器 -->
<div class="flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2">
<!-- 税率输入 -->
<div
class="flex min-h-[44px] w-full items-center gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 px-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)] sm:w-auto"
>
<span class="text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">税率</span>
<InputNumber
v-model:value="taxRate"
:min="0"
:max="1"
:step="0.01"
:precision="2"
size="small"
class="tax-rate-input !h-8 !w-20 !rounded-lg !border-none !bg-white/30 dark:!bg-[hsl(240deg_3.7%_22%/30%)] !text-sm !font-bold !text-center"
:formatter="formatTaxRate"
:parser="parseTaxRate"
/>
</div>
<!-- 时间选择器容器 -->
<div
class="flex w-full flex-col gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 p-1.5 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)] sm:w-auto sm:flex-row sm:items-center sm:gap-2"
>
<!-- 快速选择按钮组 -->
<div
class="flex w-full items-center gap-1 overflow-x-auto rounded-xl bg-white/30 p-1 dark:bg-[hsl(240deg_3.7%_22%/30%)]"
>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'today'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('today')"
>
今日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'yesterday'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('yesterday')"
>
昨日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === '7days'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('7days')"
>
近7日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === '30days'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('30days')"
>
近30日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'thisMonth'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('thisMonth')"
>
本月
</Button>
</div>
<!-- 日期选择器 -->
<div class="flex w-full items-center justify-between gap-2 sm:w-auto sm:justify-start">
<span class="hidden whitespace-nowrap text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)] sm:inline">
自定义日期
</span>
<DatePicker.RangePicker
v-model:value="customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始', '结束']"
class="!h-8 !w-full !border-none !bg-transparent !text-sm !font-bold dark:!text-[hsl(240deg_5%_64.9%)] sm:!w-[220px]"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</div>
</template>
<Spin :spinning="loading">
<div class="mx-auto w-full space-y-6">
<!-- 第一层:核心汇总指标 -->
<KpiCards :overview-data="overviewData" :tax-rate="taxRate" />
<!-- 第二层:深度分析图表 -->
<ShopCharts
ref="shopChartsRef"
:shop-sales-ratios="overviewData?.shopSalesRatios"
:shop-summary="overviewData?.shopSummary"
:sales-amount-trend="overviewData?.salesAmountTrend"
:order-count-trend="overviewData?.orderCountTrend"
/>
<!-- 第三层:平台/店铺/品类明细切换 -->
<ComparisonSwitcher
:tax-rate="taxRate"
:platform-summary="overviewData?.platformSummary"
:platform-export-mode="platformExportMode"
:selected-export-platform-codes="selectedExportPlatformCodes"
:shop-summary="overviewData?.shopSummary"
:shop-export-mode="shopExportMode"
:selected-export-shop-ids="selectedExportShopIds"
:category-summary="overviewData?.categorySummary"
:category-export-mode="categoryExportMode"
:selected-export-category-ids="selectedExportCategoryIds"
@update:selected-export-platform-codes="(codes) => (selectedExportPlatformCodes = codes)"
@toggle-platform-export-mode="togglePlatformExportMode"
@platform-export="handlePlatformExport"
@update:selected-export-shop-ids="(ids) => (selectedExportShopIds = ids)"
@toggle-shop-export-mode="toggleShopExportMode"
@shop-export="handleExportCompanyOverview"
@navigate="navigateToShopOverview"
@toggle-category-export-mode="handleCategoryExportToggle"
@update:selected-export-category-ids="selectedExportCategoryIds = $event"
@category-export="handleCategoryExport"
/>
</div>
</Spin>
</Page>
</template>
<style scoped>
:deep(.tax-rate-input .ant-input-number-input) {
height: 32px;
line-height: 32px;
padding-top: 0;
padding-bottom: 0;
}
:deep(.store-overview-page-header) {
align-items: center;
}
@media (max-width: 640px) {
:deep(.store-overview-page-header) {
flex-direction: column;
align-items: stretch;
gap: 10px;
}
:deep(.store-overview-page-header > div:first-child) {
width: 100%;
}
:deep(.store-overview-page-header > div:last-child) {
width: 100%;
}
}
</style>
@@ -101,7 +101,7 @@ function goToImportPromotionFee() {
void router.push('/import/promotion-fee');
}
/** 与全店概览一致:快捷区间 + 自定义 RangePicker */
/** 与工作台一致:快捷区间 + 自定义 RangePicker */
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().startOf('month'),
dayjs(),
@@ -200,7 +200,7 @@ async function handleProductExport() {
<PlatformSummaryCard
v-if="activeMode === 'platform'"
heading-title="各平台多维度经营明细汇总"
heading-subtitle="与全店概览同款表格"
heading-subtitle="与工作台经营概览同源表格"
:platform-summary="platformSummary ?? undefined"
:tax-rate="taxRate"
:platform-export-mode="platformExportMode"
@@ -213,7 +213,7 @@ async function handleProductExport() {
<CategorySummaryTable
v-if="activeMode === 'category'"
heading-title="各品类多维度经营明细汇总"
heading-subtitle="与全店概览同款表格"
heading-subtitle="与工作台经营概览同源表格"
:category-summary="categorySummary ?? undefined"
:tax-rate="taxRate"
:category-export-mode="categoryExportMode"
@@ -226,7 +226,7 @@ async function handleProductExport() {
<CategorySummaryTable
v-if="activeMode === 'product'"
heading-title="各商品多维度经营明细汇总"
heading-subtitle="列结构与品类表一致;数据与全店概览商品维度同源;点击商品名可跳转商品概览"
heading-subtitle="列结构与品类表一致;数据与工作台商品维度同源;点击商品名可跳转商品概览"
first-column-label="商品"
:product-navigate="true"
:category-summary="productSummary ?? undefined"
@@ -374,7 +374,7 @@ defineExpose({ redraw });
class="mt-0.5 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
销售/毛利/净利/退款(柱)与毛利率、净利率(线)·
{{ liveData ? '接口数据(与全店概览订单口径一致)' : '演示数据' }}
{{ liveData ? '接口数据(与工作台订单口径一致)' : '演示数据' }}
</p>
</div>
<div
@@ -28,7 +28,7 @@ defineExpose({ redraw });
<p
class="text-xs font-bold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
按平台、店铺、品类、商品各一张卡;数据与全店概览订单统计口径一致
按平台、店铺、品类、商品各一张卡;数据与工作台订单统计口径一致
</p>
<WorkbenchMultiDimCardsGrid
ref="gridRef"
@@ -16,7 +16,7 @@ import { Page } from '@vben/common-ui';
import { message, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import { getShopOverviewApi, getShopPageApi } from '#/api/ecommerce/shop/apis';
import { exportByPost } from '#/utils/export';
import {
applyOverviewDateRangeFromUrl,
@@ -249,8 +249,18 @@ const loadOverviewData = async () => {
isRequesting.value = true;
try {
loading.value = true;
// 原 /ec/shop/overview 已下线,待接入 Mongo BI 读模型
const [startDate, endDate] = dateRange.value;
overviewData.value = await getShopOverviewApi({
shopId: shopId.value,
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
taxRate: taxRate.value,
});
} catch (err: any) {
overviewData.value = null;
message.error(err?.message || '加载店铺概览失败');
} finally {
loading.value = false;
isRequesting.value = false;
@@ -267,7 +277,7 @@ const handleExportShopOverview = async () => {
const safeName = String(shopName).replace(/[/\\:*?"<>|]/g, '_');
const filename = `${safeName}_按商品汇总统计_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/shop/export/summary-by-product',
'/bi/shop/export/summary-by-product',
{
shopId: shopId.value,
dateRange: [
@@ -309,7 +319,7 @@ const handleCategoryExport = async () => {
const catShopName = overviewData.value?.shopName || `店铺${shopId.value}`;
const catSafeName = String(catShopName).replace(/[/\\:*?"<>|]/g, '_');
await exportByPost(
'/ec/shop/export/summary-by-category',
'/bi/shop/export/summary-by-category',
params,
`${catSafeName}_按品类汇总统计_${catStart.format('YYYYMMDD')}-${catEnd.format('YYYYMMDD')}.xlsx`,
);
@@ -17,7 +17,7 @@ exports[`defaultPreferences immutability test > should not modify the config obj
"contentPaddingRight": 0,
"contentPaddingTop": 0,
"defaultAvatar": "https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp",
"defaultHomePath": "/store-overview",
"defaultHomePath": "/workbench",
"dynamicTitle": true,
"enableCheckUpdates": true,
"enablePreferences": true,
@@ -17,7 +17,7 @@ const defaultPreferences: Preferences = {
contentPaddingTop: 0,
defaultAvatar:
'https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp',
defaultHomePath: '/store-overview',
defaultHomePath: '/workbench',
dynamicTitle: true,
enableCheckUpdates: true,
enablePreferences: true,