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
@@ -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>