diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CategoryExportExcelServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CategoryExportExcelServiceImpl.java index 176df879..de3cacef 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CategoryExportExcelServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CategoryExportExcelServiceImpl.java @@ -14,8 +14,11 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStatisticsVO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; @@ -30,7 +33,14 @@ import java.math.RoundingMode; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.*; +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; @Service @@ -47,6 +57,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic private final ProductSpecMapper productSpecMapper; private final CategoryService categoryService; private final ExportStatusRangeHelper exportStatusRangeHelper; + private final ShopOverviewStatisticsService shopOverviewStatisticsService; public CategoryExportExcelServiceImpl( CurrentUserContext currentUserContext, @@ -56,7 +67,8 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic ProductService productService, ProductSpecMapper productSpecMapper, CategoryService categoryService, - ExportStatusRangeHelper exportStatusRangeHelper) { + ExportStatusRangeHelper exportStatusRangeHelper, + ShopOverviewStatisticsService shopOverviewStatisticsService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.promotionFeeMapper = promotionFeeMapper; @@ -65,10 +77,14 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic this.productSpecMapper = productSpecMapper; this.categoryService = categoryService; this.exportStatusRangeHelper = exportStatusRangeHelper; + this.shopOverviewStatisticsService = shopOverviewStatisticsService; } @Override public byte[] exportCategoryOverview(CategoryExportDTO dto) { + if (dto.getShopId() != null) { + return exportShopCategoryViaOverview(dto); + } Long companyId = currentUserContext.getCurrentCompanyId(); LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); LocalDate startDate = dateRange[0]; @@ -237,7 +253,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) { Set allowedIds = new HashSet<>(dto.getCategoryIds()); categoryDataList = categoryDataList.stream() - .filter(c -> c.getCategoryId() != null && allowedIds.contains(c.getCategoryId())) + .filter(c -> allowedIds.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L)) .collect(Collectors.toList()); } @@ -245,9 +261,15 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT); + List shopRows = categoryDataList.stream() + .map(this::toShopCategorySummary) + .collect(Collectors.toList()); + ShopOverviewStatisticsVO.CategorySummary totalRow = aggregateCategoryTotals(shopRows, taxRate); + try (Workbook workbook = new XSSFWorkbook()) { - Sheet sheet = workbook.createSheet("品类明细"); - createCategoryDetailSheet(sheet, dateRangeLabel, categoryDataList, taxRate); + Sheet sheet = workbook.createSheet("品类汇总"); + writeCategoryMultidimensionalSheet( + sheet, "全店 - 品类多维度损益汇总", dateRangeLabel, shopRows, totalRow, taxRate); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -257,23 +279,164 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic } } - private void createCategoryDetailSheet(Sheet sheet, String dateRangeLabel, - List dataList, - BigDecimal taxRate) { - CellStyle titleStyle = createTitleStyle(sheet.getWorkbook()); - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); + /** + * 店铺侧导出:与 {@link ShopOverviewStatisticsService#getShopOverviewStatistics} 同源, + * 保证订单状态参与统计、推广费/刷单费分摊与前端「品类多维度损益汇总」一致。 + */ + private byte[] exportShopCategoryViaOverview(CategoryExportDTO dto) { + 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); - String taxLabel = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() + "%税额"; + ShopOverviewQueryDTO query = new ShopOverviewQueryDTO(); + query.setShopId(dto.getShopId()); + query.setDateRange(dto.getDateRange()); + query.setTaxRate(taxRate); + + ShopOverviewStatisticsVO vo = shopOverviewStatisticsService.getShopOverviewStatistics(query); + ShopOverviewStatisticsVO.CategoryOverview co = vo.getCategoryOverview(); + + List rows = (co != null && co.getCategories() != null) + ? new ArrayList<>(co.getCategories()) + : new ArrayList<>(); + ShopOverviewStatisticsVO.CategorySummary totalRow = (co != null && co.getTotal() != null) + ? co.getTotal() + : aggregateCategoryTotals(rows, taxRate); + + if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) { + Set allowed = new HashSet<>(dto.getCategoryIds()); + rows = rows.stream() + .filter(c -> allowed.contains(c.getCategoryId())) + .collect(Collectors.toList()); + totalRow = aggregateCategoryTotals(rows, taxRate); + } + + String shopTitle = vo.getShopName() != null && !vo.getShopName().isBlank() + ? vo.getShopName() + " - 品类多维度损益汇总" + : ("店铺" + dto.getShopId() + " - 品类多维度损益汇总"); + + try (Workbook workbook = new XSSFWorkbook()) { + Sheet sheet = workbook.createSheet("品类汇总"); + writeCategoryMultidimensionalSheet(sheet, shopTitle, dateRangeLabel, rows, totalRow, taxRate); + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + workbook.write(out); + return out.toByteArray(); + } + } catch (Exception e) { + throw new BusinessException("导出品类Excel失败: " + e.getMessage()); + } + } + + private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) { + ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary(); + s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L); + 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.setTotalCost(c.getTotalCost()); + 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; + } + + /** 与店铺概览品类「合计」行算法一致,用于按品类 ID 筛选导出后的合计行。 */ + private ShopOverviewStatisticsVO.CategorySummary aggregateCategoryTotals( + List categories, BigDecimal taxRate) { + 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; + + for (ShopOverviewStatisticsVO.CategorySummary c : categories) { + totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : 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 = totalSales.multiply(taxRate); + 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; + + ShopOverviewStatisticsVO.CategorySummary total = new ShopOverviewStatisticsVO.CategorySummary(); + total.setCategoryId(0L); + total.setCategoryName("合计"); + total.setSalesAmount(totalSales); + total.setOrderCount(totalOrders); + total.setAverageOrderValue(avgOrderValue); + total.setProductCost(totalProductCost); + total.setShippingCost(totalShippingCost); + total.setOtherCost(totalOtherCost); + total.setTotalCost(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; + } + + /** + * 列顺序与前端 {@code CategoryComparisonTable.vue} 一致;费比列为「百分比数值」(×100,一位小数),与页面展示一致。 + */ + private void writeCategoryMultidimensionalSheet( + Sheet sheet, + String title, + String dateRangeLabel, + List rows, + ShopOverviewStatisticsVO.CategorySummary totalRow, + BigDecimal taxRate) { + Workbook wb = sheet.getWorkbook(); + CellStyle titleStyle = createTitleStyle(wb); + CellStyle headerStyle = createHeaderStyle(wb); + CellStyle dataStyle = createDataStyle(wb); + CellStyle totalStyle = createBoldDataStyle(wb); + + String taxHeader = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() + + "%税额"; String[] headers = { - "品类名称", "销售额", "单量", "客单价", - "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", - "费比", "税前盈亏", taxLabel, "税后盈亏", "ROI" + "品类名称", "实际销售额", "单量", "客单价", + "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比 %", + "税前盈亏", taxHeader, "ROI", "税后盈亏" }; Row titleRow = sheet.createRow(0); Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("品类明细 | " + dateRangeLabel); + titleCell.setCellValue(title + " | " + dateRangeLabel); titleCell.setCellStyle(titleStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1)); @@ -284,37 +447,61 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic cell.setCellStyle(headerStyle); } - int rowIdx = 2; - for (CompanyOverviewVO.CategorySummary data : dataList) { - Row row = sheet.createRow(rowIdx++); - setCell(row, 0, data.getCategoryName(), dataStyle); - setCell(row, 1, objToDouble(data.getSalesAmount()), dataStyle); - setCell(row, 2, objToDouble(data.getOrderCount()), dataStyle); - setCell(row, 3, objToDouble(data.getAverageOrderValue()), dataStyle); - setCell(row, 4, objToDouble(data.getProductCost()), dataStyle); - setCell(row, 5, objToDouble(data.getShippingCost()), dataStyle); - setCell(row, 6, objToDouble(data.getOtherCost()), dataStyle); - setCell(row, 7, objToDouble(data.getTotalCost()), dataStyle); - setCell(row, 8, objToDouble(data.getRefundAmount()), dataStyle); - setCell(row, 9, objToDouble(data.getTotalPromotionFee()), dataStyle); - setCell(row, 10, objToDouble(data.getBrushFee()), dataStyle); - setCell(row, 11, objToDouble(data.getFeeRatio()), dataStyle); - setCell(row, 12, objToDouble(data.getTotalProfitBeforeTax()), dataStyle); - setCell(row, 13, objToDouble(data.getSalesTaxAmount()), dataStyle); - setCell(row, 14, objToDouble(data.getProfitAfterTax()), dataStyle); - setCell(row, 15, objToDouble(data.getRoi()), dataStyle); + int r = 2; + for (ShopOverviewStatisticsVO.CategorySummary rowData : rows) { + fillCategoryDataRow(sheet.createRow(r++), rowData, dataStyle); + } + if (totalRow != null) { + fillCategoryDataRow(sheet.createRow(r), totalRow, totalStyle); } - for (int i = 0; i < headers.length; i++) { - sheet.setColumnWidth(i, 3200); + sheet.setColumnWidth(0, 5200); + for (int i = 1; i < headers.length; i++) { + sheet.setColumnWidth(i, 3400); } } - 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; + private void fillCategoryDataRow(Row row, ShopOverviewStatisticsVO.CategorySummary d, CellStyle style) { + setCell(row, 0, d.getCategoryName() != null ? d.getCategoryName() : "", style); + setCell(row, 1, bd2Money(d.getSalesAmount()), style); + Cell oc = row.createCell(2); + oc.setCellStyle(style); + oc.setCellValue(d.getOrderCount() != null ? d.getOrderCount() : 0); + setCell(row, 3, bd2Money(d.getAverageOrderValue()), style); + setCell(row, 4, bd2Money(d.getProductCost()), style); + setCell(row, 5, bd2Money(d.getShippingCost()), style); + setCell(row, 6, bd2Money(d.getOtherCost()), style); + setCell(row, 7, bd2Money(d.getTotalCost()), style); + setCell(row, 8, bd2Money(d.getRefundAmount()), style); + setCell(row, 9, bd2Money(d.getTotalPromotionFee()), style); + setCell(row, 10, bd2Money(d.getBrushFee()), style); + setCell(row, 11, bd2FeeRatioPercent(d.getFeeRatio()), style); + setCell(row, 12, bd2Money(d.getTotalProfitBeforeTax()), style); + setCell(row, 13, bd2Money(d.getSalesTaxAmount()), style); + setCell(row, 14, bd2Roi(d.getRoi()), style); + setCell(row, 15, bd2Money(d.getProfitAfterTax()), style); + } + + private static double bd2Money(BigDecimal v) { + if (v == null) { + return 0.0; + } + return v.setScale(2, RoundingMode.HALF_UP).doubleValue(); + } + + private static double bd2Roi(BigDecimal v) { + if (v == null) { + return 0.0; + } + return v.setScale(4, RoundingMode.HALF_UP).doubleValue(); + } + + /** 费比小数(如 0.052)转为与前端一致的百分比数值(5.2) */ + private static double bd2FeeRatioPercent(BigDecimal ratio) { + if (ratio == null) { + return 0.0; + } + return ratio.multiply(new BigDecimal("100")).setScale(1, RoundingMode.HALF_UP).doubleValue(); } private CellStyle createTitleStyle(Workbook workbook) { @@ -353,6 +540,14 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic return style; } + private CellStyle createBoldDataStyle(Workbook workbook) { + CellStyle style = createDataStyle(workbook); + Font font = workbook.createFont(); + font.setBold(true); + style.setFont(font); + return style; + } + private void setCell(Row row, int col, String value, CellStyle style) { Cell cell = row.createCell(col); cell.setCellValue(value != null ? value : "");