diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CategoryExportExcelService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CategoryExportExcelService.java index a067b501..efba9a7e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CategoryExportExcelService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CategoryExportExcelService.java @@ -1,6 +1,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.overview.service; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; /** * 按品类维度导出 Excel(店铺「门店品类汇总」与全店「品类概览」共用实现) @@ -8,4 +9,10 @@ import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportD public interface CategoryExportExcelService { byte[] exportCategoryOverview(CategoryExportDTO dto); + + /** + * 全店按品类:与 {@link top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService#getCompanyOverview} 同源, + * 生成「品类汇总 + 销售趋势」两表。 + */ + byte[] exportStoreCategoryFromOverview(CategoryExportDTO dto, CompanyOverviewVO overview); } 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 de3cacef..e975f6d6 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 @@ -34,6 +34,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; @@ -82,194 +83,53 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic @Override public byte[] exportCategoryOverview(CategoryExportDTO dto) { - if (dto.getShopId() != null) { - return exportShopCategoryViaOverview(dto); + if (dto.getShopId() == null) { + throw new BusinessException("全店按品类导出请使用 ExportService.exportCategoryOverview"); } - Long companyId = currentUserContext.getCurrentCompanyId(); + 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]; - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; + String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT); - OrderStatusStatSets stat = exportStatusRangeHelper.resolveStat(companyId); - List unionStatusIds = stat.getUnionStatusIds(); - - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, unionStatusIds); - } else { - orderWrapper.isNull(OrderPO::getId); - } - List orders = orderMapper.selectList(orderWrapper); - - LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); - promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - List promotionFees = promotionFeeMapper.selectList(promoWrapper); - - LambdaQueryWrapper brushWrapper = new LambdaQueryWrapper<>(); - brushWrapper.eq(BrushOrderPO::getCompanyId, companyId) - .ge(BrushOrderPO::getBrushTime, startDate.atStartOfDay()) - .le(BrushOrderPO::getBrushTime, endDate.atTime(23, 59, 59)); - List brushOrders = brushOrderMapper.selectList(brushWrapper); - - List specIds = orders.stream() - .map(OrderPO::getProductSpecId) - .filter(Objects::nonNull) - .distinct() - .collect(Collectors.toList()); - Map specIdToProductId = new HashMap<>(); - if (!specIds.isEmpty()) { - List specs = productSpecMapper.selectList(new LambdaQueryWrapper() - .in(ProductSpecPO::getId, specIds) - .select(ProductSpecPO::getId, ProductSpecPO::getProductId)); - for (ProductSpecPO s : specs) { - specIdToProductId.put(s.getId(), s.getProductId()); - } - } - List productIds = specIdToProductId.values().stream().filter(Objects::nonNull).distinct() - .collect(Collectors.toList()); - Map productCategoryMap = new HashMap<>(); - if (!productIds.isEmpty()) { - LambdaQueryWrapper productWrapper = new LambdaQueryWrapper<>(); - productWrapper.in(ProductPO::getId, productIds).select(ProductPO::getId, ProductPO::getCategoryId); - List products = productService.list(productWrapper); - for (ProductPO product : products) { - productCategoryMap.put(product.getId(), product.getCategoryId()); - } - } - - Map> ordersByCategory = orders.stream() - .collect(Collectors.groupingBy(order -> { - Long sid = order.getProductSpecId(); - Long pid = sid != null ? specIdToProductId.get(sid) : null; - Long categoryId = pid != null ? productCategoryMap.get(pid) : null; - return categoryId != null ? categoryId : -1L; - })); - - Map shopTotalPromoFeeMap = promotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId, - Collectors.reducing(BigDecimal.ZERO, - f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO, - BigDecimal::add))); - Map shopTotalBrushFeeMap = brushOrders.stream() - .collect(Collectors.groupingBy(BrushOrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, - b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO, - BigDecimal::add))); - - LambdaQueryWrapper categoryWrapper = new LambdaQueryWrapper<>(); - categoryWrapper.eq(CategoryPO::getCompanyId, companyId); - List allCategories = categoryService.list(categoryWrapper); - Map categoryNameMap = allCategories.stream() - .collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName)); - - List categoryDataList = new ArrayList<>(); - for (Map.Entry> entry : ordersByCategory.entrySet()) { - Long categoryId = entry.getKey(); - List categoryOrders = entry.getValue(); - - BigDecimal salesAmount = categoryOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - int orderCount = (int) categoryOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); - BigDecimal refundAmount = categoryOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal productCost = categoryOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal shippingCost = categoryOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal otherCost = categoryOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - Map categorySalesByShop = categoryOrders.stream() - .collect(Collectors.groupingBy(OrderPO::getShopId, - Collectors.reducing(BigDecimal.ZERO, stat::receivedForSales, BigDecimal::add))); - BigDecimal categoryTotalSales = categorySalesByShop.values().stream() - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - if (categoryTotalSales.compareTo(BigDecimal.ZERO) > 0) { - for (Map.Entry shopEntry : categorySalesByShop.entrySet()) { - Long shopId = shopEntry.getKey(); - BigDecimal ratio = shopEntry.getValue().divide(categoryTotalSales, 6, RoundingMode.HALF_UP); - totalPromotionFee = totalPromotionFee.add( - shopTotalPromoFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio)); - totalBrushFee = totalBrushFee.add( - shopTotalBrushFeeMap.getOrDefault(shopId, BigDecimal.ZERO).multiply(ratio)); - } - } - - BigDecimal totalCost = productCost.add(shippingCost).add(otherCost); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(totalPromotionFee).subtract(totalBrushFee); - BigDecimal salesTaxAmount = salesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? salesAmount.subtract(refundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0 - ? totalPromotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - BigDecimal avgOrderValue = orderCount > 0 - ? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) - : BigDecimal.ZERO; - - String categoryName = categoryId == -1L - ? "未分配品类" - : categoryNameMap.getOrDefault(categoryId, "Unknown"); - - CompanyOverviewVO.CategorySummary data = new CompanyOverviewVO.CategorySummary(); - data.setCategoryId(categoryId == -1L ? null : categoryId); - data.setCategoryName(categoryName); - data.setSalesAmount(salesAmount); - data.setOrderCount(orderCount); - data.setAverageOrderValue(avgOrderValue); - data.setProductCost(productCost); - data.setShippingCost(shippingCost); - data.setOtherCost(otherCost); - data.setTotalCost(totalCost); - data.setRefundAmount(refundAmount); - data.setTotalPromotionFee(totalPromotionFee); - data.setBrushFee(totalBrushFee); - data.setFeeRatio(feeRatio); - data.setTotalProfitBeforeTax(profitBeforeTax); - data.setSalesTaxAmount(salesTaxAmount); - data.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - data.setRoi(roi); - categoryDataList.add(data); - } + CompanyOverviewVO.CategoryOverview co = overview.getCategorySummary(); + List catRows = (co != null && co.getCategories() != null) + ? new ArrayList<>(co.getCategories()) + : new ArrayList<>(); if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) { - Set allowedIds = new HashSet<>(dto.getCategoryIds()); - categoryDataList = categoryDataList.stream() - .filter(c -> allowedIds.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L)) + Set allowed = new HashSet<>(dto.getCategoryIds()); + catRows = catRows.stream() + .filter(c -> allowed.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L)) .collect(Collectors.toList()); } - categoryDataList.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount).reversed()); - - String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT); - - List shopRows = categoryDataList.stream() + List shopRows = catRows.stream() .map(this::toShopCategorySummary) .collect(Collectors.toList()); - ShopOverviewStatisticsVO.CategorySummary totalRow = aggregateCategoryTotals(shopRows, taxRate); + + 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("品类汇总"); + 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(); @@ -320,6 +180,12 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic try (Workbook workbook = new XSSFWorkbook()) { Sheet sheet = workbook.createSheet("品类汇总"); writeCategoryMultidimensionalSheet(sheet, shopTitle, dateRangeLabel, rows, totalRow, taxRate); + if (vo.getSalesAmountTrend() != null + && vo.getSalesAmountTrend().getDailyDataList() != null + && !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) { + Sheet trendSheet = workbook.createSheet("销量趋势"); + writeShopSalesTrendSheet(trendSheet, shopTitle, dateRangeLabel, vo); + } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -329,6 +195,140 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic } } + /** 与店铺概览销量趋势同源({@link ShopOverviewStatisticsVO} 日销售额、日单量)。 */ + private void writeShopSalesTrendSheet( + Sheet sheet, String shopContextTitle, String dateRangeLabel, ShopOverviewStatisticsVO 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(shopContextTitle + " - 销量趋势 | " + 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 dailySales = vo.getSalesAmountTrend().getDailyDataList(); + List dailyOrders = vo.getOrderCountTrend() != null + ? vo.getOrderCountTrend().getDailyDataList() + : null; + + Map salesMap = dailySales.stream() + .collect(Collectors.toMap( + ShopOverviewStatisticsVO.TrendDataItem::getDate, + ShopOverviewStatisticsVO.TrendDataItem::getValue, + (a, b) -> a)); + Map ordersMap = dailyOrders != null + ? dailyOrders.stream() + .collect(Collectors.toMap( + ShopOverviewStatisticsVO.TrendDataItem::getDate, + ShopOverviewStatisticsVO.TrendDataItem::getValue, + (a, b) -> a)) + : Collections.emptyMap(); + + LocalDate startDate = dailySales.stream() + .map(ShopOverviewStatisticsVO.TrendDataItem::getDate) + .min(LocalDate::compareTo) + .orElse(null); + LocalDate endDate = dailySales.stream() + .map(ShopOverviewStatisticsVO.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); + } + + /** 全店概览 {@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 dailySales = vo.getSalesAmountTrend().getDailyDataList(); + List dailyOrders = vo.getOrderCountTrend() != null + ? vo.getOrderCountTrend().getDailyDataList() + : null; + + Map salesMap = dailySales.stream() + .collect(Collectors.toMap( + CompanyOverviewVO.TrendDataItem::getDate, + CompanyOverviewVO.TrendDataItem::getValue, + (a, b) -> a)); + Map 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); @@ -511,6 +511,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic font.setFontHeightInPoints((short) 14); style.setFont(font); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -526,6 +527,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -535,6 +537,8 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic 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; diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportServiceImpl.java index ce27c949..856a5d6a 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ExportServiceImpl.java @@ -1,38 +1,26 @@ package top.xyquan.ecomdmbbackend.modules.ecom.overview.service.impl; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 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.ecom.brushorder.mapper.BrushOrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService; -import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; -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.promotion.model.po.PromotionFeePO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.model.po.ShopMonthlyTargetPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; -import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.io.ByteArrayOutputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; -import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -44,118 +32,57 @@ public class ExportServiceImpl implements ExportService { private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - private final CurrentUserContext currentUserContext; - private final OrderMapper orderMapper; - private final PromotionFeeMapper promotionFeeMapper; - private final BrushOrderMapper brushOrderMapper; - private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; - private final ShopService shopService; - private final PlatformMapper platformMapper; private final ExportStatusRangeHelper exportStatusRangeHelper; private final CategoryExportExcelService categoryExportExcelService; + private final CompanyOverviewService companyOverviewService; - public ExportServiceImpl(CurrentUserContext currentUserContext, - OrderMapper orderMapper, - PromotionFeeMapper promotionFeeMapper, - BrushOrderMapper brushOrderMapper, - ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService, - PlatformMapper platformMapper, - ExportStatusRangeHelper exportStatusRangeHelper, - CategoryExportExcelService categoryExportExcelService) { - this.currentUserContext = currentUserContext; - this.orderMapper = orderMapper; - this.promotionFeeMapper = promotionFeeMapper; - this.brushOrderMapper = brushOrderMapper; - this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; - this.shopService = shopService; - this.platformMapper = platformMapper; + public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper, + CategoryExportExcelService categoryExportExcelService, + CompanyOverviewService companyOverviewService) { this.exportStatusRangeHelper = exportStatusRangeHelper; this.categoryExportExcelService = categoryExportExcelService; + this.companyOverviewService = companyOverviewService; } @Override public byte[] exportCompanyOverview(CompanyExportDTO dto) { - Long companyId = currentUserContext.getCurrentCompanyId(); - LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); + 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); - List shops = shopService.list( - new LambdaQueryWrapper().eq(ShopPO::getCompanyId, companyId) - ); + CompanyOverviewVO.ShopOverview shopOv = vo.getShopSummary(); + List shops = (shopOv != null && shopOv.getShops() != null) + ? new ArrayList<>(shopOv.getShops()) + : new ArrayList<>(); if (dto.getShopIds() != null && !dto.getShopIds().isEmpty()) { + Set allowed = new HashSet<>(dto.getShopIds()); shops = shops.stream() - .filter(s -> dto.getShopIds().contains(s.getId())) + .filter(s -> s.getShopId() != null && allowed.contains(s.getShopId())) .collect(Collectors.toList()); } - OrderStatusStatSets stat = exportStatusRangeHelper.resolveStat(companyId); - List unionStatusIds = stat.getUnionStatusIds(); - - List> shopDataList = new ArrayList<>(); - BigDecimal totalSales = BigDecimal.ZERO; - BigDecimal totalOrders = BigDecimal.ZERO; - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalProfitBeforeTax = BigDecimal.ZERO; - BigDecimal totalRefundAmount = BigDecimal.ZERO; - - BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; - - for (ShopPO shop : shops) { - Map data = buildShopData(shop, dateRange[0], dateRange[1], unionStatusIds, stat, companyId, taxRate); - shopDataList.add(data); - - totalSales = totalSales.add((BigDecimal) data.get("salesAmount")); - totalOrders = totalOrders.add(new BigDecimal((Integer) data.get("orderCount"))); - totalPromotionFee = totalPromotionFee.add((BigDecimal) data.get("totalPromotionFee")); - totalRefundAmount = totalRefundAmount.add((BigDecimal) data.get("refundAmount")); - totalBrushFee = totalBrushFee.add((BigDecimal) data.get("brushFee")); - totalProfitBeforeTax = totalProfitBeforeTax.add((BigDecimal) data.get("totalProfitBeforeTax")); - } - - // 计算汇总数据(税额按销售额比例,与全店概览一致) - BigDecimal totalTax = totalSales.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); - BigDecimal totalProfitAfterTax = totalProfitBeforeTax.subtract(totalTax); - BigDecimal totalCost = totalPromotionFee.add(totalBrushFee); - BigDecimal totalRoi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 - ? totalSales.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - BigDecimal avgFeeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 - ? totalPromotionFee.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - - // 查询所有店铺所有订单,用于趋势计算 - LocalDateTime startDateTime = dateRange[0].atStartOfDay(); - LocalDateTime endDateTime = dateRange[1].atTime(23, 59, 59); - LambdaQueryWrapper allOrdersWrapper = new LambdaQueryWrapper<>(); - allOrdersWrapper.eq(OrderPO::getCompanyId, companyId) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusIds.isEmpty()) { - allOrdersWrapper.in(OrderPO::getStatusId, unionStatusIds); - } else { - allOrdersWrapper.isNull(OrderPO::getId); - } - List allOrders = orderMapper.selectList(allOrdersWrapper); - Map> ordersByDate = allOrders.stream() - .collect(Collectors.groupingBy(o -> o.getOrderTime().toLocalDate())); + List> shopRows = shops.stream().map(this::shopSummaryToRowMap).collect(Collectors.toList()); + boolean shopFiltered = dto.getShopIds() != null && !dto.getShopIds().isEmpty(); + CompanyOverviewVO.ShopSummary totalShop = shopFiltered + ? aggregateShopSummariesForExport(shops, taxRate) + : (shopOv != null && shopOv.getTotal() != null ? shopOv.getTotal() : aggregateShopSummariesForExport(shops, taxRate)); + Map totalRowMap = shopSummaryToRowMap(totalShop); + LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); String dateRangeLabel = dateRange[0].format(DATE_FMT) + " 至 " + dateRange[1].format(DATE_FMT); try (Workbook workbook = new XSSFWorkbook()) { Sheet summarySheet = workbook.createSheet("汇总"); - createSummarySheet(summarySheet, dateRangeLabel, totalSales, totalOrders, totalPromotionFee, - totalBrushFee, avgFeeRatio, totalProfitBeforeTax, totalTax, totalProfitAfterTax, totalRoi); - - String exportType = dto.getExportType() == null ? "all" : dto.getExportType(); - if ("detail".equals(exportType) || "all".equals(exportType)) { - Sheet detailSheet = workbook.createSheet("店铺明细"); - createCompanyDetailSheet(detailSheet, dateRangeLabel, shopDataList, taxRate); - } - - if (("trend".equals(exportType) || "all".equals(exportType)) && !ordersByDate.isEmpty()) { + createCompanyDetailSheet( + summarySheet, "全店 - 按店铺汇总", dateRangeLabel, shopRows, taxRate, totalRowMap); + if (vo.getSalesAmountTrend() != null + && vo.getSalesAmountTrend().getDailyDataList() != null + && !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) { Sheet trendSheet = workbook.createSheet("销售趋势"); - createTrendSheet(trendSheet, dateRangeLabel, ordersByDate, dateRange[0], dateRange[1], stat); + writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, vo); } - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -167,86 +94,79 @@ public class ExportServiceImpl implements ExportService { @Override public byte[] exportCategoryOverview(CategoryExportDTO dto) { - return categoryExportExcelService.exportCategoryOverview(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 createSummarySheet(Sheet sheet, String dateRangeLabel, BigDecimal totalSales, BigDecimal totalOrders, - BigDecimal totalPromotionFee, BigDecimal totalBrushFee, - BigDecimal avgFeeRatio, BigDecimal profitBeforeTax, - BigDecimal tax, BigDecimal profitAfterTax, BigDecimal roi) { - CellStyle titleStyle = createTitleStyle(sheet.getWorkbook()); - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); - - String[] headers = {"全店总销售额", "全店总单量", "总推广费", "总刷单费", "平均费比", - "税前总盈亏", "总税额", "税后总盈亏", "汇总ROI"}; - Object[] values = { - totalSales.setScale(2, RoundingMode.HALF_UP), - totalOrders.intValue(), - totalPromotionFee.setScale(2, RoundingMode.HALF_UP), - totalBrushFee.setScale(2, RoundingMode.HALF_UP), - avgFeeRatio.setScale(4, RoundingMode.HALF_UP), - profitBeforeTax.setScale(2, RoundingMode.HALF_UP), - tax.setScale(2, RoundingMode.HALF_UP), - profitAfterTax.setScale(2, RoundingMode.HALF_UP), - roi.setScale(4, RoundingMode.HALF_UP) - }; - - int colCount = headers.length; - - // 标题行 - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("全店概览汇总 | " + dateRangeLabel); - titleCell.setCellStyle(titleStyle); - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colCount - 1)); - - // 表头行 - 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); - } - - // 数据行 - Row dataRow = sheet.createRow(2); - for (int i = 0; i < values.length; i++) { - Cell cell = dataRow.createCell(i); - cell.setCellStyle(dataStyle); - Object val = values[i]; - if (val instanceof BigDecimal) { - int scale = (i == 4 || i == 8) ? 4 : 2; - cell.setCellValue(((BigDecimal) val).setScale(scale, RoundingMode.HALF_UP).doubleValue()); - } else { - cell.setCellValue(val.toString()); - } - } - - for (int i = 0; i < headers.length; i++) { - sheet.setColumnWidth(i, 3200); - } + private void createCompanyDetailSheet( + Sheet sheet, + String summaryTitle, + String dateRangeLabel, + List> shopDataList, + BigDecimal taxRate, + Map totalRowMap) { + createOverviewDimensionSheet( + sheet, + summaryTitle, + dateRangeLabel, + shopDataList, + taxRate, + totalRowMap, + "店铺名称", + m -> m.get("shopName") != null ? m.get("shopName").toString() : ""); } - private void createCompanyDetailSheet(Sheet sheet, String dateRangeLabel, List> shopDataList, BigDecimal taxRate) { + private void createPlatformSummarySheet( + Sheet sheet, + String summaryTitle, + String dateRangeLabel, + List> platformRows, + BigDecimal taxRate, + Map totalRowMap) { + createOverviewDimensionSheet( + sheet, + summaryTitle, + dateRangeLabel, + platformRows, + taxRate, + totalRowMap, + "平台名称", + m -> m.get("platformName") != null ? m.get("platformName").toString() : ""); + } + + private void createOverviewDimensionSheet( + Sheet sheet, + String summaryTitle, + String dateRangeLabel, + List> dataList, + BigDecimal taxRate, + Map totalRowMap, + String firstColumnHeader, + Function, String> firstColumnValue) { + Workbook wb = sheet.getWorkbook(); Row titleRow = sheet.createRow(0); Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("店铺明细 | " + dateRangeLabel); - titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook())); + titleCell.setCellValue(summaryTitle + " | " + dateRangeLabel); + titleCell.setCellStyle(createTitleStyle(wb)); String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额"; String[] headers = { - "店铺名称", "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)", - "实际销售额", "单量", "客单价", - "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比", - "税前盈亏", taxLabel, "ROI", "税后盈亏" + firstColumnHeader, "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)", + "实际销售额", "单量", "客单价", + "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比", + "税前盈亏", taxLabel, "ROI", "税后盈亏" }; sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1)); - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); - - // 列顺序与 Dashboard 表格一致 + CellStyle headerStyle = createHeaderStyle(wb); + CellStyle dataStyle = createDataStyle(wb); + CellStyle boldStyle = createBoldDataStyle(wb); Row headerRow = sheet.createRow(1); for (int i = 0; i < headers.length; i++) { @@ -256,28 +176,13 @@ public class ExportServiceImpl implements ExportService { } int rowIdx = 2; - for (Map data : shopDataList) { + for (Map data : dataList) { Row row = sheet.createRow(rowIdx++); - setCell(row, 0, (String) data.get("shopName"), dataStyle); - setCell(row, 1, objToDouble(data.get("targetOrderCount")), dataStyle); - setCell(row, 2, objToPct(data.get("orderCountAchievementRate")), dataStyle); - setCell(row, 3, objToDouble(data.get("targetAmount")), dataStyle); - setCell(row, 4, objToPct(data.get("salesAchievementRate")), dataStyle); - setCell(row, 5, objToDouble(data.get("salesAmount")), dataStyle); - setCell(row, 6, objToDouble(data.get("orderCount")), dataStyle); - setCell(row, 7, objToDouble(data.get("avgOrderValue")), dataStyle); - setCell(row, 8, objToDouble(data.get("productCost")), dataStyle); - setCell(row, 9, objToDouble(data.get("shippingCost")), dataStyle); - setCell(row, 10, objToDouble(data.get("otherCost")), dataStyle); - setCell(row, 11, objToDouble(data.get("totalCost")), dataStyle); - setCell(row, 12, objToDouble(data.get("refundAmount")), dataStyle); - setCell(row, 13, objToDouble(data.get("totalPromotionFee")), dataStyle); - setCell(row, 14, objToDouble(data.get("brushFee")), dataStyle); - setCell(row, 15, objToDouble(data.get("feeRatio")), dataStyle); - setCell(row, 16, objToDouble(data.get("totalProfitBeforeTax")), dataStyle); - setCell(row, 17, objToDouble(data.get("salesTaxAmount")), dataStyle); - setCell(row, 18, objToDouble(data.get("roi")), dataStyle); - setCell(row, 19, objToDouble(data.get("profitAfterTax")), dataStyle); + writeOverviewDetailRow(row, data, dataStyle, firstColumnValue.apply(data)); + } + if (totalRowMap != null) { + Row row = sheet.createRow(rowIdx); + writeOverviewDetailRow(row, totalRowMap, boldStyle, firstColumnValue.apply(totalRowMap)); } for (int i = 0; i < headers.length; i++) { @@ -285,6 +190,291 @@ public class ExportServiceImpl implements ExportService { } } + private void writeOverviewDetailRow(Row row, Map data, CellStyle style, String firstColumnText) { + setCell(row, 0, firstColumnText, style); + setCell(row, 1, objToDouble(data.get("targetOrderCount")), style); + setCell(row, 2, objToPct(data.get("orderCountAchievementRate")), style); + setCell(row, 3, objToDouble(data.get("targetAmount")), style); + setCell(row, 4, objToPct(data.get("salesAchievementRate")), style); + setCell(row, 5, objToDouble(data.get("salesAmount")), style); + setCell(row, 6, objToDouble(data.get("orderCount")), style); + setCell(row, 7, objToDouble(data.get("avgOrderValue")), style); + setCell(row, 8, objToDouble(data.get("productCost")), style); + setCell(row, 9, objToDouble(data.get("shippingCost")), style); + setCell(row, 10, objToDouble(data.get("otherCost")), style); + setCell(row, 11, objToDouble(data.get("totalCost")), style); + setCell(row, 12, objToDouble(data.get("refundAmount")), style); + setCell(row, 13, objToDouble(data.get("totalPromotionFee")), style); + setCell(row, 14, objToDouble(data.get("brushFee")), style); + setCell(row, 15, objToDouble(data.get("feeRatio")), style); + setCell(row, 16, objToDouble(data.get("totalProfitBeforeTax")), style); + setCell(row, 17, objToDouble(data.get("salesTaxAmount")), style); + setCell(row, 18, objToDouble(data.get("roi")), style); + setCell(row, 19, objToDouble(data.get("profitAfterTax")), style); + } + + private Map shopSummaryToRowMap(CompanyOverviewVO.ShopSummary s) { + Map data = new HashMap<>(); + data.put("shopName", s.getShopName()); + data.put("targetOrderCount", s.getTargetOrderCount()); + data.put("orderCountAchievementRate", s.getOrderCountAchievementRate()); + data.put("targetAmount", s.getTargetAmount()); + data.put("salesAchievementRate", s.getSalesAmountAchievementRate()); + data.put("salesAmount", s.getSalesAmount()); + data.put("orderCount", s.getOrderCount()); + data.put("avgOrderValue", s.getAverageOrderValue()); + data.put("productCost", s.getProductCost()); + data.put("shippingCost", s.getShippingCost()); + data.put("otherCost", s.getOtherCost()); + data.put("totalCost", s.getTotalCost()); + data.put("refundAmount", s.getRefundAmount()); + data.put("totalPromotionFee", s.getTotalPromotionFee()); + data.put("brushFee", s.getBrushFee()); + data.put("feeRatio", s.getFeeRatio()); + data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax()); + data.put("salesTaxAmount", s.getSalesTaxAmount()); + data.put("roi", s.getRoi()); + data.put("profitAfterTax", s.getProfitAfterTax()); + return data; + } + + private CompanyOverviewVO.ShopSummary aggregateShopSummariesForExport( + List shops, BigDecimal taxRate) { + 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; + + for (CompanyOverviewVO.ShopSummary s : shops) { + totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : 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 = 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; + 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.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.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; + } + + private Map platformSummaryToRowMap(CompanyOverviewVO.PlatformSummary s) { + Map data = new HashMap<>(); + data.put("platformName", s.getPlatformName()); + data.put("targetOrderCount", s.getTargetOrderCount()); + data.put("orderCountAchievementRate", s.getOrderCountAchievementRate()); + data.put("targetAmount", s.getTargetAmount()); + data.put("salesAchievementRate", s.getSalesAmountAchievementRate()); + data.put("salesAmount", s.getSalesAmount()); + data.put("orderCount", s.getOrderCount()); + data.put("avgOrderValue", s.getAverageOrderValue()); + data.put("productCost", s.getProductCost()); + data.put("shippingCost", s.getShippingCost()); + data.put("otherCost", s.getOtherCost()); + data.put("totalCost", s.getTotalCost()); + data.put("refundAmount", s.getRefundAmount()); + data.put("totalPromotionFee", s.getTotalPromotionFee()); + data.put("brushFee", s.getBrushFee()); + data.put("feeRatio", s.getFeeRatio()); + data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax()); + data.put("salesTaxAmount", s.getSalesTaxAmount()); + data.put("roi", s.getRoi()); + data.put("profitAfterTax", s.getProfitAfterTax()); + return data; + } + + private CompanyOverviewVO.PlatformSummary aggregatePlatformSummariesForExport( + List platforms, BigDecimal taxRate) { + 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; + + for (CompanyOverviewVO.PlatformSummary s : platforms) { + totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : 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 = 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; + 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.PlatformSummary total = new CompanyOverviewVO.PlatformSummary(); + total.setPlatformId(0L); + total.setPlatformName("合计"); + total.setSalesAmount(totalSales); + 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.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; + } + + 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 dailySales = vo.getSalesAmountTrend().getDailyDataList(); + List dailyOrders = vo.getOrderCountTrend() != null + ? vo.getOrderCountTrend().getDailyDataList() + : null; + + Map salesMap = dailySales.stream() + .collect(Collectors.toMap( + CompanyOverviewVO.TrendDataItem::getDate, + CompanyOverviewVO.TrendDataItem::getValue, + (a, b) -> a)); + Map 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(); @@ -300,186 +490,6 @@ public class ExportServiceImpl implements ExportService { return 0.0; } - private void createTrendSheet(Sheet sheet, String dateRangeLabel, - Map> ordersByDate, - LocalDate startDate, LocalDate endDate, - OrderStatusStatSets stat) { - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); - - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("销售趋势 | " + dateRangeLabel); - titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook())); - sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(0, 0, 0, 3)); - - 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); - } - - int rowIdx = 2; - LocalDate current = startDate; - while (!current.isAfter(endDate)) { - List dayOrders = ordersByDate.getOrDefault(current, Collections.emptyList()); - - BigDecimal salesAmount = dayOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) dayOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); - BigDecimal avgOrderValue = orderCount > 0 - ? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; - - Row row = sheet.createRow(rowIdx++); - setCell(row, 0, current.format(DATE_FMT), dataStyle); - setCell(row, 1, salesAmount.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 2, (double) orderCount, dataStyle); - setCell(row, 3, avgOrderValue.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - - current = current.plusDays(1); - } - - sheet.setColumnWidth(0, 3200); - sheet.setColumnWidth(1, 3200); - sheet.setColumnWidth(2, 3200); - sheet.setColumnWidth(3, 3200); - } - - // ==================== 数据构建方法 ==================== - - private Map buildShopData(ShopPO shop, LocalDate startDate, LocalDate endDate, - List unionStatusIds, OrderStatusStatSets stat, Long companyId, - BigDecimal taxRate) { - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); - - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .eq(OrderPO::getShopId, shop.getId()) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, unionStatusIds); - } else { - orderWrapper.isNull(OrderPO::getId); - } - List orders = orderMapper.selectList(orderWrapper); - - LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); - promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .eq(PromotionFeePO::getShopId, shop.getId()) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - List promotionFees = promotionFeeMapper.selectList(promoWrapper); - - LambdaQueryWrapper brushWrapper = new LambdaQueryWrapper<>(); - brushWrapper.eq(BrushOrderPO::getCompanyId, companyId) - .eq(BrushOrderPO::getShopId, shop.getId()) - .ge(BrushOrderPO::getBrushTime, startDateTime) - .le(BrushOrderPO::getBrushTime, endDateTime); - List brushOrders = brushOrderMapper.selectList(brushWrapper); - - // 目标数据 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .eq(ShopMonthlyTargetPO::getShopId, shop.getId()) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List targets = shopMonthlyTargetMapper.selectList(targetWrapper); - - BigDecimal targetAmount = targets.stream() - .map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - Integer targetOrderCount = targets.stream() - .mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0) - .sum(); - - // 计算各项指标(与全店概览:按订单状态各统计维度) - BigDecimal salesAmount = orders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - int orderCount = (int) orders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); - BigDecimal avgOrderValue = orderCount > 0 - ? salesAmount.divide(new BigDecimal(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; - - BigDecimal refundAmount = orders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal shippingCost = orders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal productCostTotal = orders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal otherCostTotal = orders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal promotionFee = promotionFees.stream() - .map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal brushFee = brushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalCost = productCostTotal.add(shippingCost).add(otherCostTotal); - BigDecimal profitBeforeTax = salesAmount.subtract(totalCost).subtract(refundAmount) - .subtract(promotionFee).subtract(brushFee); - BigDecimal tax = salesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); - BigDecimal profitAfterTax = profitBeforeTax.subtract(tax); - BigDecimal feeRatio = salesAmount.compareTo(BigDecimal.ZERO) > 0 - ? promotionFee.divide(salesAmount, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - BigDecimal roi = promotionFee.compareTo(BigDecimal.ZERO) > 0 - ? salesAmount.subtract(refundAmount).divide(promotionFee, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - - BigDecimal salesAchievementRate = targetAmount.compareTo(BigDecimal.ZERO) > 0 - ? salesAmount.divide(targetAmount, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) : BigDecimal.ZERO; - BigDecimal orderAchievementRate = targetOrderCount > 0 - ? new BigDecimal(orderCount).divide(new BigDecimal(targetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) : BigDecimal.ZERO; - - Map data = new HashMap<>(); - data.put("shopName", shop.getName()); - data.put("platform", shop.getPlatformId() != null ? getPlatformNameById(shop.getPlatformId()) : null); - data.put("salesAmount", salesAmount); - data.put("orderCount", orderCount); - data.put("avgOrderValue", avgOrderValue); - data.put("totalPromotionFee", promotionFee); // 对齐 ShopComparison - data.put("brushFee", brushFee); - data.put("feeRatio", feeRatio); - data.put("refundAmount", refundAmount); - data.put("productCost", productCostTotal); - data.put("shippingCost", shippingCost); - data.put("otherCost", otherCostTotal); - data.put("totalCost", totalCost); - data.put("totalProfitBeforeTax", profitBeforeTax); // 对齐 ShopComparison - data.put("salesTaxAmount", tax); // 对齐 ShopComparison - data.put("profitAfterTax", profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - data.put("roi", roi); - data.put("targetAmount", targetAmount); - data.put("targetOrderCount", targetOrderCount); - data.put("salesAchievementRate", salesAchievementRate); - data.put("orderCountAchievementRate", orderAchievementRate); - return data; - } - // ==================== Excel 样式工具 ==================== private CellStyle createTitleStyle(Workbook workbook) { @@ -489,6 +499,7 @@ public class ExportServiceImpl implements ExportService { font.setFontHeightInPoints((short) 14); style.setFont(font); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -504,6 +515,7 @@ public class ExportServiceImpl implements ExportService { style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -516,6 +528,8 @@ 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; } @@ -525,6 +539,8 @@ 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; } @@ -534,11 +550,21 @@ 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; } + 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 : ""); @@ -559,218 +585,47 @@ public class ExportServiceImpl implements ExportService { @Override public byte[] exportPlatformOverview(PlatformExportDTO dto) { - Long companyId = currentUserContext.getCurrentCompanyId(); - LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); - LocalDate startDate = dateRange[0]; - LocalDate endDate = dateRange[1]; - LocalDateTime startDateTime = startDate.atStartOfDay(); - LocalDateTime endDateTime = endDate.atTime(23, 59, 59); 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); - OrderStatusStatSets stat = exportStatusRangeHelper.resolveStat(companyId); - List unionStatusIds = stat.getUnionStatusIds(); - - // 查询所有店铺并按平台分组 - List allShops = shopService.list( - new LambdaQueryWrapper().eq(ShopPO::getCompanyId, companyId) - ); - Map> shopsByPlatform = allShops.stream() - .filter(shop -> shop.getPlatformId() != null) - .collect(Collectors.groupingBy(ShopPO::getPlatformId)); - - // 按平台过滤 + CompanyOverviewVO.PlatformOverview platformOv = vo.getPlatformSummary(); + List platforms = (platformOv != null && platformOv.getPlatforms() != null) + ? new ArrayList<>(platformOv.getPlatforms()) + : new ArrayList<>(); if (dto.getPlatformIds() != null && !dto.getPlatformIds().isEmpty()) { - Set allowedPlatformIds = new HashSet<>(dto.getPlatformIds()); - shopsByPlatform = shopsByPlatform.entrySet().stream() - .filter(e -> allowedPlatformIds.contains(e.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + Set allowed = new HashSet<>(dto.getPlatformIds()); + platforms = platforms.stream() + .filter(p -> p.getPlatformId() != null && allowed.contains(p.getPlatformId())) + .collect(Collectors.toList()); } - // 获取当前公司的所有平台信息 - LambdaQueryWrapper platformWrapper = new LambdaQueryWrapper<>(); - platformWrapper.eq(PlatformPO::getCompanyId, companyId); - List allPlatforms = platformMapper.selectList(platformWrapper); - Map platformMap = allPlatforms.stream() - .collect(Collectors.toMap(PlatformPO::getId, p -> p)); + List> platformRows = platforms.stream() + .map(this::platformSummaryToRowMap) + .collect(Collectors.toList()); + boolean platformFiltered = dto.getPlatformIds() != null && !dto.getPlatformIds().isEmpty(); + CompanyOverviewVO.PlatformSummary totalPlatform = platformFiltered + ? aggregatePlatformSummariesForExport(platforms, taxRate) + : (platformOv != null && platformOv.getTotal() != null + ? platformOv.getTotal() + : aggregatePlatformSummariesForExport(platforms, taxRate)); + Map totalRowMap = platformSummaryToRowMap(totalPlatform); - // 生成目标月份列表 - List targetMonths = new ArrayList<>(); - LocalDate currentMonth = startDate.withDayOfMonth(1); - LocalDate endMonth = endDate.withDayOfMonth(1); - while (!currentMonth.isAfter(endMonth)) { - targetMonths.add(currentMonth); - currentMonth = currentMonth.plusMonths(1); - } - - // 查询所有目标数据 - LambdaQueryWrapper targetWrapper = new LambdaQueryWrapper<>(); - targetWrapper.eq(ShopMonthlyTargetPO::getCompanyId, companyId) - .in(ShopMonthlyTargetPO::getTargetMonth, targetMonths); - List allTargets = shopMonthlyTargetMapper.selectList(targetWrapper); - Map> targetsByShop = allTargets.stream() - .collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId)); - - // 查询所有订单 - LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); - orderWrapper.eq(OrderPO::getCompanyId, companyId) - .ge(OrderPO::getOrderTime, startDateTime) - .le(OrderPO::getOrderTime, endDateTime); - if (!unionStatusIds.isEmpty()) { - orderWrapper.in(OrderPO::getStatusId, unionStatusIds); - } else { - orderWrapper.isNull(OrderPO::getId); - } - List allOrders = orderMapper.selectList(orderWrapper); - Map> ordersByShop = allOrders.stream() - .collect(Collectors.groupingBy(OrderPO::getShopId)); - - // 查询推广费 - LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); - promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - List allPromotionFees = promotionFeeMapper.selectList(promoWrapper); - Map> promotionFeesByShop = allPromotionFees.stream() - .collect(Collectors.groupingBy(PromotionFeePO::getShopId)); - - // 查询刷单费 - LambdaQueryWrapper brushWrapper = new LambdaQueryWrapper<>(); - brushWrapper.eq(BrushOrderPO::getCompanyId, companyId) - .ge(BrushOrderPO::getBrushTime, startDateTime) - .le(BrushOrderPO::getBrushTime, endDateTime); - List allBrushOrders = brushOrderMapper.selectList(brushWrapper); - Map> brushOrdersByShop = allBrushOrders.stream() - .collect(Collectors.groupingBy(BrushOrderPO::getShopId)); - - // 按平台聚合数据 - List> platformDataList = new ArrayList<>(); - for (Map.Entry> entry : shopsByPlatform.entrySet()) { - Long platformId = entry.getKey(); - List platformShops = entry.getValue(); - PlatformPO platform = platformMap.get(platformId); - if (platform == null) continue; - - BigDecimal totalSalesAmount = BigDecimal.ZERO; - int totalOrderCount = 0; - BigDecimal totalRefundAmount = BigDecimal.ZERO; - BigDecimal totalProductCost = BigDecimal.ZERO; - BigDecimal totalShippingCost = BigDecimal.ZERO; - BigDecimal totalOtherCost = BigDecimal.ZERO; - BigDecimal totalPromotionFee = BigDecimal.ZERO; - BigDecimal totalBrushFee = BigDecimal.ZERO; - BigDecimal totalTargetAmount = BigDecimal.ZERO; - int totalTargetOrderCount = 0; - - for (ShopPO shop : platformShops) { - List shopOrders = ordersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopPromoFees = promotionFeesByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopBrushOrders = brushOrdersByShop.getOrDefault(shop.getId(), new ArrayList<>()); - List shopTargets = targetsByShop.getOrDefault(shop.getId(), new ArrayList<>()); - - BigDecimal shopSales = shopOrders.stream() - .map(stat::receivedForSales) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalSalesAmount = totalSalesAmount.add(shopSales); - totalOrderCount += (int) shopOrders.stream().filter(o -> stat.includesSales(o.getStatusId())).count(); - - BigDecimal shopRefund = shopOrders.stream() - .map(stat::receivedForRefund) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalRefundAmount = totalRefundAmount.add(shopRefund); - - BigDecimal shopProductCost = shopOrders.stream() - .map(stat::productCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalProductCost = totalProductCost.add(shopProductCost); - - BigDecimal shopShippingCost = shopOrders.stream() - .map(stat::freightCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalShippingCost = totalShippingCost.add(shopShippingCost); - - BigDecimal shopOtherCost = shopOrders.stream() - .map(stat::otherCostForStats) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalOtherCost = totalOtherCost.add(shopOtherCost); - - BigDecimal shopPromoFee = shopPromoFees.stream() - .map(f -> f.getFeeAmount() != null ? f.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalPromotionFee = totalPromotionFee.add(shopPromoFee); - - BigDecimal shopBrush = shopBrushOrders.stream() - .map(b -> b.getBrushAmount() != null ? b.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalBrushFee = totalBrushFee.add(shopBrush); - - BigDecimal shopTargetAmount = shopTargets.stream() - .map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - totalTargetAmount = totalTargetAmount.add(shopTargetAmount); - - int shopTargetOrderCount = shopTargets.stream() - .mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0) - .sum(); - totalTargetOrderCount += shopTargetOrderCount; - } - - 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 salesTaxAmount = totalSalesAmount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); - BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTaxAmount); - 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")) - : BigDecimal.ZERO; - BigDecimal orderAchievementRate = totalTargetOrderCount > 0 - ? new BigDecimal(totalOrderCount) - .divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100")) - : BigDecimal.ZERO; - - Map data = new HashMap<>(); - data.put("platformId", platformId); - data.put("platformName", platform.getPlatformName()); - data.put("targetOrderCount", totalTargetOrderCount); - data.put("orderCountAchievementRate", orderAchievementRate); - data.put("targetAmount", totalTargetAmount); - data.put("salesAmountAchievementRate", salesAchievementRate); - data.put("salesAmount", totalSalesAmount); - data.put("orderCount", totalOrderCount); - data.put("avgOrderValue", avgOrderValue); - data.put("productCost", totalProductCost); - data.put("shippingCost", totalShippingCost); - data.put("otherCost", totalOtherCost); - data.put("totalCost", totalCost); - data.put("refundAmount", totalRefundAmount); - data.put("totalPromotionFee", totalPromotionFee); - data.put("brushFee", totalBrushFee); - data.put("feeRatio", feeRatio); - data.put("totalProfitBeforeTax", profitBeforeTax); - data.put("salesTaxAmount", salesTaxAmount); - data.put("roi", roi); - data.put("profitAfterTax", profitAfterTax.setScale(2, RoundingMode.HALF_UP)); - platformDataList.add(data); - } - - platformDataList.sort((a, b) -> - ((BigDecimal) b.get("salesAmount")).compareTo((BigDecimal) a.get("salesAmount"))); - - String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT); + LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange()); + String dateRangeLabel = dateRange[0].format(DATE_FMT) + " 至 " + dateRange[1].format(DATE_FMT); try (Workbook workbook = new XSSFWorkbook()) { - Sheet sheet = workbook.createSheet("平台明细"); - createPlatformDetailSheet(sheet, dateRangeLabel, platformDataList, taxRate); + Sheet summarySheet = workbook.createSheet("汇总"); + createPlatformSummarySheet( + summarySheet, "全店 - 按平台汇总", dateRangeLabel, platformRows, taxRate, totalRowMap); + if (vo.getSalesAmountTrend() != null + && vo.getSalesAmountTrend().getDailyDataList() != null + && !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) { + Sheet trendSheet = workbook.createSheet("销售趋势"); + writeCompanyOverviewTrendSheet(trendSheet, "全店", dateRangeLabel, vo); + } try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { workbook.write(out); return out.toByteArray(); @@ -779,71 +634,4 @@ public class ExportServiceImpl implements ExportService { throw new BusinessException("导出平台Excel失败: " + e.getMessage()); } } - - private void createPlatformDetailSheet(Sheet sheet, String dateRangeLabel, - List> platformDataList, - BigDecimal taxRate) { - CellStyle titleStyle = createTitleStyle(sheet.getWorkbook()); - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); - - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("平台维度汇总 | " + dateRangeLabel); - titleCell.setCellStyle(titleStyle); - String taxLabel = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() + "%税额"; - String[] headers = { - "平台名称", "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)", - "实际销售额", "单量", "客单价", - "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", "费比", - "税前盈亏", taxLabel, "ROI", "税后盈亏" - }; - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1)); - - 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); - } - - int rowIdx = 2; - for (Map data : platformDataList) { - Row row = sheet.createRow(rowIdx++); - setCell(row, 0, (String) data.get("platformName"), dataStyle); - setCell(row, 1, objToDouble(data.get("targetOrderCount")), dataStyle); - setCell(row, 2, objToPct(data.get("orderCountAchievementRate")), dataStyle); - setCell(row, 3, objToDouble(data.get("targetAmount")), dataStyle); - setCell(row, 4, objToPct(data.get("salesAmountAchievementRate")), dataStyle); - setCell(row, 5, objToDouble(data.get("salesAmount")), dataStyle); - setCell(row, 6, objToDouble(data.get("orderCount")), dataStyle); - setCell(row, 7, objToDouble(data.get("avgOrderValue")), dataStyle); - setCell(row, 8, objToDouble(data.get("productCost")), dataStyle); - setCell(row, 9, objToDouble(data.get("shippingCost")), dataStyle); - setCell(row, 10, objToDouble(data.get("otherCost")), dataStyle); - setCell(row, 11, objToDouble(data.get("totalCost")), dataStyle); - setCell(row, 12, objToDouble(data.get("refundAmount")), dataStyle); - setCell(row, 13, objToDouble(data.get("totalPromotionFee")), dataStyle); - setCell(row, 14, objToDouble(data.get("brushFee")), dataStyle); - setCell(row, 15, objToPct(data.get("feeRatio")), dataStyle); - setCell(row, 16, objToDouble(data.get("totalProfitBeforeTax")), dataStyle); - setCell(row, 17, objToDouble(data.get("salesTaxAmount")), dataStyle); - setCell(row, 18, objToDouble(data.get("roi")), dataStyle); - setCell(row, 19, objToDouble(data.get("profitAfterTax")), dataStyle); - } - - for (int i = 0; i < headers.length; i++) { - sheet.setColumnWidth(i, 3200); - } - } - - private String getPlatformNameById(Long platformId) { - if (platformId == null) return null; - Long companyId = currentUserContext.getCurrentCompanyId(); - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(PlatformPO::getId, platformId) - .eq(PlatformPO::getCompanyId, companyId); - PlatformPO platform = platformMapper.selectOne(wrapper); - return platform != null ? platform.getPlatformName() : null; - } } \ No newline at end of file diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/shop/service/impl/ShopExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/shop/service/impl/ShopExportServiceImpl.java index 4bbbf15d..74afb44d 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/shop/service/impl/ShopExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/shop/service/impl/ShopExportServiceImpl.java @@ -18,7 +18,6 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.time.format.DateTimeFormatter; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -56,23 +55,28 @@ public class ShopExportServiceImpl implements ShopExportService { String exportType = dto.getExportType() == null ? "all" : dto.getExportType(); try (Workbook workbook = new XSSFWorkbook()) { - if ("summary".equals(exportType) || "all".equals(exportType)) { - Sheet summarySheet = workbook.createSheet("汇总"); - createShopSummarySheetFromVO(summarySheet, vo, dateRangeLabel); + // 与店铺概览一致:仅「按商品汇总」+「销量趋势」,不再导出第一张「汇总」指标表 + if (("product".equals(exportType) || "all".equals(exportType) || "summary".equals(exportType)) + && vo.getProductOverview() != null) { + List products = vo.getProductOverview().getProducts() != null + ? vo.getProductOverview().getProducts() + : Collections.emptyList(); + ShopOverviewStatisticsVO.ProductSummary totalRow = vo.getProductOverview().getTotal(); + Sheet productSheet = workbook.createSheet("按商品汇总"); + createProductDetailSheetFromVO( + productSheet, + vo.getShopName(), + dateRangeLabel, + products, + totalRow, + taxRate); } - if (("product".equals(exportType) || "all".equals(exportType)) - && vo.getProductOverview() != null && vo.getProductOverview().getProducts() != null - && !vo.getProductOverview().getProducts().isEmpty()) { - Sheet productSheet = workbook.createSheet("商品明细"); - createProductDetailSheetFromVO(productSheet, dateRangeLabel, vo.getProductOverview().getProducts(), taxRate); - } - - if (("trend".equals(exportType) || "all".equals(exportType)) + if (("trend".equals(exportType) || "all".equals(exportType) || "summary".equals(exportType)) && vo.getSalesAmountTrend() != null && vo.getSalesAmountTrend().getDailyDataList() != null && !vo.getSalesAmountTrend().getDailyDataList().isEmpty()) { - Sheet trendSheet = workbook.createSheet("销售趋势"); + Sheet trendSheet = workbook.createSheet("销量趋势"); createTrendSheetFromVO(trendSheet, dateRangeLabel, vo); } @@ -90,122 +94,34 @@ public class ShopExportServiceImpl implements ShopExportService { return categoryExportExcelService.exportCategoryOverview(dto); } - private void createShopSummarySheetFromVO(Sheet sheet, ShopOverviewStatisticsVO vo, String dateRangeLabel) { - CellStyle titleStyle = createTitleStyle(sheet.getWorkbook()); - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); - - List fields = Arrays.asList( - new SummaryField("销售额", "totalSalesAmount", true), - new SummaryField("单量", "totalOrderCount", false), - new SummaryField("客单价", "avgOrderValue", true), - new SummaryField("推广费", "totalPromotionFee", true), - new SummaryField("费比", "averageFeeRatio", true), - new SummaryField("退款金额", "refundAmount", true), - new SummaryField("税前盈亏", "profitBeforeTax", true), - new SummaryField("税额", "totalTaxAmount", true), - new SummaryField("税后盈亏", "totalNetProfitAfterTax", true), - new SummaryField("ROI", "totalROI", true), - new SummaryField("目标销售额", "totalTargetAmount", true), - new SummaryField("目标单量", "totalTargetOrderCount", false), - new SummaryField("销售额达成率(%)", "salesAmountAchievementRate", true), - new SummaryField("单量达成率(%)", "orderCountAchievementRate", true) - ); - - int colCount = fields.size() + 1; - - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue((vo.getShopName() != null ? vo.getShopName() : "") + " - 概览汇总 | " + dateRangeLabel); - titleCell.setCellStyle(titleStyle); - sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colCount - 1)); - - Row headerRow = sheet.createRow(1); - Cell h0 = headerRow.createCell(0); - h0.setCellValue("指标名称"); - h0.setCellStyle(headerStyle); - for (int c = 0; c < fields.size(); c++) { - Cell hCell = headerRow.createCell(c + 1); - hCell.setCellValue(fields.get(c).label); - hCell.setCellStyle(headerStyle); - } - - Row dataRow = sheet.createRow(2); - Cell shopNameCell = dataRow.createCell(0); - shopNameCell.setCellValue(vo.getShopName() != null ? vo.getShopName() : ""); - shopNameCell.setCellStyle(dataStyle); - - for (int c = 0; c < fields.size(); c++) { - SummaryField f = fields.get(c); - Cell cell = dataRow.createCell(c + 1); - cell.setCellStyle(dataStyle); - Object val = getVOFieldValue(vo, f.key); - if (val != null) { - if (val instanceof BigDecimal) { - int scale = ("averageFeeRatio".equals(f.key) || "totalROI".equals(f.key)) ? 4 : 2; - cell.setCellValue(((BigDecimal) val).setScale(scale, RoundingMode.HALF_UP).doubleValue()); - } else if (val instanceof Integer) { - cell.setCellValue(((Integer) val).doubleValue()); - } - } - } - - sheet.setColumnWidth(0, 4000); - for (int c = 0; c < fields.size(); c++) { - sheet.setColumnWidth(c + 1, 3200); - } - } - - private static class SummaryField { - final String label; - final String key; - @SuppressWarnings("unused") - final boolean isDecimal; - - SummaryField(String label, String key, boolean isDecimal) { - this.label = label; - this.key = key; - this.isDecimal = isDecimal; - } - } - - private Object getVOFieldValue(ShopOverviewStatisticsVO vo, String key) { - return switch (key) { - case "totalSalesAmount" -> vo.getTotalSalesAmount(); - case "totalOrderCount" -> vo.getTotalOrderCount(); - case "avgOrderValue" -> vo.getAverageOrderValue(); - case "totalPromotionFee" -> vo.getTotalPromotionFee(); - case "averageFeeRatio" -> vo.getAverageFeeRatio(); - case "refundAmount" -> vo.getRefundAmount(); - case "profitBeforeTax" -> vo.getTotalProfitBeforeTax(); - case "totalTaxAmount" -> vo.getTotalTaxAmount(); - case "totalNetProfitAfterTax" -> vo.getTotalNetProfitAfterTax(); - case "totalROI" -> vo.getTotalROI(); - case "totalTargetAmount" -> vo.getTotalTargetAmount(); - case "totalTargetOrderCount" -> vo.getTotalTargetOrderCount(); - case "salesAmountAchievementRate" -> vo.getSalesAmountAchievementRate(); - case "orderCountAchievementRate" -> vo.getOrderCountAchievementRate(); - default -> null; - }; - } - - private void createProductDetailSheetFromVO(Sheet sheet, String dateRangeLabel, - List products, - BigDecimal taxRate) { - Row titleRow = sheet.createRow(0); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("核心商品多维度损益汇总表 | " + dateRangeLabel); - titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook())); - - CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); - CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); + /** + * 列顺序与概览页 {@code ProductComparisonTable.vue} 一致;费比 % 为「×100 后一位小数」与前端展示一致;合计行与 {@code productOverview.total} 同源。 + */ + private void createProductDetailSheetFromVO( + Sheet sheet, + String shopName, + String dateRangeLabel, + List products, + ShopOverviewStatisticsVO.ProductSummary totalRow, + BigDecimal taxRate) { + Workbook wb = sheet.getWorkbook(); + CellStyle titleStyle = createTitleStyle(wb); + CellStyle headerStyle = createHeaderStyle(wb); + CellStyle dataStyle = createDataStyle(wb); + CellStyle totalStyle = createBoldDataStyle(wb); + String titlePrefix = (shopName != null && !shopName.isBlank() ? shopName : "店铺") + " - 按商品汇总"; String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额"; String[] headers = { - "商品详情", "销售额", "单量", "客单价", + "商品", "销售额", "单量", "客单价", "商品成本", "运费", "其他成本", "总成本", "退款金额", "推广费", "刷单费用", - "费比(%)", "单品ROI", "税前盈亏", taxLabel, "税后净利" + "费比 %", "单品 ROI", "税前盈亏", taxLabel, "税后净利" }; + + Row titleRow = sheet.createRow(0); + Cell titleCell = titleRow.createCell(0); + titleCell.setCellValue(titlePrefix + " | " + dateRangeLabel); + titleCell.setCellStyle(titleStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1)); Row headerRow = sheet.createRow(1); @@ -218,37 +134,57 @@ public class ShopExportServiceImpl implements ShopExportService { int rowIdx = 2; for (ShopOverviewStatisticsVO.ProductSummary p : products) { Row row = sheet.createRow(rowIdx++); - setCell(row, 0, p.getProductName() + (p.getProductCode() != null ? "\n编码: " + p.getProductCode() : ""), dataStyle); - setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 2, (double) nvl(p.getOrderCount(), 0), dataStyle); - setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 7, nvl(p.getTotalCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 8, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 9, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 10, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 11, nvl(p.getFeeRatio(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 14, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); - setCell(row, 15, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle); + fillProductDataRow(row, p, dataStyle, false); + } + if (totalRow != null) { + fillProductDataRow(sheet.createRow(rowIdx), totalRow, totalStyle, true); } - sheet.setColumnWidth(0, 5000); + sheet.setColumnWidth(0, 5200); for (int i = 1; i < headers.length; i++) { - sheet.setColumnWidth(i, 3200); + sheet.setColumnWidth(i, 3400); } } + private void fillProductDataRow( + Row row, + ShopOverviewStatisticsVO.ProductSummary p, + CellStyle style, + boolean isTotalRow) { + String nameCol = isTotalRow + ? "合计" + : (p.getProductName() != null ? p.getProductName() : "") + + (p.getProductCode() != null && !p.getProductCode().isBlank() + ? "\n编码: " + p.getProductCode() + : ""); + setCell(row, 0, nameCol, style); + setCell(row, 1, nvl(p.getSalesAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 2, (double) nvl(p.getOrderCount(), 0), style); + setCell(row, 3, nvl(p.getAverageOrderValue(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 4, nvl(p.getProductCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 5, nvl(p.getShippingCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 6, nvl(p.getOtherCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 7, nvl(p.getTotalCost(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 8, nvl(p.getRefundAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 9, nvl(p.getTotalPromotionFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 10, nvl(p.getBrushFee(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + BigDecimal fr = p.getFeeRatio(); + double feePct = fr == null ? 0.0 + : fr.multiply(new BigDecimal("100")).setScale(1, RoundingMode.HALF_UP).doubleValue(); + setCell(row, 11, feePct, style); + setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 14, nvl(p.getSalesTaxAmount(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + setCell(row, 15, nvl(p.getProfitAfterTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); + } + private void createTrendSheetFromVO(Sheet sheet, String dateRangeLabel, ShopOverviewStatisticsVO vo) { CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook()); CellStyle dataStyle = createDataStyle(sheet.getWorkbook()); Row titleRow = sheet.createRow(0); Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("销售趋势 | " + dateRangeLabel); + titleCell.setCellValue("销量趋势 | " + dateRangeLabel); titleCell.setCellStyle(createTitleStyle(sheet.getWorkbook())); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); @@ -312,6 +248,7 @@ public class ShopExportServiceImpl implements ShopExportService { font.setFontHeightInPoints((short) 14); style.setFont(font); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -327,6 +264,7 @@ public class ShopExportServiceImpl implements ShopExportService { style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } @@ -336,11 +274,21 @@ public class ShopExportServiceImpl implements ShopExportService { 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; } + 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 : "");