新增邮编相关字段及优化附加费计算逻辑

This commit is contained in:
wuweihua
2026-11-18 15:39:52 +08:00
parent b4569e5c15
commit b3ef85b0bb
9 changed files with 381 additions and 50 deletions
@@ -51,6 +51,18 @@ public class PrcSurchargeRel extends BaseEntity
private String roundMode;
private String ssCode;
private String scNote;
/** 命中邮编(来自 prc_surcharge.postcode_text) */
private String postcodeText;
/** 超尺寸长/宽/高(厘米) */
private BigDecimal lengthCm;
private BigDecimal widthCm;
private BigDecimal heightCm;
/** 超重阈值(公斤) */
private BigDecimal overWeightKg;
/** 续重起始重量(公斤) */
private BigDecimal extraWeightKg;
/** 命中分区(block_title) */
private String blockTitle;
/** 明细展示字段(PRODUCT/REDLINE LEFT JOIN product_country) */
private String countryName;
@@ -149,6 +149,55 @@ public final class PaySurchargeRules
return false;
}
/**
* 应收订单附加费邮编命中:去掉全部空白后按连续串计费。
* 如 PA2 8HA → PA28HA,并尝试 PA2/PA28 等外向码前缀,便于命中 PA20-49。
* 仅应收报价使用;应付/打单仍走 matchesPostcode。
*/
public static boolean matchesPostcodeReceivable(String param, String postcode)
{
if (param == null || param.isBlank() || postcode == null || postcode.isBlank())
{
return false;
}
String whole = postcode.toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9]", "");
if (whole.isEmpty())
{
return false;
}
List<UkPostcode> candidates = ukOutwardCandidates(whole);
String digits = whole.replaceAll("\\D", "");
for (String token : param.split(","))
{
String value = token.trim().toUpperCase(Locale.ROOT);
if (value.isEmpty())
{
continue;
}
String compact = value.replaceAll("[^A-Z0-9]", "");
if (!compact.isEmpty() && compact.equals(whole))
{
return true;
}
for (UkPostcode parsed : candidates)
{
if (tokenMatches(value, parsed))
{
return true;
}
}
if (candidates.isEmpty() && value.matches("\\d{1,5}") && !digits.isEmpty())
{
boolean full = value.length() >= 4 ? digits.equals(value) : digits.startsWith(value);
if (full)
{
return true;
}
}
}
return false;
}
/**
* 配置页上的邮编。逗号或换行分隔。短码按前缀,长码按完整邮编,数字区间和英国邮编区间都认。
* 返回命中的最长一段长度,没有命中时为 -1。
@@ -753,6 +802,40 @@ public final class PaySurchargeRules
return AREA.matcher(token).matches() && postcode.area.equals(token);
}
/** 从去空格后的邮编串收集可能的英国外向码(含标准解析与前缀)。 */
private static List<UkPostcode> ukOutwardCandidates(String compact)
{
List<UkPostcode> list = new ArrayList<UkPostcode>();
java.util.LinkedHashSet<String> seen = new java.util.LinkedHashSet<String>();
UkPostcode primary = parseUk(compact);
if (primary != null)
{
String key = primary.area + "#" + primary.district;
if (seen.add(key))
{
list.add(primary);
}
}
int max = Math.min(4, compact.length());
for (int len = 2; len <= max; len++)
{
String prefix = compact.substring(0, len);
Matcher outward = UK_OUTWARD.matcher(prefix);
if (!outward.matches())
{
continue;
}
String area = outward.group(1);
int district = Integer.parseInt(outward.group(2));
String key = area + "#" + district;
if (seen.add(key))
{
list.add(new UkPostcode(area, district));
}
}
return list;
}
private static UkPostcode parseUk(String postcode)
{
if (postcode == null)
@@ -15,6 +15,7 @@ import java.util.TreeSet;
import java.util.zip.CRC32;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -191,7 +192,8 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
{
String taskId = IdUtils.fastSimpleUUID();
saveAsyncRunner.put(taskId, PrcPriceSetSaveTask.STATUS_PENDING, 0, "queued", null, null);
saveAsyncRunner.runSurchargeBatch(taskId, details);
// 传入当前登录态,供异步线程写 createBy / 变更日志
saveAsyncRunner.runSurchargeBatch(taskId, details, SecurityContextHolder.getContext().getAuthentication());
return taskId;
}
@@ -43,6 +43,7 @@ import com.bms.price.domain.PrcQuote;
import com.bms.price.domain.PrcQuoteFee;
import com.bms.price.domain.PrcSurchargeRel;
import com.bms.price.domain.PrcZone;
import com.bms.price.pay.PaySurchargeRules;
import com.bms.price.pay.PayZoneMatcher;
import com.bms.price.mapper.PrcZoneDetailMapper;
import com.bms.price.domain.vo.TmsPriceBillRequest;
@@ -1262,6 +1263,23 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
{
result.setDestPostcode(emptyToNull(request.getDestPostcode()));
}
// 计费请求带上长宽高,供 SIZE 附加费判定
if (request instanceof TmsPriceBillRequest)
{
TmsPriceBillRequest billReq = (TmsPriceBillRequest) request;
if (result.getPkgLength() == null)
{
result.setPkgLength(billReq.getPkgLength());
}
if (result.getPkgWidth() == null)
{
result.setPkgWidth(billReq.getPkgWidth());
}
if (result.getPkgHeight() == null)
{
result.setPkgHeight(billReq.getPkgHeight());
}
}
// 始终优先使用根据 customerCode 解析出的客户(忽略 TMS/绑定 ID)
if (request.getCustomerId() != null)
{
@@ -1958,7 +1976,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
*/
private boolean surchargeApplies(PrcSurchargeRel rel, TmsPriceQuoteResult result, boolean salesRel)
{
if (rel == null)
if (rel == null || result == null)
{
return false;
}
@@ -1971,34 +1989,158 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
{
return false;
}
if (salesRel)
if (!salesRel)
{
if (rel.getDetailId() != null)
{
if (PrcSurchargeRel.PRICE_TYPE_REDLINE.equals(rel.getPriceType()))
{
if (result.getRedlineCountryId() == null || !rel.getDetailId().equals(result.getRedlineCountryId()))
{
return false;
}
}
else if (result.getProductCountryId() == null || !rel.getDetailId().equals(result.getProductCountryId()))
{
return false;
}
}
}
return surchargeConditionHit(rel, result);
}
/** 按附加费 chargeType 判定是否命中(邮编/分区/超重/超尺寸等) */
private boolean surchargeConditionHit(PrcSurchargeRel rel, TmsPriceQuoteResult result)
{
String chargeType = rel.getChargeType() == null ? "MANUAL" : rel.getChargeType().trim().toUpperCase(Locale.ROOT);
if ("MANUAL".equals(chargeType))
{
return false;
}
if ("ALWAYS".equals(chargeType) || "FIXED".equals(chargeType))
{
return true;
}
if (rel.getDetailId() == null)
if ("POSTCODE".equals(chargeType))
{
return PaySurchargeRules.matchesPostcodeReceivable(rel.getPostcodeText(), result.getDestPostcode());
}
if ("ZONE".equals(chargeType))
{
return zoneTitleHit(rel.getBlockTitle(), result.getZoneName(), result.getZoneCode());
}
if ("WEIGHT".equals(chargeType))
{
return rel.getOverWeightKg() != null && result.getWeight() != null
&& result.getWeight().compareTo(rel.getOverWeightKg()) > 0;
}
if ("SIZE".equals(chargeType))
{
return sizeHit(rel, result.getPkgLength(), result.getPkgWidth(), result.getPkgHeight());
}
if ("EXTRA_KG".equals(chargeType))
{
// 若配了邮编则先命中邮编;再判断超过续重起始
if (StringUtils.isNotEmpty(rel.getPostcodeText())
&& !PaySurchargeRules.matchesPostcodeReceivable(rel.getPostcodeText(), result.getDestPostcode()))
{
return false;
}
return rel.getExtraWeightKg() != null && result.getWeight() != null
&& result.getWeight().compareTo(rel.getExtraWeightKg()) > 0;
}
if ("RETURN".equals(chargeType))
{
return "REFUNDED".equalsIgnoreCase(String.valueOf(result.getRefundStatus()));
}
// 未知类型:不自动计费,避免误收
return false;
}
private static boolean zoneTitleHit(String blockTitle, String zoneName, String zoneCode)
{
if (StringUtils.isEmpty(blockTitle))
{
return false;
}
String want = blockTitle.trim();
if (StringUtils.isNotEmpty(zoneName) && want.equalsIgnoreCase(zoneName.trim()))
{
return true;
}
if (PrcSurchargeRel.PRICE_TYPE_REDLINE.equals(rel.getPriceType()))
if (StringUtils.isNotEmpty(zoneCode) && want.equalsIgnoreCase(zoneCode.trim()))
{
return result.getRedlineCountryId() != null && rel.getDetailId().equals(result.getRedlineCountryId());
return true;
}
return result.getProductCountryId() != null && rel.getDetailId().equals(result.getProductCountryId());
return false;
}
/** 超尺寸:订单任一边超过对应配置阈值即命中(未配的边忽略) */
private static boolean sizeHit(PrcSurchargeRel rel, BigDecimal length, BigDecimal width, BigDecimal height)
{
if (rel == null)
{
return false;
}
boolean hit = false;
boolean anyRule = false;
if (rel.getLengthCm() != null)
{
anyRule = true;
if (length != null && length.compareTo(rel.getLengthCm()) > 0)
{
hit = true;
}
}
if (rel.getWidthCm() != null)
{
anyRule = true;
if (width != null && width.compareTo(rel.getWidthCm()) > 0)
{
hit = true;
}
}
if (rel.getHeightCm() != null)
{
anyRule = true;
if (height != null && height.compareTo(rel.getHeightCm()) > 0)
{
hit = true;
}
}
return anyRule && hit;
}
private BigDecimal calcSurchargeAmount(PrcSurchargeRel rel, BigDecimal weight, BigDecimal freightAmount)
{
if (rel.getChargeValue() == null)
if (rel == null || rel.getChargeValue() == null)
{
return BigDecimal.ZERO;
}
RoundingMode rm = resolveRoundingMode(rel.getRoundMode());
String chargeType = rel.getChargeType() == null ? "MANUAL" : rel.getChargeType().toUpperCase();
// MANUAL=暂不计费;其他计费方式暂按固定金额 charge_value
String chargeType = rel.getChargeType() == null ? "MANUAL" : rel.getChargeType().trim().toUpperCase(Locale.ROOT);
if ("MANUAL".equals(chargeType))
{
return BigDecimal.ZERO.setScale(2, rm);
}
if ("EXTRA_KG".equals(chargeType))
{
if (weight == null || rel.getExtraWeightKg() == null)
{
return BigDecimal.ZERO.setScale(2, rm);
}
BigDecimal over = weight.subtract(rel.getExtraWeightKg());
if (over.compareTo(BigDecimal.ZERO) <= 0)
{
return BigDecimal.ZERO.setScale(2, rm);
}
return rel.getChargeValue().multiply(over).setScale(2, rm);
}
if ("RATE".equals(chargeType))
{
// 比例类:按运费乘以 charge_value(例如 0.15 = 15%)
return nvl(freightAmount).multiply(rel.getChargeValue()).setScale(2, rm);
}
return rel.getChargeValue().setScale(2, rm);
}
@@ -6,6 +6,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.bms.common.core.redis.RedisCache;
import com.bms.common.utils.StringUtils;
@@ -53,12 +56,19 @@ public class PrcPriceSetSaveAsyncRunner
}
}
/** 后台批量写入明细附加费快照。 */
/** 后台批量写入明细附加费快照(带入登录态,避免异步线程 SecurityUtils 取不到用户)。 */
@Async("threadPoolTaskExecutor")
public void runSurchargeBatch(String taskId, List<PrcPriceSetDetail> details)
public void runSurchargeBatch(String taskId, List<PrcPriceSetDetail> details, Authentication authentication)
{
SecurityContext previous = SecurityContextHolder.getContext();
try
{
if (authentication != null)
{
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
}
put(taskId, PrcPriceSetSaveTask.STATUS_RUNNING, 10, "saving surcharges", null, null);
int rows = priceSetService.batchUpdateDetailSurcharges(details);
put(taskId, PrcPriceSetSaveTask.STATUS_SUCCESS, 100, "done", null, null);
@@ -74,6 +84,10 @@ public class PrcPriceSetSaveAsyncRunner
}
put(taskId, PrcPriceSetSaveTask.STATUS_FAIL, 100, "failed", null, msg);
}
finally
{
SecurityContextHolder.setContext(previous);
}
}
@@ -21,6 +21,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="roundMode" column="round_mode" />
<result property="ssCode" column="ss_code" />
<result property="scNote" column="sc_note" />
<result property="postcodeText" column="postcode_text" />
<result property="lengthCm" column="length_cm" />
<result property="widthCm" column="width_cm" />
<result property="heightCm" column="height_cm" />
<result property="overWeightKg" column="over_weight_kg" />
<result property="extraWeightKg" column="extra_weight_kg" />
<result property="blockTitle" column="block_title" />
<result property="countryName" column="country_name" />
<result property="weightMin" column="weight_min" />
<result property="weightMax" column="weight_max" />
@@ -36,6 +43,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
r.created_by, r.create_time, r.updated_by, r.update_time,
s.sc_name, s.fee_type, s.charge_type, s.charge_value, s.currency,
s.round_mode, s.ss_code, s.sc_note,
s.postcode_text, s.length_cm, s.width_cm, s.height_cm,
s.over_weight_kg, s.extra_weight_kg, s.block_title,
ifnull(c.country_name, rc.country_name) as country_name, ifnull(c.weight_min, rc.weight_min) as weight_min, ifnull(c.weight_max, rc.weight_max) as weight_max
from prc_surcharge_rel r
join prc_surcharge s on s.sc_id = r.sc_id and ifnull(s.is_del, '0') = '0'