Merge remote-tracking branch 'origin/test' into test

This commit is contained in:
liuminghui
2026-11-17 17:47:57 +08:00
21 changed files with 1021 additions and 117 deletions
@@ -8,6 +8,8 @@ import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -16,6 +18,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.bms.common.annotation.Log;
@@ -38,6 +41,7 @@ import com.bms.price.domain.vo.PrcProfitReportProductRow;
import com.bms.price.domain.vo.PrcProfitReportQuery;
import com.bms.price.domain.vo.PrcProfitReportSummary;
import com.bms.price.service.IPrcProfitReportService;
import com.bms.price.task.PrcProfitReportExportRunner;
/** 产品/订单维度毛利报表。 */
@RestController
@@ -50,6 +54,9 @@ public class PrcProfitReportController extends BaseController
@Autowired
private OssStorage ossStorage;
@Autowired
private PrcProfitReportExportRunner exportRunner;
/** 客户筛选选项,沿用毛利报表的访问权限和查询范围。 */
@PreAuthorize("@ss.hasPermi('report:profit:list')")
@GetMapping("/customer-options")
@@ -105,6 +112,8 @@ public class PrcProfitReportController extends BaseController
public TableDataInfo orders(PrcProfitReportQuery query)
{
startPage();
// 分页总数由页面复用汇总订单数,订单明细仅执行分页查询。
PageHelper.getLocalPage().setCount(false);
List<PrcProfitReportOrderRow> rows = profitReportService.selectOrderRows(query);
return getDataTable(rows);
}
@@ -121,19 +130,23 @@ public class PrcProfitReportController extends BaseController
@Log(title = "毛利报表-订单维度", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('report:profit:export')")
@PostMapping("/orders/export")
public AjaxResult exportOrders(PrcProfitReportQuery query)
public AjaxResult exportOrders(@RequestBody PrcProfitReportQuery query)
{
PrcProfitReportExport export = beginExport("ORDER", "订单维度毛利分析");
try
{
List<PrcProfitReportOrderRow> rows = profitReportService.selectOrderRows(query);
return finishExport(export, rows, PrcProfitReportOrderRow.class, "订单毛利报表", query.getProfitRule());
}
catch (RuntimeException e)
{
failExport(export, e);
throw e;
}
return success(Map.of("taskId", exportRunner.submit(query, getUserId())));
}
@PreAuthorize("@ss.hasPermi('report:profit:export')")
@GetMapping("/orders/export/task/{taskId}")
public AjaxResult orderExportTask(@PathVariable String taskId)
{
return success(exportRunner.getTask(taskId, getUserId()));
}
@PreAuthorize("@ss.hasPermi('report:profit:export')")
@GetMapping("/orders/export/download/{taskId}")
public void downloadOrderExport(@PathVariable String taskId, HttpServletResponse response) throws Exception
{
exportRunner.download(taskId, getUserId(), response);
}
@Log(title = "毛利报表-产品维度", businessType = BusinessType.EXPORT)
@@ -104,6 +104,12 @@ class ProfitReportAreaFilterTest
String emptySql = statement.getBoundSql(query).getSql();
assertFalse(emptySql.contains("join ctr_customer c"));
assertTrue(emptySql.contains("and 1 = 0"));
query.setAreaCustomerIds(null);
query.setProductKeyword("EXP");
String productSql = statement.getBoundSql(query).getSql();
assertTrue(productSql.contains("p.product_code like concat('%', ?, '%')"));
assertTrue(productSql.contains("p.product_name like concat('%', ?, '%')"));
}
}
@@ -0,0 +1,324 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.*;
import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.zip.ZipFile;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.bms.common.config.BmsConfig;
import com.bms.common.core.redis.RedisCache;
import com.bms.common.exception.ServiceException;
import com.bms.common.utils.poi.ExcelUtil;
import com.bms.price.domain.PrcProfitReportExportTask;
import com.bms.price.domain.vo.PrcProfitReportOrderRow;
import com.bms.price.domain.vo.PrcProfitReportQuery;
import com.bms.price.enums.ProfitAreaRule;
import com.bms.price.service.IPrcProfitReportService;
import com.bms.price.task.PrcProfitReportExportRunner;
import com.github.pagehelper.PageHelper;
class ProfitReportAsyncExportTest
{
@TempDir
Path tempDir;
private String previousProfile;
@BeforeEach
void useTempProfile()
{
previousProfile = BmsConfig.getProfile();
new BmsConfig().setProfile(tempDir.toString());
}
@AfterEach
void restoreProfile()
{
new BmsConfig().setProfile(previousProfile);
PageHelper.clearPage();
}
@Test
void submissionQueuesWorkAndExportsAllRowsUsingTheSubmittedFiltersAndRegionColumns() throws Exception
{
for (String area : List.of("C", "GZ"))
{
AtomicInteger calls = new AtomicInteger();
HoldingExecutor executor = new HoldingExecutor();
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> {
calls.incrementAndGet();
assertNull(PageHelper.getLocalPage());
assertEquals(area, query.getCustomerArea());
assertEquals("UNBILLED", query.getArBillStatus());
assertEquals("P1", query.getProductCode());
query.setProfitRule(ProfitAreaRule.fromCustomerArea(area).name());
return List.of(row("ORDER-A"), row("ORDER-B"));
}), new MemoryRedis(), executor);
PrcProfitReportQuery query = query(area);
query.setProductCode("P1");
String taskId = runner.submit(query, 1L);
assertEquals(0, calls.get());
assertEquals("PENDING", runner.getTask(taskId, 1L).getStatus());
assertThrows(ServiceException.class, () -> runner.download(taskId, 1L, new MockHttpServletResponse()));
query.setProductCode("CHANGED-AFTER-SUBMIT");
PageHelper.startPage(2, 1);
executor.work.run();
PrcProfitReportExportTask task = runner.getTask(taskId, 1L);
assertEquals("SUCCESS", task.getStatus());
assertEquals(100, task.getPercent());
assertEquals(2, task.getRowCount());
assertEquals(1, calls.get());
assertNull(PageHelper.getLocalPage());
assertThrows(ServiceException.class, () -> runner.getTask(taskId, 2L));
assertThrows(ServiceException.class, () -> runner.download(taskId, 2L, new MockHttpServletResponse()));
Path file = tempDir.resolve("download").resolve(task.getStorageKey());
try (InputStream input = Files.newInputStream(file); Workbook workbook = WorkbookFactory.create(input))
{
var sheet = workbook.getSheetAt(0);
assertEquals(2, sheet.getLastRowNum());
Row header = sheet.getRow(0);
assertEquals(area.equals("C"), hasColumn(header, "产品价(目录价)"));
assertEquals(area.equals("C"), hasColumn(header, "红线毛利"));
assertTrue(hasColumn(header, "销售价"));
}
MockHttpServletResponse response = new MockHttpServletResponse();
runner.download(taskId, 1L, response);
assertArrayEquals(Files.readAllBytes(file), response.getContentAsByteArray());
assertTrue(response.getHeader("Content-Disposition").contains(".xlsx"));
}
}
@Test
void rejectedExecutionAndQueryFailuresBecomeVisibleFailedTasks() throws Exception
{
ThreadPoolTaskExecutor rejected = new ThreadPoolTaskExecutor() {
@Override
public void execute(Runnable task) { throw new TaskRejectedException("busy"); }
};
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> {
fail("Rejected tasks must not query orders");
return List.of();
}), new MemoryRedis(), rejected);
String rejectedId = runner.submit(query("C"), 1L);
assertEquals("FAIL", runner.getTask(rejectedId, 1L).getStatus());
assertEquals("导出任务较多,请稍后重试", runner.getTask(rejectedId, 1L).getError());
HoldingExecutor executor = new HoldingExecutor();
PrcProfitReportExportRunner failing = new PrcProfitReportExportRunner(service(query -> {
throw new ServiceException("该客户区域未配置毛利规则");
}), new MemoryRedis(), executor);
String failedId = failing.submit(query("INVALID"), 1L);
executor.work.run();
PrcProfitReportExportTask failed = failing.getTask(failedId, 1L);
assertEquals("FAIL", failed.getStatus());
assertEquals("该客户区域未配置毛利规则", failed.getError());
assertNull(failed.getStorageKey());
assertThrows(ServiceException.class, () -> failing.download(failedId, 1L, new MockHttpServletResponse()));
assertFalse(Files.exists(tempDir.resolve("download/profitReportExport/" + failedId + ".xlsx")));
}
@Test
void exportsMoreThanLegacySheetLimitIntoOneSheet() throws Exception
{
int rowCount = ExcelUtil.sheetSize + 1;
List<PrcProfitReportOrderRow> rows = Collections.nCopies(rowCount, row("ORDER-LARGE"));
HoldingExecutor executor = new HoldingExecutor();
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> rows),
new MemoryRedis(), executor);
String taskId = runner.submit(query("C"), 1L);
executor.work.run();
PrcProfitReportExportTask task = runner.getTask(taskId, 1L);
assertEquals("SUCCESS", task.getStatus());
assertEquals(rowCount, task.getRowCount());
Path file = tempDir.resolve("download").resolve(task.getStorageKey());
assertEquals(1, countWorkbookSheets(file));
assertEquals(rowCount + 1, lastWorksheetRowNumber(file));
}
@Test
void rejectsRowsBeyondTheSingleSheetLimit()
{
List<PrcProfitReportOrderRow> rows = Collections.nCopies(ExcelUtil.XLSX_MAX_ROW_COUNT, row("ORDER-LARGE"));
HoldingExecutor executor = new HoldingExecutor();
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> rows),
new MemoryRedis(), executor);
String taskId = runner.submit(query("C"), 1L);
executor.work.run();
PrcProfitReportExportTask task = runner.getTask(taskId, 1L);
assertEquals("FAIL", task.getStatus());
assertTrue(task.getError().contains("单个工作表最多支持1048575条订单"));
assertFalse(Files.exists(tempDir.resolve("download/profitReportExport/" + taskId + ".xlsx")));
}
@Test
void cleanupRemovesOnlyExpiredExportFiles() throws Exception
{
Path dir = Files.createDirectories(tempDir.resolve("download/profitReportExport"));
Path old = Files.writeString(dir.resolve("a".repeat(32) + ".xlsx"), "old");
Path recent = Files.writeString(dir.resolve("b".repeat(32) + ".xlsx"), "new");
Path other = Files.writeString(dir.resolve("unrelated.xlsx"), "other");
FileTime expired = FileTime.from(Instant.now().minusSeconds(TimeUnit.HOURS.toSeconds(25)));
Files.setLastModifiedTime(old, expired);
Files.setLastModifiedTime(other, expired);
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> List.of()),
new MemoryRedis(), new HoldingExecutor());
runner.cleanupExpiredFiles();
assertFalse(Files.exists(old));
assertTrue(Files.exists(recent));
assertTrue(Files.exists(other));
}
@Test
void jsonSubmissionRetainsTheListDateRangeAndFilters() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
PrcProfitReportQuery query = mapper.readValue("""
{"customerArea":"C", "beginBizDate":"2026-10-18 00:00:00",
"endBizDate":"2026-11-17 23:59:59", "arBillStatus":"UNBILLED", "orderNo":"A\\nB"}
""", PrcProfitReportQuery.class);
assertEquals(Instant.parse("2026-10-17T16:00:00Z"), query.getBeginBizDate().toInstant());
assertEquals(Instant.parse("2026-11-17T15:59:59Z"), query.getEndBizDate().toInstant());
assertEquals("A\nB", query.getOrderNo());
assertEquals("UNBILLED", query.getArBillStatus());
}
private static PrcProfitReportQuery query(String area)
{
PrcProfitReportQuery query = new PrcProfitReportQuery();
query.setCustomerArea(area);
query.setArBillStatus("UNBILLED");
return query;
}
private static PrcProfitReportOrderRow row(String orderNo)
{
PrcProfitReportOrderRow row = new PrcProfitReportOrderRow();
row.setOrderNo(orderNo);
row.setSalesAmount(new BigDecimal("26.60"));
row.setArBillStatus("UNBILLED");
return row;
}
private static boolean hasColumn(Row header, String name)
{
for (var cell : header) if (name.equals(cell.getStringCellValue())) return true;
return false;
}
private static int countWorkbookSheets(Path file) throws Exception
{
try (ZipFile workbook = new ZipFile(file.toFile());
InputStream input = workbook.getInputStream(workbook.getEntry("xl/workbook.xml")))
{
XMLStreamReader reader = xmlInputFactory().createXMLStreamReader(input);
int count = 0;
try
{
while (reader.hasNext())
{
if (reader.next() == XMLStreamReader.START_ELEMENT && "sheet".equals(reader.getLocalName()))
{
count++;
}
}
}
finally
{
reader.close();
}
return count;
}
}
private static int lastWorksheetRowNumber(Path file) throws Exception
{
try (ZipFile workbook = new ZipFile(file.toFile());
InputStream input = workbook.getInputStream(workbook.getEntry("xl/worksheets/sheet1.xml")))
{
XMLStreamReader reader = xmlInputFactory().createXMLStreamReader(input);
int lastRowNumber = 0;
try
{
while (reader.hasNext())
{
if (reader.next() == XMLStreamReader.START_ELEMENT && "row".equals(reader.getLocalName()))
{
lastRowNumber = Integer.parseInt(reader.getAttributeValue(null, "r"));
}
}
}
finally
{
reader.close();
}
return lastRowNumber;
}
}
private static XMLInputFactory xmlInputFactory()
{
XMLInputFactory factory = XMLInputFactory.newFactory();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
return factory;
}
private static IPrcProfitReportService service(Function<PrcProfitReportQuery, List<PrcProfitReportOrderRow>> query)
{
return (IPrcProfitReportService) Proxy.newProxyInstance(ProfitReportAsyncExportTest.class.getClassLoader(),
new Class<?>[] { IPrcProfitReportService.class }, (proxy, method, args) -> {
if ("selectOrderRows".equals(method.getName())) return query.apply((PrcProfitReportQuery) args[0]);
throw new AssertionError("Unexpected service call: " + method.getName());
});
}
private static class HoldingExecutor extends ThreadPoolTaskExecutor
{
private Runnable work;
@Override
public void execute(Runnable task) { work = task; }
}
private static class MemoryRedis extends RedisCache
{
private final Map<String, Object> values = new HashMap<>();
@Override
public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit unit)
{
values.put(key, value);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getCacheObject(String key) { return (T) values.get(key); }
}
}
@@ -111,11 +111,12 @@ public class ExcelUtil<T>
*/
private Map<String, CellStyle> cellStyleCache = new HashMap<String, CellStyle>();
/**
* Excel sheet最大行数,默认65536
*/
/** 通用导出的默认每个工作表数据行数;单工作表 XLSX 导出使用 XLSX 实际上限。 */
public static final int sheetSize = 65536;
/** XLSX 工作表的最大行数。 */
public static final int XLSX_MAX_ROW_COUNT = 1_048_576;
/**
* 工作表名称
*/
@@ -796,6 +797,28 @@ public class ExcelUtil<T>
}
}
/** 写入单个 XLSX 工作表;超出 Excel 行数上限时返回明确错误。 */
public void exportExcelToSingleSheetStream(List<T> list, String sheetName, OutputStream output) throws IOException
{
try
{
this.init(list, sheetName, StringUtils.EMPTY, Type.EXPORT);
int reservedRows = rownum + 1 + (hasStatisticsColumns() ? 1 : 0);
int maxDataRows = XLSX_MAX_ROW_COUNT - reservedRows;
if (this.list.size() > maxDataRows)
{
throw new IOException(StringUtils.format("单个工作表最多支持{}条数据,当前{}条,请缩小查询范围",
maxDataRows, this.list.size()));
}
writeSheet(maxDataRows);
wb.write(output);
}
finally
{
IOUtils.closeQuietly(wb);
}
}
/** 对 list 数据源生成本地 Excel 文件,返回文件名。 */
public AjaxResult exportExcel()
{
@@ -824,9 +847,14 @@ public class ExcelUtil<T>
* 创建写入数据到Sheet
*/
public void writeSheet()
{
writeSheet(sheetSize);
}
private void writeSheet(int rowsPerSheet)
{
// 取出一共有多少个sheet.
int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / rowsPerSheet));
for (int index = 0; index < sheetNo; index++)
{
createSheet(sheetNo, index);
@@ -855,7 +883,7 @@ public class ExcelUtil<T>
}
if (Type.EXPORT.equals(type))
{
fillExcelData(index);
fillExcelData(index, rowsPerSheet);
addStatisticsRow();
}
}
@@ -869,8 +897,13 @@ public class ExcelUtil<T>
@SuppressWarnings("unchecked")
public void fillExcelData(int index)
{
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, list.size());
fillExcelData(index, sheetSize);
}
private void fillExcelData(int index, int rowsPerSheet)
{
int startNo = index * rowsPerSheet;
int endNo = Math.min(startNo + rowsPerSheet, list.size());
int currentRowNum = rownum + 1; // 从标题行后开始
for (int i = startNo; i < endNo; i++)
@@ -931,6 +964,18 @@ public class ExcelUtil<T>
}
}
private boolean hasStatisticsColumns()
{
for (Object[] field : fields)
{
if (((Excel) field[1]).isStatistics())
{
return true;
}
}
return false;
}
/**
* 获取子列表最大数
*/
@@ -0,0 +1,23 @@
package com.bms.price.config;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/** 毛利分析导出专用线程池,限制全量订单查询与 Excel 生成的并发。 */
@Configuration
public class ProfitReportExportTaskConfig
{
@Bean(name = "profitReportExportTaskExecutor")
public ThreadPoolTaskExecutor profitReportExportTaskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(2);
executor.setThreadNamePrefix("profit-report-export-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
return executor;
}
}
@@ -0,0 +1,21 @@
package com.bms.price.domain;
import java.io.Serializable;
import lombok.Data;
/** 毛利分析订单异步导出任务的临时状态。 */
@Data
public class PrcProfitReportExportTask implements Serializable
{
private static final long serialVersionUID = 1L;
private String taskId;
private Long userId;
private String status;
private int percent;
private String message;
private String error;
private int rowCount;
private String fileName;
private String storageKey;
}
@@ -2,6 +2,7 @@ package com.bms.price.domain.vo;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import com.bms.common.core.domain.BaseEntity;
import lombok.Data;
@@ -15,8 +16,10 @@ public class PrcProfitReportQuery extends BaseEntity
private static final long serialVersionUID = 1L;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date beginBizDate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endBizDate;
private String orderNo;
/** 订单号拆分后的多值查询条件。 */
@@ -34,6 +37,8 @@ public class PrcProfitReportQuery extends BaseEntity
/** 客户名称拆分后的多值查询条件。 */
private List<String> customerNames;
private String belongSalerCode;
/** 产品代码或产品名称的统一模糊查询关键字。 */
private String productKeyword;
private String productCode;
private String productName;
private String countryCode;
@@ -235,7 +235,9 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
BigDecimal calcWeight = resolveBillCalcWeight(request, existed, systemWeight);
request.setWeight(calcWeight);
TmsPriceQuoteResult result = tmsPriceQuoteService.calculate(request);
persistBill(request, systemWeight, bizDate, result);
// 规则命中时覆盖落库 weight;有 charge_weight 覆盖时保留原系统 weight
BigDecimal persistWeight = resolvePersistSystemWeight(request, existed, systemWeight, calcWeight);
persistBill(request, persistWeight, bizDate, result);
return result;
}
catch (RuntimeException e)
@@ -2083,8 +2085,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
bill.setCountryName(result.getCountryName());
}
// weight=上游计费重(DIMENSIONAL_WEIGHT_FACTOR);charge_weight=客户确认重/人工修改
bill.setWeight(weight);
// weight:默认上游系统重;业务规则命中时写入规则计费重;charge_weight=客户确认重/人工修改
bill.setWeight(weight);
bill.setBizDate(bizDate);
bill.setTmsId(request.getTmsId() == null ? null : Long.valueOf(request.getTmsId()));
bill.setPriceSetId(result.getPriceSetId());
@@ -3136,6 +3138,25 @@ bill.setWeight(weight);
return applyBizRuleWeight(request, systemWeight);
}
/**
* 落库 weight:无 charge_weight 覆盖时写入计费用重(含规则命中结果);
* 有客户确认重/人工改重时保留原系统 weight。
*/
private BigDecimal resolvePersistSystemWeight(TmsPriceBillRequest request, PrcOrderBill existed,
BigDecimal systemWeight, BigDecimal calcWeight)
{
BigDecimal preferred = positiveOrNull(request == null ? null : request.getChargeWeight());
if (preferred == null && !isUpstreamSyncRequest(request) && hasChargeWeightOverride(existed))
{
preferred = existed.getChargeWeight();
}
if (preferred != null)
{
return systemWeight;
}
return calcWeight != null ? calcWeight : systemWeight;
}
/**
* 上游同步/软失败:weight=上游计费重;charge_weight=客户确认重(无值则 null)。
*/
@@ -3153,7 +3174,7 @@ bill.setWeight(weight);
}
/**
* 业务规则计费重量(THREE_SIDE / VOL_8000)。
* 业务规则计费重量(THREE_SIDE / USE_RECEIVE_WEIGHT / VOL_8000)。
* 如需禁用:注释掉 resolveWeightByRule 调用,始终返回 baseWeight。
*/
private BigDecimal applyBizRuleWeight(TmsPriceBillRequest request, BigDecimal baseWeight)
@@ -171,6 +171,10 @@ public class PrcProfitReportServiceImpl implements IPrcProfitReportService
}
query.setCustomerArea(query.getCustomerArea().trim());
query.setProfitRule(rule.name());
if (query.getBelongSalerCode() != null)
{
query.setBelongSalerCode(query.getBelongSalerCode().trim());
}
query.setOrderNos(splitFilterValues(query.getOrderNo(), "订单号"));
query.setCustomerCodes(splitFilterValues(query.getCustomerCode(), "客户代码"));
query.setCustomerNames(splitFilterValues(query.getCustomerName(), "客户名称"));
@@ -0,0 +1,194 @@
package com.bms.price.task;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import com.bms.common.config.BmsConfig;
import com.bms.common.core.redis.RedisCache;
import com.bms.common.exception.ServiceException;
import com.bms.common.utils.DateUtils;
import com.bms.common.utils.file.FileUtils;
import com.bms.common.utils.poi.ExcelUtil;
import com.bms.common.utils.uuid.IdUtils;
import com.bms.price.domain.PrcProfitReportExportTask;
import com.bms.price.domain.vo.PrcProfitReportOrderRow;
import com.bms.price.domain.vo.PrcProfitReportQuery;
import com.bms.price.enums.ProfitAreaRule;
import com.bms.price.service.IPrcProfitReportService;
import com.github.pagehelper.PageHelper;
/** 毛利分析订单异步导出,沿用应收生成预览的任务、轮询、下载流程。 */
@Component
public class PrcProfitReportExportRunner
{
private static final Logger log = LoggerFactory.getLogger(PrcProfitReportExportRunner.class);
private static final String CACHE_PREFIX = "report:profit:orders:export:";
private static final String REL_DIR = "profitReportExport";
private static final int TTL_MINUTES = 60;
private static final long FILE_RETENTION_MILLIS = TimeUnit.HOURS.toMillis(24);
private final IPrcProfitReportService reportService;
private final RedisCache redisCache;
private final ThreadPoolTaskExecutor executor;
public PrcProfitReportExportRunner(IPrcProfitReportService reportService, RedisCache redisCache,
@Qualifier("profitReportExportTaskExecutor") ThreadPoolTaskExecutor executor)
{
this.reportService = reportService;
this.redisCache = redisCache;
this.executor = executor;
}
public String submit(PrcProfitReportQuery query, Long userId)
{
if (query == null || userId == null)
{
throw new ServiceException("导出参数无效");
}
PrcProfitReportQuery snapshot = new PrcProfitReportQuery();
BeanUtils.copyProperties(query, snapshot);
String taskId = IdUtils.fastSimpleUUID();
String fileName = "订单维度毛利分析_" + DateUtils.dateTimeNow() + ".xlsx";
put(taskId, userId, "PENDING", 0, "排队中", null, 0, fileName, null);
try
{
executor.execute(() -> run(taskId, userId, snapshot, fileName));
}
catch (TaskRejectedException e)
{
put(taskId, userId, "FAIL", 100, "导出失败", "导出任务较多,请稍后重试", 0, fileName, null);
}
return taskId;
}
private void run(String taskId, Long userId, PrcProfitReportQuery query, String fileName)
{
Path file = null;
try
{
// 导出全部匹配订单,不使用页面分页,也不执行分页 COUNT。
PageHelper.clearPage();
put(taskId, userId, "RUNNING", 5, "正在查询订单", null, 0, fileName, null);
List<PrcProfitReportOrderRow> rows = reportService.selectOrderRows(query);
put(taskId, userId, "RUNNING", 40, "正在生成 Excel", null, rows.size(), fileName, null);
int maxRows = ExcelUtil.XLSX_MAX_ROW_COUNT - 1;
if (rows.size() > maxRows)
{
throw new ServiceException(String.format("单个工作表最多支持%d条订单,当前%d条,请缩小查询范围",
maxRows, rows.size()));
}
ExcelUtil<PrcProfitReportOrderRow> util = new ExcelUtil<>(PrcProfitReportOrderRow.class);
if (ProfitAreaRule.GUANGZHOU.name().equals(query.getProfitRule()))
{
util.hideColumn("costAmount", "redlineGrossProfit", "redlineGrossMarginRate");
}
Path dir = Paths.get(BmsConfig.getDownloadPath(), REL_DIR).toAbsolutePath().normalize();
Files.createDirectories(dir);
file = dir.resolve(taskId + ".xlsx").normalize();
try (OutputStream output = Files.newOutputStream(file))
{
util.exportExcelToSingleSheetStream(rows, "订单毛利报表", output);
}
put(taskId, userId, "SUCCESS", 100, "导出完成,正在下载", null, rows.size(), fileName,
REL_DIR + "/" + taskId + ".xlsx");
}
catch (Exception e)
{
log.error("毛利分析订单导出失败 taskId={}", taskId, e);
if (file != null)
{
try { Files.deleteIfExists(file); }
catch (Exception cleanupError) { log.warn("清理导出文件失败 taskId={}", taskId, cleanupError); }
}
String error = e instanceof ServiceException ? e.getMessage() : "导出失败,请稍后重试";
put(taskId, userId, "FAIL", 100, "导出失败", error, 0, fileName, null);
}
finally
{
PageHelper.clearPage();
}
}
public PrcProfitReportExportTask getTask(String taskId, Long userId)
{
PrcProfitReportExportTask task = redisCache.getCacheObject(CACHE_PREFIX + taskId);
if (task == null || userId == null || !userId.equals(task.getUserId()))
{
throw new ServiceException("导出任务不存在或已过期");
}
return task;
}
public void download(String taskId, Long userId, HttpServletResponse response) throws Exception
{
PrcProfitReportExportTask task = getTask(taskId, userId);
String storageKey = task.getStorageKey();
if (!"SUCCESS".equals(task.getStatus()) || storageKey == null || !FileUtils.checkAllowDownload(storageKey))
{
throw new ServiceException("导出文件尚未生成");
}
Path root = Paths.get(BmsConfig.getDownloadPath(), REL_DIR).toAbsolutePath().normalize();
Path file = Paths.get(BmsConfig.getDownloadPath()).toAbsolutePath().normalize().resolve(storageKey).normalize();
if (!file.startsWith(root) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS))
{
throw new ServiceException("导出文件不存在");
}
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
FileUtils.setAttachmentResponseHeader(response, task.getFileName());
FileUtils.writeBytes(file.toString(), response.getOutputStream());
}
@Scheduled(cron = "0 25 * * * ?")
public void cleanupExpiredFiles()
{
Path dir = Paths.get(BmsConfig.getDownloadPath(), REL_DIR).toAbsolutePath().normalize();
if (!Files.isDirectory(dir)) return;
long cutoff = System.currentTimeMillis() - FILE_RETENTION_MILLIS;
try (Stream<Path> files = Files.list(dir))
{
files.filter(file -> file.getFileName().toString().matches("[a-f0-9]{32}\\.xlsx"))
.filter(file -> Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS))
.forEach(file -> {
try
{
if (Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis() < cutoff)
{
Files.deleteIfExists(file);
}
}
catch (Exception e) { log.warn("清理过期毛利导出文件失败: {}", file, e); }
});
}
catch (Exception e) { log.warn("扫描过期毛利导出文件失败: {}", dir, e); }
}
private void put(String taskId, Long userId, String status, int percent, String message, String error,
int rowCount, String fileName, String storageKey)
{
PrcProfitReportExportTask task = new PrcProfitReportExportTask();
task.setTaskId(taskId);
task.setUserId(userId);
task.setStatus(status);
task.setPercent(percent);
task.setMessage(message);
task.setError(error);
task.setRowCount(rowCount);
task.setFileName(fileName);
task.setStorageKey(storageKey);
redisCache.setCacheObject(CACHE_PREFIX + taskId, task, TTL_MINUTES, TimeUnit.MINUTES);
}
}
@@ -131,6 +131,8 @@ public class ArBillServiceImpl implements IArBillService {
private static final int TEMPLATE_DATA_START_ROW = 5;
/** 模板的明细区只有第 5 行;超出的明细行插入在页脚前。 */
private static final int TEMPLATE_LAST_DETAIL_ROW = 5;
/** 明细与银行信息、合计区域之间固定保留一行空白。 */
private static final int EXPORT_FOOTER_GAP_ROWS = 1;
/** DrawingML 行号从 0 开始,插入点是模板第 5 行之后。 */
private static final int TEMPLATE_DRAWING_INSERT_ROW_INDEX = 5;
private static final int TEMPLATE_COLUMN_COUNT = 21;
@@ -1561,7 +1563,7 @@ public class ArBillServiceImpl implements IArBillService {
}
/**
* 明细超出模板预留行时,同步下移插入点之后的图片锚点,保持二维码与页脚的相对位置。
* 根据明细新增行及页脚前空行,同步下移图片锚点,保持二维码与页脚的相对位置。
*/
private String shiftDrawingAnchorRows(String drawingXml, int rowOffset) {
if (rowOffset <= 0) {
@@ -1667,8 +1669,10 @@ public class ArBillServiceImpl implements IArBillService {
}
int lastDetailRow = Math.max(rowIndex - 1, TEMPLATE_LAST_DETAIL_ROW);
int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW;
writeOoxmlFooter(output, templateRows, lastDetailRow, bill, styleIndexes.generalNumber());
int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW + EXPORT_FOOTER_GAP_ROWS;
writeUtf8(output, "<row r=\"" + (lastDetailRow + 1) + "\" ht=\""
+ EXPORT_DETAIL_ROW_HEIGHT + "\" customHeight=\"true\"/>");
writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber());
String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset);
writeUtf8(output, suffix);
return rowOffset;
@@ -1778,9 +1782,8 @@ public class ArBillServiceImpl implements IArBillService {
return rows;
}
private void writeOoxmlFooter(OutputStream output, Map<Integer, String> templateRows, int lastDetailRow,
private void writeOoxmlFooter(OutputStream output, Map<Integer, String> templateRows, int rowOffset,
ArBill bill, int generalNumberStyleIndex) throws IOException {
int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW;
String totalAmountFormula = "SUM(S" + TEMPLATE_DATA_START_ROW + ":INDEX(S:S,ROW()-1))";
for (int offset = 0; offset < 4; offset++) {
int sourceRowNumber = TEMPLATE_LAST_DETAIL_ROW + offset + 1;
@@ -21,7 +21,7 @@ public interface IBmsBizRuleService
int deleteByIds(Long[] ruleIds);
/**
* 将生效的重量规则(THREE_SIDE / VOL_8000)应用到计费请求。
* 将生效的重量规则(THREE_SIDE / USE_RECEIVE_WEIGHT / VOL_8000)应用到计费请求。
* @return 规则命中时返回覆盖后的计费重量;无规则适用时返回 null
*/
BigDecimal resolveWeightByRule(TmsPriceBillRequest request, BigDecimal systemWeight);
@@ -27,6 +27,8 @@ public class BmsBizRuleServiceImpl implements IBmsBizRuleService
public static final String RULE_TYPE_THREE_SIDE = "THREE_SIDE";
/** 计费重量 = max(L*W*H/8000, weightSource)。 */
public static final String RULE_TYPE_VOL_8000 = "VOL_8000";
/** 命中后按取值字段取重(默认实重/收货重)。 */
public static final String RULE_TYPE_USE_RECEIVE_WEIGHT = "USE_RECEIVE_WEIGHT";
public static final String WEIGHT_SOURCE_RECEIVE = "RECEIVE_WEIGHT";
public static final String WEIGHT_SOURCE_CHARGE = "CHARGE_WEIGHT";
public static final String WEIGHT_SOURCE_VOLUME = "VOLUME_WEIGHT";
@@ -137,11 +139,17 @@ public class BmsBizRuleServiceImpl implements IBmsBizRuleService
return null;
}
// 先三边之和取重,未命中再走 VOL_8000
// 优先:三边 > 取实重(收货重) > VOL_8000
BigDecimal threeSide = resolveThreeSideWeight(request, systemWeight);
if (threeSide != null)
{
return threeSide;
}
BigDecimal useReceive = resolveUseReceiveWeight(request, systemWeight);
if (useReceive != null)
{
return useReceive;
}
BigDecimal vol8000 = resolveVol8000(request, systemWeight);
if (vol8000 != null)
{
@@ -223,6 +231,34 @@ public class BmsBizRuleServiceImpl implements IBmsBizRuleService
return null;
}
/**
* 取实重(收货重):按产品/国家/客户/重量段命中后,
* 按取值字段取重(默认 RECEIVE_WEIGHT:实重优先,次收货重)。
*/
private BigDecimal resolveUseReceiveWeight(TmsPriceBillRequest request, BigDecimal systemWeight)
{
List<BmsBizRule> rules = bizRuleMapper.selectActiveByType(RULE_TYPE_USE_RECEIVE_WEIGHT);
if (rules == null || rules.isEmpty())
{
return null;
}
for (BmsBizRule rule : rules)
{
if (!matchVol8000(rule, request, systemWeight))
{
continue;
}
String source = StringUtils.isEmpty(rule.getWeightSource())
? WEIGHT_SOURCE_RECEIVE : rule.getWeightSource();
BigDecimal picked = pickWeight(source, request, systemWeight);
if (picked != null)
{
return picked.setScale(3, RoundingMode.HALF_UP);
}
}
return null;
}
private boolean matchVol8000(BmsBizRule rule, TmsPriceBillRequest request, BigDecimal systemWeight)
{
if (rule == null)
@@ -571,7 +607,9 @@ public class BmsBizRuleServiceImpl implements IBmsBizRuleService
{
throw new ServiceException("规则类型不能为空");
}
if (RULE_TYPE_VOL_8000.equalsIgnoreCase(row.getRuleType()) && StringUtils.isEmpty(row.getWeightSource()))
if ((RULE_TYPE_VOL_8000.equalsIgnoreCase(row.getRuleType())
|| RULE_TYPE_USE_RECEIVE_WEIGHT.equalsIgnoreCase(row.getRuleType()))
&& StringUtils.isEmpty(row.getWeightSource()))
{
row.setWeightSource(WEIGHT_SOURCE_RECEIVE);
}
@@ -197,12 +197,18 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and p.country_code &lt;=&gt; #{countryCode}
and i.currency &lt;=&gt; #{currency}
<if test="belongSalerCode != null and belongSalerCode != ''">
and i.belong_saler_code = #{belongSalerCode}
and (i.belong_saler_code = #{belongSalerCode}
or p.belong_saler_code = #{belongSalerCode}
or i.belong_saler like concat('%', #{belongSalerCode}, '%')
or p.belong_saler like concat('%', #{belongSalerCode}, '%'))
</if>
</when>
<otherwise>
<if test="belongSalerCode != null and belongSalerCode != ''">
and i.belong_saler_code = #{belongSalerCode}
and (i.belong_saler_code = #{belongSalerCode}
or p.belong_saler_code = #{belongSalerCode}
or i.belong_saler like concat('%', #{belongSalerCode}, '%')
or p.belong_saler like concat('%', #{belongSalerCode}, '%'))
</if>
<if test="productCode != null and productCode != ''">
and p.product_code = #{productCode}
@@ -215,6 +221,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</if>
</otherwise>
</choose>
<if test="productKeyword != null and productKeyword != ''">
and (p.product_code like concat('%', #{productKeyword}, '%')
or p.product_name like concat('%', #{productKeyword}, '%'))
</if>
<if test="productName != null and productName != ''">
and p.product_name like concat('%', #{productName}, '%')
</if>
@@ -0,0 +1,7 @@
-- USE_RECEIVE_WEIGHT: hit by product/country/customer/weight range, use receive/actual weight
SET NAMES utf8mb4;
INSERT INTO sys_dict_data (dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark)
SELECT 3, N'取实重(收货重)', 'USE_RECEIVE_WEIGHT', 'bms_biz_rule_type', '', 'warning', 'N', '0', 'admin', sysdate(),
N'命中后按取值字段取重;实重优先 actual_weight,次收货重 receive_weight'
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM sys_dict_data WHERE dict_type = 'bms_biz_rule_type' AND dict_value = 'USE_RECEIVE_WEIGHT');
+1 -1
View File
@@ -48,7 +48,7 @@ export function listProfitProducts(params) {
}
export function exportProfitOrders(params) {
return createProfitExport('/report/profit/orders/export', params)
return request({ url: '/report/profit/orders/export', method: 'post', data: params })
}
export function exportProfitProducts(params) {
+24
View File
@@ -0,0 +1,24 @@
function formatLocalDate(date) {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
// 次月没有对应日期时取月末,再减一天;起止日期均包含当天。
export function maxEndDate(start) {
const [year, month, day] = start.split('-').map(Number)
const lastDayOfNextMonth = new Date(year, month + 1, 0).getDate()
const limit = new Date(year, month, Math.min(day, lastDayOfNextMonth))
limit.setDate(limit.getDate() - 1)
return formatLocalDate(limit)
}
export function defaultDateRange() {
const end = new Date()
const start = new Date(end.getFullYear(), end.getMonth(), end.getDate())
const endText = formatLocalDate(end)
start.setDate(start.getDate() - 31)
while (maxEndDate(formatLocalDate(start)) < endText) start.setDate(start.getDate() + 1)
return [formatLocalDate(start), endText]
}
@@ -112,6 +112,14 @@
style="margin-bottom: 12px"
title="计费重 = max(长×宽×高(cm)/8000, 收货重);无尺寸时不覆盖"
/>
<el-alert
v-if="form.ruleType === 'USE_RECEIVE_WEIGHT'"
type="info"
:closable="false"
show-icon
style="margin-bottom: 12px"
title="命中后按取值字段取重;实重优先 actual_weight,次收货重 receive_weight"
/>
<el-form-item label="状态" prop="status">
<el-radio-group v-model="form.status">
<el-radio value="0">正常</el-radio>
@@ -33,8 +33,9 @@
<el-table-column :label="colBoundChannels" min-width="180" show-overflow-tooltip>
<template #default="{ row }">{{ boundChannelText(row) }}</template>
</el-table-column>
<el-table-column :label="colAction" width="90" align="center" fixed="right">
<el-table-column :label="colAction" width="160" align="center" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="openDetail(row)" v-hasPermi="['price:label:query']">查看详情</el-button>
<el-button link type="primary" @click="openBindList(row)" v-hasPermi="['price:label:edit']">绑定</el-button>
</template>
</el-table-column>
@@ -112,6 +113,23 @@
<el-button type="primary" :loading="addSaving" @click="submitAddChannels">保存</el-button>
</template>
</el-dialog>
<el-drawer
v-model="detailVisible"
:title="detailTitle"
size="78%"
append-to-body
destroy-on-close
@closed="onDetailClosed"
>
<div v-loading="detailLoading">
<label-config-detail v-if="detailProduct" :product="detailProduct" :editable="false" />
<el-empty v-else-if="!detailLoading" description="暂无产品明细" />
</div>
<template #footer>
<el-button @click="detailVisible = false">关闭</el-button>
</template>
</el-drawer>
</el-drawer>
</template>
@@ -119,9 +137,11 @@
import {
listLabelProducts,
listLabelProductChannels,
replaceLabelProductChannels
replaceLabelProductChannels,
getLabelProduct
} from '@/api/price/label'
import { listChannelOptions } from '@/api/masterdata/serviceChannel'
import LabelConfigDetail from './LabelConfigDetail.vue'
const props = defineProps({
visible: { type: Boolean, default: false },
@@ -145,6 +165,14 @@ const addVisible = ref(false)
const addLoading = ref(false)
const addSaving = ref(false)
const addChannelIds = ref([])
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailProduct = ref(null)
const detailTitle = computed(() => {
if (!detailProduct.value) return '产品明细'
return detailProduct.value.productName || detailProduct.value.sheetName || '产品明细'
})
const phSearch = '产品名称 / 绑定渠道'
const colId = '产品编号'
@@ -261,6 +289,26 @@ async function loadBoundChannels() {
}
}
async function openDetail(row) {
if (!row?.productId) return
detailVisible.value = true
detailLoading.value = true
detailProduct.value = null
try {
const res = await getLabelProduct(row.productId, row.versionId || row.termId)
detailProduct.value = res.data || row
} catch (e) {
detailProduct.value = row
} finally {
detailLoading.value = false
}
}
function onDetailClosed() {
detailProduct.value = null
detailLoading.value = false
}
async function openBindList(row) {
if (!row?.productId) return
bindProductId.value = row.productId
+76 -38
View File
@@ -1,31 +1,45 @@
<template>
<div class="app-container ar-profit-report">
<el-card shadow="never">
<el-form :model="query" inline @submit.prevent>
<el-form-item label="账单日期">
<el-date-picker v-model="dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
</el-form-item>
<el-form-item label="客户">
<customer-select v-model="query.customerId" :fetch-options="listArBillCustomerOptions"
placeholder="请输入客户名称或代码搜索" :remote-search="true" :page-size="20" />
</el-form-item>
<el-form-item label="销售员">
<el-select v-model="query.salesUserId" placeholder="姓名或工号搜索" clearable filterable remote
:remote-method="searchSales" :loading="salesLoading" style="width: 180px"
@input="handleSalesInput">
<el-option v-for="person in salesOptions" :key="person.userId" :label="person.name || person.code || String(person.userId)" :value="person.userId">
<span>{{ person.name || person.code || person.userId }}</span>
<span v-if="person.code" class="sales-code">{{ person.code }}</span>
</el-option>
</el-select>
</el-form-item>
<el-form-item label="账单号"><el-input v-model="query.billNo" clearable @keyup.enter="search" /></el-form-item>
<el-form-item label="状态">
<el-select v-model="query.status" placeholder="全部状态" clearable style="width: 140px">
<el-option label="已确认" value="CONFIRMED" /><el-option label="部分核销" value="PARTIAL_WRITTEN_OFF" /><el-option label="已核销" value="WRITTEN_OFF" />
</el-select>
</el-form-item>
<el-form-item><el-button type="primary" icon="Search" @click="search">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button></el-form-item>
<el-card shadow="never" class="search-card">
<el-form :model="query" label-width="88px" @submit.prevent>
<el-row :gutter="16">
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="账单日期" class="filter-item" :error="dateRangeError" required>
<el-date-picker v-model="dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="filter-control" />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="客户" class="filter-item">
<customer-select v-model="query.customerId" :fetch-options="listArBillCustomerOptions"
placeholder="请输入客户名称或代码搜索" :remote-search="true" :page-size="20" class="filter-control" />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="销售员" class="filter-item">
<el-select v-model="query.salesUserId" placeholder="姓名或工号搜索" clearable filterable remote
:remote-method="searchSales" :loading="salesLoading" class="filter-control"
@input="handleSalesInput">
<el-option v-for="person in salesOptions" :key="person.userId" :label="person.name || person.code || String(person.userId)" :value="person.userId">
<span>{{ person.name || person.code || person.userId }}</span>
<span v-if="person.code" class="sales-code">{{ person.code }}</span>
</el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="账单号" class="filter-item"><el-input v-model="query.billNo" clearable class="filter-control" @keyup.enter="search" /></el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="状态" class="filter-item">
<el-select v-model="query.status" placeholder="全部状态" clearable class="filter-control">
<el-option label="已确认" value="CONFIRMED" /><el-option label="部分核销" value="PARTIAL_WRITTEN_OFF" /><el-option label="已核销" value="WRITTEN_OFF" />
</el-select>
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<div class="filter-item filter-actions"><el-button type="primary" icon="Search" @click="search">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button></div>
</el-col>
</el-row>
</el-form>
</el-card>
@@ -179,6 +193,7 @@
import { listArBillCustomerOptions } from '@/api/ar/bill'
import { addArProfitRate, confirmArProfitMissingRate, listArProfitAreaRules, listArProfitBillDetails, listArProfitBills, listArProfitCommissions, listArProfitCommissionSummary, listArProfitFees, listArProfitMissingRates, listArProfitRates, listArProfitSalesOptions, listArProfitSummary, listArProfitWriteoffRates } from '@/api/report/arProfit'
import { parseTime } from '@/utils/bms'
import { defaultDateRange, maxEndDate } from '@/utils/reportDateRange'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
@@ -187,7 +202,11 @@ const salesOptions = ref([])
const salesLoading = ref(false)
let salesSearchVersion = 0
const areaRules = ref({})
const dateRange = ref(defaultBillDateRange())
const dateRange = ref(defaultDateRange())
const dateRangeError = computed(() => {
if (!dateRange.value?.[0] || !dateRange.value?.[1]) return ''
return dateRange.value[1] > maxEndDate(dateRange.value[0]) ? '账单日期最多查询一个月' : ''
})
const pageNum = ref(1), pageSize = ref(10), total = ref(0), rows = ref([]), loading = ref(false)
const summaries = ref([]), summaryLoaded = ref(false)
const detailsVisible = ref(false), detailsLoading = ref(false), details = ref([]), detailsTotal = ref(0)
@@ -211,18 +230,20 @@ const missingRates = ref([]), missingTotal = ref(0), missingPage = ref(1), missi
const confirmVisible = ref(false), confirmForm = reactive({ writeoffId: null, billNo: '', rate: null, remark: '' })
const writeoffRatesVisible = ref(false), writeoffRatesLoading = ref(false), writeoffRates = ref([])
function formatLocalDate(offset) {
const date = new Date()
date.setDate(date.getDate() + offset)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
function validateDateRange(showMessage = true) {
if (!dateRange.value?.[0] || !dateRange.value?.[1]) {
if (showMessage) ElMessage.warning('请选择完整的账单日期')
return false
}
if (dateRangeError.value) {
if (showMessage) ElMessage.warning(dateRangeError.value)
return false
}
return true
}
function defaultBillDateRange() { return [formatLocalDate(-30), formatLocalDate(0)] }
function params() { return { ...query, beginBillDate: dateRange.value?.[0], endBillDate: dateRange.value?.[1] } }
function search() { pageNum.value = 1; loadRows(); loadSummary() }
function reset() { Object.assign(query, { customerId: null, salesUserId: null, billNo: '', status: '' }); dateRange.value = defaultBillDateRange(); search() }
function search() { if (!validateDateRange()) return; pageNum.value = 1; loadRows(); loadSummary() }
function reset() { Object.assign(query, { customerId: null, salesUserId: null, billNo: '', status: '' }); dateRange.value = defaultDateRange(); search() }
function handleSalesInput() {
salesSearchVersion++
salesOptions.value = []
@@ -241,6 +262,7 @@ async function searchSales(keyword) {
}
}
function loadRows() {
if (!validateDateRange()) return
const version = ++requestVersion
loading.value = true
rows.value = []
@@ -250,6 +272,7 @@ function loadRows() {
}
let summaryVersion = 0
function loadSummary() {
if (!validateDateRange(false)) return
const version = ++summaryVersion
summaryLoaded.value = false
listArProfitSummary(params()).then(res => { if (version === summaryVersion) { summaries.value = res.data || []; summaryLoaded.value = true } })
@@ -263,7 +286,7 @@ async function loadBillDetails() {
finally { if (version === detailsVersion) detailsLoading.value = false }
}
async function openFees(row) { feeVisible.value = true; feeLoading.value = true; fees.value = []; try { fees.value = (await listArProfitFees(row.detailId)).data || [] } finally { feeLoading.value = false } }
function exportRows() { proxy.download('/report/ar-profit/export', params(), `应收账单毛利分析_${Date.now()}.xlsx`) }
function exportRows() { if (validateDateRange()) proxy.download('/report/ar-profit/export', params(), `应收账单毛利分析_${Date.now()}.xlsx`) }
function exportCommissions() { proxy.download('/report/ar-profit/commissions/export', {}, `应收账单提成明细_${Date.now()}.xlsx`) }
function money(v) { return v === null || v === undefined || v === '' || !Number.isFinite(Number(v)) ? '-' : Number(v).toFixed(2) }
function rate(v) { return v === null || v === undefined || v === '' || !Number.isFinite(Number(v)) ? '-' : Number(v).toFixed(2) + '%' }
@@ -318,11 +341,26 @@ async function confirmRate() {
if (confirmForm.rate === null || !confirmForm.remark.trim()) return ElMessage.warning('请填写比例及核对说明')
await confirmArProfitMissingRate(confirmForm); confirmVisible.value = false; ElMessage.success('已确认提成比例'); loadCommissionTab()
}
watch(dateRange, () => {
requestVersion++
summaryVersion++
rows.value = []
total.value = 0
loading.value = false
summaries.value = []
summaryLoaded.value = false
}, { flush: 'sync' })
listArProfitAreaRules().then(res => { areaRules.value = res.data || {} })
search()
</script>
<style scoped>
.search-card :deep(.el-card__body) { padding: 18px 20px 8px; }
.filter-item { width: 100%; margin-bottom: 14px; }
.filter-item :deep(.el-form-item__content) { min-width: 0; }
.filter-item :deep(.el-date-editor.el-input__wrapper) { width: 100%; }
.filter-control { width: 100%; }
.filter-actions { display: flex; align-items: center; }
.summary-card, .data-card { margin-top: 14px; }
.metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 14px; }
.metrics > div { min-width: 0; padding: 10px; background: var(--el-fill-color-lighter); color: var(--el-text-color-secondary); }
+116 -44
View File
@@ -1,7 +1,22 @@
<template>
<div class="app-container profit-report">
<Teleport to="body">
<div v-if="exportFloatVisible" class="export-status-float">
<el-tooltip :content="exportMessage || '点击查看详情'" placement="bottom">
<el-button class="export-status-button" type="warning" plain size="small" @click="exportProgressVisible = true">
<span class="export-progress-ring" :style="{ '--export-progress': exportDegree + 'deg' }" aria-hidden="true">
<span class="export-progress-value">{{ exportPercent }}%</span>
</span>
<span class="export-status-text">
<strong>{{ exportFloatTitle }}</strong>
<small>{{ exportFloatSummary }}</small>
</span>
</el-button>
</el-tooltip>
</div>
</Teleport>
<el-card shadow="never" class="search-card">
<el-form :model="query" label-width="88px" @submit.prevent>
<el-form :model="query" label-width="120px" @submit.prevent>
<el-row :gutter="16">
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="客户区域" class="filter-item">
@@ -11,7 +26,7 @@
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="计费日期" class="filter-item" required>
<el-form-item label="计费日期" class="filter-item" :error="dateRangeError" required>
<el-date-picker
v-model="dateRange"
type="daterange"
@@ -37,18 +52,13 @@
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="业务员编码" class="filter-item">
<el-input v-model="query.belongSalerCode" clearable placeholder="输入业务员编码" class="filter-control" @keyup.enter="handleSearch" />
<el-form-item label="业务员编码/姓名" class="filter-item">
<el-input v-model="query.belongSalerCode" clearable placeholder="输入业务员编码或姓名" class="filter-control" @keyup.enter="handleSearch" />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="产品代码" class="filter-item">
<el-input v-model="query.productCode" clearable placeholder="输入产品代码" class="filter-control" @keyup.enter="handleSearch" />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
<el-form-item label="产品名称" class="filter-item">
<el-input v-model="query.productName" clearable placeholder="输入产品名称" class="filter-control" @keyup.enter="handleSearch" />
<el-form-item label="产品代码/名称" class="filter-item">
<el-input v-model="query.productKeyword" clearable placeholder="输入产品代码或名称" class="filter-control" @keyup.enter="handleSearch" />
</el-form-item>
</el-col>
<el-col :xs="24" :sm="12" :lg="8">
@@ -141,7 +151,7 @@
<el-card shadow="never" class="table-card">
<div class="table-heading">
<span class="table-title">订单明细</span>
<span class="table-title">订单列表</span>
<div class="table-toolbar">
<!-- 提成功能暂停使用。
<el-button
@@ -156,9 +166,9 @@
icon="Download"
v-hasPermi="['report:profit:export']"
:loading="exporting"
:disabled="!hasProfitRule() || !hasSearched"
:disabled="!hasProfitRule() || !hasSearched || loading"
@click="handleExport"
>导出订单明细</el-button>
>导出订单</el-button>
</div>
</div>
@@ -202,6 +212,17 @@
/>
</el-card>
<el-dialog v-model="exportProgressVisible" :title="exportDialogTitle" width="480px" append-to-body :close-on-click-modal="false">
<el-progress :percentage="exportPercent" :status="exportStatus" :stroke-width="14" striped :striped-flow="exporting" />
<div class="export-progress__msg">{{ exportMessage }}</div>
<div class="export-progress__text">导出行数 {{ exportRowCount }}</div>
<p v-if="exporting" class="export-progress__hint">导出在后台进行,可收起弹窗继续操作;请勿关闭或刷新本页</p>
<template #footer>
<el-button v-if="exporting" @click="exportProgressVisible = false">收起</el-button>
<el-button v-else type="primary" @click="exportProgressVisible = false">关闭</el-button>
</template>
</el-dialog>
<!-- 提成设置与编辑弹窗暂停使用。
<el-dialog v-model="commissionDialogVisible" title="业务员固定提成比例" width="760px" append-to-body>
<div class="commission-toolbar">
@@ -240,24 +261,29 @@
</template>
<script setup name="ProfitReport">
import { downloadProfitExport, exportProfitOrders, listProfitAreaRules, listProfitCustomerOptions, listProfitOrders, listProfitSummary } from '@/api/report/profit'
import { listProfitAreaRules, listProfitCustomerOptions, listProfitOrders, listProfitSummary } from '@/api/report/profit'
// 提成功能暂停使用:import { deleteProfitCommissionRate, listProfitCommissionRates, saveProfitCommissionRate } from '@/api/report/profit'
import { parseTime } from '@/utils/bms'
import { defaultDateRange, maxEndDate } from '@/utils/reportDateRange'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'
import { exportAsync } from '@/utils/excelExport'
// 提成功能暂停使用:import { ElMessageBox } from 'element-plus'
const { customer_area, bms_currency } = useDict('customer_area', 'bms_currency')
const multiValueFilterLimit = 2000
const dateRange = ref([formatLocalDate(-30), formatLocalDate(0)])
const dateRange = ref(defaultDateRange())
const dateRangeError = computed(() => {
if (!hasCompleteDateRange()) return ''
const [start, end] = dateRange.value
return end > maxEndDate(start) ? '计费日期最多查询一个月' : ''
})
const arBillStatus = ref('')
const query = reactive({
customerArea: '',
orderNo: '',
customerCode: '',
belongSalerCode: '',
productCode: '',
productName: '',
productKeyword: '',
countryName: '',
countryCode: '',
currency: ''
@@ -275,9 +301,27 @@ let rowsRequestVersion = 0
const loading = ref(false)
const hasSearched = ref(false)
const exporting = ref(false)
const exportFinished = ref(false)
const exportProgressVisible = ref(false)
const exportPercent = ref(0)
const exportStatus = ref(undefined)
const exportMessage = ref('')
const exportRowCount = ref(0)
let exportHideTimer = null
const exportFloatVisible = computed(() => exporting.value || exportFinished.value)
const exportDegree = computed(() => Math.round(exportPercent.value / 100 * 360))
const exportFloatTitle = computed(() => exporting.value ? '导出中' : (exportStatus.value === 'exception' ? '导出失败' : '导出完成'))
const exportFloatSummary = computed(() => exportRowCount.value > 0
? `${exportPercent.value}% / ${exportRowCount.value} 行`
: `${exportPercent.value}%`)
const exportDialogTitle = computed(() => exporting.value ? '异步导出进行中' : (exportStatus.value === 'exception' ? '异步导出失败' : '异步导出完成'))
onBeforeUnmount(() => {
clearTimeout(exportHideTimer)
})
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 汇总按币种分组,分页总数复用各币种订单数之和。
const total = computed(() => summaryList.value.reduce((count, summary) => count + Number(summary.orderCount || 0), 0))
/* 提成表单状态与初始化暂停使用,保留代码便于恢复。
const commissionDialogVisible = ref(false)
const commissionLoading = ref(false)
@@ -304,15 +348,6 @@ function createRateForm(row = {}) {
}
*/
function formatLocalDate(offset) {
const date = new Date()
date.setDate(date.getDate() + offset)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
function buildQuery(paged = true) {
const params = { ...query }
if (arBillStatus.value) params.arBillStatus = arBillStatus.value
@@ -356,6 +391,10 @@ function validateRequiredFilters(showMessage = true) {
if (showMessage) ElMessage.warning('请选择完整的计费日期')
return false
}
if (dateRangeError.value) {
if (showMessage) ElMessage.warning(dateRangeError.value)
return false
}
return true
}
@@ -377,7 +416,6 @@ function loadRows() {
return listProfitOrders(buildQuery()).then(res => {
if (requestVersion !== rowsRequestVersion) return
rows.value = res.rows || []
total.value = res.total || 0
}).finally(() => {
if (requestVersion === rowsRequestVersion) loading.value = false
})
@@ -390,7 +428,6 @@ function clearReportResults() {
summaryList.value = []
summaryLoaded.value = false
rows.value = []
total.value = 0
loading.value = false
}
@@ -407,7 +444,7 @@ function handleReset() {
Object.keys(query).forEach(key => { query[key] = '' })
query.customerArea = customer_area.value[0]?.value ?? ''
arBillStatus.value = ''
dateRange.value = [formatLocalDate(-30), formatLocalDate(0)]
dateRange.value = defaultDateRange()
hasSearched.value = false
clearReportResults()
}
@@ -442,23 +479,47 @@ function arBillStatusLabel(value) {
}
async function handleExport() {
if (!hasSearched.value || !validateRequiredFilters()) return
if (exporting.value || !hasSearched.value || !validateRequiredFilters()) return
if (!hasProfitRule() || !validateMultiValueFilters()) return
clearTimeout(exportHideTimer)
exporting.value = true
exportFinished.value = false
exportProgressVisible.value = false
exportPercent.value = 0
exportStatus.value = undefined
exportMessage.value = '正在提交导出任务'
exportRowCount.value = 0
try {
const response = await exportProfitOrders(buildQuery(false))
const exportResult = response.data
const file = await downloadProfitExport(exportResult.exportId)
if (file.type?.includes('json')) {
const error = JSON.parse(await file.text())
throw new Error(error.msg || '下载导出文件失败')
const result = await exportAsync({
baseUrl: '/report/profit/orders/export',
query: buildQuery(false),
filePrefix: '订单维度毛利分析',
showLoading: false,
onProgress: task => {
exportPercent.value = Math.max(0, Math.min(100, Number(task.percent) || 0))
exportRowCount.value = Number(task.rowCount) || 0
exportMessage.value = task.error || task.message || '导出中'
if (task.status === 'FAIL' || task.status === 'FAILED') exportStatus.value = 'exception'
}
})
if (result) {
exportPercent.value = 100
exportStatus.value = 'success'
exportMessage.value = '导出完成'
} else {
if (exportStatus.value !== 'exception') exportMessage.value = '导出失败,请查看提示后重试'
exportStatus.value = 'exception'
}
saveAs(file, exportResult.fileName)
ElMessage.success('报表已导出')
} catch (error) {
ElMessage.error(error?.message || '报表导出失败')
exportStatus.value = 'exception'
exportMessage.value = error?.message || '导出失败,请稍后重试'
} finally {
exporting.value = false
exportFinished.value = true
exportHideTimer = window.setTimeout(() => {
exportFinished.value = false
exportHideTimer = null
}, 1000)
}
}
@@ -533,8 +594,7 @@ watch(() => [
query.orderNo,
query.customerCode,
query.belongSalerCode,
query.productCode,
query.productName,
query.productKeyword,
query.countryName,
query.countryCode,
query.currency,
@@ -546,6 +606,18 @@ watch(() => [
</script>
<style scoped lang="scss">
.export-status-float { position: fixed; top: 92px; right: 24px; z-index: 3001; }
.export-status-button { display: inline-flex; align-items: center; gap: 10px; min-width: 200px; min-height: 68px; padding: 6px 16px 6px 7px; border-radius: 36px; }
.export-progress-ring { position: relative; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 54px; width: 54px; height: 54px; border-radius: 50%; background: conic-gradient(var(--el-color-warning) 0deg var(--export-progress, 0deg), var(--el-color-warning-light-8) var(--export-progress, 0deg) 360deg); }
.export-progress-ring::after { position: absolute; inset: 5px; content: ''; border-radius: 50%; background: var(--el-bg-color); }
.export-progress-value { position: relative; z-index: 1; color: var(--el-color-warning); font-size: 12px; font-weight: 600; line-height: 1; }
.export-status-text { display: flex; flex-direction: column; align-items: flex-start; gap: 3px; line-height: 1.2; white-space: nowrap; }
.export-status-text strong { font-size: 14px; font-weight: 600; }
.export-status-text small { color: var(--el-text-color-secondary); font-size: 11px; }
.export-progress__msg { margin-top: 12px; color: var(--el-text-color-regular); }
.export-progress__text { margin-top: 8px; color: var(--el-text-color-secondary); font-size: 13px; }
.export-progress__hint { margin-top: 12px; color: var(--el-color-warning); font-size: 12px; }
.search-card,
.table-card {
margin-bottom: 14px;