This commit is contained in:
wuweihua
2026-11-17 10:26:24 +08:00
6 changed files with 248 additions and 8 deletions
@@ -10,6 +10,11 @@ oss:
# 项目相关配置 # 项目相关配置
bms: bms:
# 毛利报表区域客户 ID 过滤:默认关闭,完成生产计划和耗时对比后再启用。
profit-report:
customer-id-filter-enabled: ${BMS_PROFIT_REPORT_CUSTOMER_ID_FILTER_ENABLED:false}
# 超过此客户数时自动回退客户表关联;小于等于 0 时停用,上限为 5000。
max-customer-ids: ${BMS_PROFIT_REPORT_MAX_CUSTOMER_IDS:1000}
# 名称 # 名称
name: BMS name: BMS
# 版本 # 版本
@@ -0,0 +1,136 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.*;
import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.bms.price.domain.PrcProfitReportExport;
import com.bms.price.domain.vo.PrcProfitReportOrderRow;
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.mapper.PrcProfitReportMapper;
import com.bms.price.service.impl.PrcProfitReportServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
class ProfitReportAreaFilterTest
{
@AfterEach
void clearPage()
{
PageHelper.clearPage();
}
@Test
void customerLookupPreservesPaginationAndUsesOnlyServerResolvedIds()
{
AtomicReference<List<Long>> ids = new AtomicReference<>(List.of(2L, 3L));
AtomicReference<PrcProfitReportQuery> seen = new AtomicReference<>();
Page<?> page = PageHelper.startPage(2, 10);
PrcProfitReportMapper mapper = mapper(ids, seen, page);
PrcProfitReportServiceImpl service = service(mapper, true, 2);
PrcProfitReportQuery query = new PrcProfitReportQuery();
query.setCustomerArea(" C ");
query.setAreaCustomerIds(List.of(999L));
service.selectOrderRows(query);
assertSame(query, seen.get());
assertEquals(List.of(2L, 3L), query.getAreaCustomerIds());
assertSame(page, PageHelper.getLocalPage());
ids.set(List.of());
service.selectSummary(query);
assertEquals(List.of(), query.getAreaCustomerIds());
ids.set(List.of(1L, 2L, 3L));
service.selectProductRows(query);
assertNull(query.getAreaCustomerIds());
}
@Test
void customerLookupFailureClearsPageContext()
{
PrcProfitReportMapper mapper = (PrcProfitReportMapper) Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[] { PrcProfitReportMapper.class },
(proxy, method, args) -> { throw new IllegalStateException("lookup failed"); });
PrcProfitReportServiceImpl service = service(mapper, true, 2);
PrcProfitReportQuery query = new PrcProfitReportQuery();
query.setCustomerArea("C");
PageHelper.startPage(1, 10);
assertThrows(IllegalStateException.class, () -> service.selectOrderRows(query));
assertNull(PageHelper.getLocalPage());
}
@Test
void sqlUsesAreaJoinOrCustomerIdsAndEmptyIdsMatchNothing() throws Exception
{
Configuration config = new Configuration();
for (Class<?> type : new Class<?>[] { PrcProfitReportExport.class, PrcProfitReportOrderRow.class,
PrcProfitReportProductRow.class, PrcProfitReportSummary.class })
{
config.getTypeAliasRegistry().registerAlias(type);
}
String resource = "mapper/price/PrcProfitReportMapper.xml";
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource))
{
assertNotNull(input);
new XMLMapperBuilder(input, config, resource, config.getSqlFragments()).parse();
}
PrcProfitReportQuery query = new PrcProfitReportQuery();
query.setCustomerArea("C");
for (String id : List.of("selectOrderRows", "selectProductRows", "selectSummary"))
{
var statement = config.getMappedStatement("com.bms.price.mapper.PrcProfitReportMapper." + id);
query.setAreaCustomerIds(null);
String joinSql = statement.getBoundSql(query).getSql();
assertTrue(joinSql.contains("join ctr_customer c"));
assertTrue(joinSql.contains("c.customer_area = ?"));
assertTrue(joinSql.contains("c.del_flag = '0'"));
query.setAreaCustomerIds(List.of(2L, 3L));
String inSql = statement.getBoundSql(query).getSql();
assertFalse(inSql.contains("join ctr_customer c"));
assertTrue(inSql.contains("p.customer_id in"));
query.setAreaCustomerIds(List.of());
String emptySql = statement.getBoundSql(query).getSql();
assertFalse(emptySql.contains("join ctr_customer c"));
assertTrue(emptySql.contains("and 1 = 0"));
}
}
private PrcProfitReportServiceImpl service(PrcProfitReportMapper mapper, boolean enabled, int max)
{
PrcProfitReportServiceImpl service = new PrcProfitReportServiceImpl();
ReflectionTestUtils.setField(service, "profitReportMapper", mapper);
ReflectionTestUtils.setField(service, "customerIdFilterEnabled", enabled);
ReflectionTestUtils.setField(service, "maxCustomerIds", max);
return service;
}
private PrcProfitReportMapper mapper(AtomicReference<List<Long>> ids,
AtomicReference<PrcProfitReportQuery> seen, Page<?> page)
{
return (PrcProfitReportMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] { PrcProfitReportMapper.class }, (proxy, method, args) -> {
if (method.getName().equals("selectAreaCustomerIds"))
{
assertNull(PageHelper.getLocalPage());
assertEquals("C", args[0]);
assertEquals(3, args[1]);
return ids.get();
}
assertSame(page, PageHelper.getLocalPage());
seen.set((PrcProfitReportQuery) args[0]);
return List.of();
});
}
}
@@ -26,6 +26,8 @@ public class PrcProfitReportQuery extends BaseEntity
private List<String> customerCodes; private List<String> customerCodes;
/** 按客户当前区域筛选。 */ /** 按客户当前区域筛选。 */
private String customerArea; private String customerArea;
/** 服务端解析的区域客户 ID;null 表示使用客户表关联,空列表表示无匹配客户。 */
private List<Long> areaCustomerIds;
/** 服务端根据客户区域确定的计算规则。 */ /** 服务端根据客户区域确定的计算规则。 */
private String profitRule; private String profitRule;
private String customerName; private String customerName;
@@ -11,6 +11,8 @@ import com.bms.price.domain.vo.PrcProfitReportSummary;
/** 毛利报表 mapper;金额事实取自 prc_income_bill。 */ /** 毛利报表 mapper;金额事实取自 prc_income_bill。 */
public interface PrcProfitReportMapper public interface PrcProfitReportMapper
{ {
List<Long> selectAreaCustomerIds(@Param("customerArea") String customerArea, @Param("limit") int limit);
List<PrcProfitReportOrderRow> selectOrderRows(PrcProfitReportQuery query); List<PrcProfitReportOrderRow> selectOrderRows(PrcProfitReportQuery query);
List<PrcProfitReportProductRow> selectProductRows(PrcProfitReportQuery query); List<PrcProfitReportProductRow> selectProductRows(PrcProfitReportQuery query);
@@ -6,6 +6,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
// 提成功能暂停使用:import java.math.BigDecimal; // 提成功能暂停使用:import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
// 提成功能暂停使用:import org.springframework.transaction.annotation.Transactional; // 提成功能暂停使用:import org.springframework.transaction.annotation.Transactional;
import com.bms.common.exception.ServiceException; import com.bms.common.exception.ServiceException;
@@ -23,16 +24,27 @@ import com.bms.price.domain.vo.PrcProfitReportSummary;
import com.bms.price.enums.ProfitAreaRule; import com.bms.price.enums.ProfitAreaRule;
import com.bms.price.mapper.PrcProfitReportMapper; import com.bms.price.mapper.PrcProfitReportMapper;
import com.bms.price.service.IPrcProfitReportService; import com.bms.price.service.IPrcProfitReportService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** 毛利报表:以 prc_income_bill 为金额事实表,不关联应付模块。 */ /** 毛利报表:以 prc_income_bill 为金额事实表,不关联应付模块。 */
@Service @Service
public class PrcProfitReportServiceImpl implements IPrcProfitReportService public class PrcProfitReportServiceImpl implements IPrcProfitReportService
{ {
private static final int MULTI_VALUE_FILTER_LIMIT = 2000; private static final int MULTI_VALUE_FILTER_LIMIT = 2000;
private static final int MAX_AREA_CUSTOMER_IDS = 5000;
private static final Logger log = LoggerFactory.getLogger(PrcProfitReportServiceImpl.class);
@Autowired @Autowired
private PrcProfitReportMapper profitReportMapper; private PrcProfitReportMapper profitReportMapper;
@Value("${bms.profit-report.customer-id-filter-enabled:false}")
private boolean customerIdFilterEnabled;
@Value("${bms.profit-report.max-customer-ids:1000}")
private int maxCustomerIds;
@Autowired @Autowired
private BmsCustomerMapper customerMapper; private BmsCustomerMapper customerMapper;
@@ -59,8 +71,35 @@ public class PrcProfitReportServiceImpl implements IPrcProfitReportService
@Override @Override
public List<PrcProfitReportOrderRow> selectOrderRows(PrcProfitReportQuery query) public List<PrcProfitReportOrderRow> selectOrderRows(PrcProfitReportQuery query)
{ {
log.info("selectOrderRows 开始, query={}", query);
long methodStart = System.currentTimeMillis();
try {
// ---- normalizeMultiValueFilters 单独计时 ----
long normalizeStart = System.currentTimeMillis();
normalizeMultiValueFilters(query); normalizeMultiValueFilters(query);
return profitReportMapper.selectOrderRows(query); long normalizeCost = System.currentTimeMillis() - normalizeStart;
log.debug("normalizeMultiValueFilters 完成, 耗时={}ms, query={}", normalizeCost, query);
// ---- 数据库查询单独计时 ----
long dbStart = System.currentTimeMillis();
List<PrcProfitReportOrderRow> prcProfitReportOrderRows = profitReportMapper.selectOrderRows(query);
long dbCost = System.currentTimeMillis() - dbStart;
long totalCost = System.currentTimeMillis() - methodStart;
int size = prcProfitReportOrderRows == null ? 0 : prcProfitReportOrderRows.size();
log.info("selectOrderRows 结束, 结果条数={}, normalize耗时={}ms, db耗时={}ms, 总耗时={}ms",
size, normalizeCost, dbCost, totalCost);
if (log.isDebugEnabled() && prcProfitReportOrderRows != null && !prcProfitReportOrderRows.isEmpty()) {
log.debug("selectOrderRows 首条数据={}", prcProfitReportOrderRows.get(0));
}
return prcProfitReportOrderRows;
} catch (Exception e) {
long totalCost = System.currentTimeMillis() - methodStart;
log.error("selectOrderRows 异常, 总耗时={}ms, query={}", totalCost, query, e);
throw e;
}
} }
@Override @Override
@@ -115,6 +154,8 @@ public class PrcProfitReportServiceImpl implements IPrcProfitReportService
{ {
throw new ServiceException("请选择客户区域"); throw new ServiceException("请选择客户区域");
} }
// 区域客户 ID 只能由服务端生成,不能信任请求中传入的值。
query.setAreaCustomerIds(null);
if ("COMMISSION_MISSING".equals(query.getDetailType())) if ("COMMISSION_MISSING".equals(query.getDetailType()))
{ {
throw new ServiceException("提成功能已暂停使用"); throw new ServiceException("提成功能已暂停使用");
@@ -133,6 +174,43 @@ public class PrcProfitReportServiceImpl implements IPrcProfitReportService
query.setOrderNos(splitFilterValues(query.getOrderNo(), "订单号")); query.setOrderNos(splitFilterValues(query.getOrderNo(), "订单号"));
query.setCustomerCodes(splitFilterValues(query.getCustomerCode(), "客户代码")); query.setCustomerCodes(splitFilterValues(query.getCustomerCode(), "客户代码"));
query.setCustomerNames(splitFilterValues(query.getCustomerName(), "客户名称")); query.setCustomerNames(splitFilterValues(query.getCustomerName(), "客户名称"));
resolveAreaCustomerIds(query);
}
private void resolveAreaCustomerIds(PrcProfitReportQuery query)
{
if (!customerIdFilterEnabled || maxCustomerIds <= 0)
{
return;
}
// startPage 已由 Controller 设置;客户查询不能消耗订单列表的分页。
Page<?> page = PageHelper.getLocalPage();
PageHelper.clearPage();
boolean resolved = false;
try
{
int threshold = Math.min(maxCustomerIds, MAX_AREA_CUSTOMER_IDS);
int limit = threshold + 1;
List<Long> customerIds = profitReportMapper.selectAreaCustomerIds(query.getCustomerArea(), limit);
if (customerIds == null)
{
throw new ServiceException("查询区域客户失败");
}
if (customerIds.size() <= threshold)
{
query.setAreaCustomerIds(customerIds);
}
// 超过阈值保留 null,回退原客户表关联,避免生成过长的 IN 列表。
resolved = true;
}
finally
{
if (resolved && page != null)
{
PageHelper.setLocalPage(page);
}
}
} }
private List<String> splitFilterValues(String rawValue, String fieldName) private List<String> splitFilterValues(String rawValue, String fieldName)
@@ -116,10 +116,17 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
--> -->
</resultMap> </resultMap>
<select id="selectAreaCustomerIds" resultType="long">
select customer_id
from ctr_customer
where customer_area = #{customerArea} and del_flag = '0'
limit #{limit}
</select>
<sql id="profitReportFromAndWhere"> <sql id="profitReportFromAndWhere">
from prc_income_bill i from prc_income_bill i
inner join prc_order_bill p on p.bill_id = i.bill_id inner join prc_order_bill p on p.bill_id = i.bill_id
<if test="customerArea != null and customerArea != ''"> <if test="areaCustomerIds == null and customerArea != null and customerArea != ''">
left join ctr_customer c on c.customer_id = p.customer_id and c.del_flag = '0' left join ctr_customer c on c.customer_id = p.customer_id and c.del_flag = '0'
</if> </if>
<!-- 提成表关联暂停使用,毛利报表不再依赖提成配置。 <!-- 提成表关联暂停使用,毛利报表不再依赖提成配置。
@@ -129,9 +136,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<where> <where>
<!-- 不将未匹配产品、国家或重量段的计费失败订单纳入毛利报表;保留历史空值(按成功处理)。 --> <!-- 不将未匹配产品、国家或重量段的计费失败订单纳入毛利报表;保留历史空值(按成功处理)。 -->
and (p.billing_fail_status is null or p.billing_fail_status not in (1, 2, 3)) and (p.billing_fail_status is null or p.billing_fail_status not in (1, 2, 3))
<if test="customerArea != null and customerArea != ''"> <choose>
<when test="areaCustomerIds != null and areaCustomerIds.size() > 0">
and p.customer_id in
<foreach collection="areaCustomerIds" item="customerId" open="(" separator="," close=")">
#{customerId}
</foreach>
</when>
<when test="areaCustomerIds != null">
and 1 = 0
</when>
<when test="customerArea != null and customerArea != ''">
and c.customer_area = #{customerArea} and c.customer_area = #{customerArea}
</if> </when>
</choose>
<if test="beginBizDate != null"> <if test="beginBizDate != null">
and p.biz_date &gt;= #{beginBizDate} and p.biz_date &gt;= #{beginBizDate}
</if> </if>
@@ -251,7 +269,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="arBillStatus != null and arBillStatus != '' and productDrilldown != true"> <if test="arBillStatus != null and arBillStatus != '' and productDrilldown != true">
and p.ar_bill_status = #{arBillStatus} and p.ar_bill_status = #{arBillStatus}
</if> </if>
order by p.biz_date desc, p.bill_id desc
</select> </select>
<!-- 汇总和产品维度使用同一套逐单有效数据计算,毛利率按有效销售额加权。 --> <!-- 汇总和产品维度使用同一套逐单有效数据计算,毛利率按有效销售额加权。 -->