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

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
@@ -170,7 +170,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
/**
* 规范化目的地邮编,用于分区匹配/持久化。
* 移除所有 Unicode 空白字符(包括 NBSP / U+2005)和 ASCII 空格;
* 仅去掉两端 Unicode 空白(含 NBSP / U+2005),保留中间空格;
* 去除纯数字末尾 Excel 风格的 ".0"。
*/
public static String normalizePostcode(String postcode)
@@ -179,17 +179,27 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
{
return postcode;
}
StringBuilder sb = new StringBuilder(postcode.length());
for (int i = 0; i < postcode.length(); )
int startIdx = 0;
int endIdx = postcode.length();
while (startIdx < endIdx)
{
int cp = postcode.codePointAt(i);
int cp = postcode.codePointAt(startIdx);
if (!Character.isWhitespace(cp))
{
sb.appendCodePoint(cp);
break;
}
i += Character.charCount(cp);
startIdx += Character.charCount(cp);
}
String n = sb.toString();
while (endIdx > startIdx)
{
int cp = postcode.codePointBefore(endIdx);
if (!Character.isWhitespace(cp))
{
break;
}
endIdx -= Character.charCount(cp);
}
String n = postcode.substring(startIdx, endIdx);
if (n.endsWith(".0") && n.matches("\\d+\\.0"))
{
return n.substring(0, n.length() - 2);
@@ -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'
@@ -100,14 +100,11 @@
<template #default="{ row }"><b>{{ row.productCode }}</b></template>
</el-table-column>
<el-table-column :label="colName" prop="productName" min-width="80" show-overflow-tooltip />
<el-table-column :label="colLevel" prop="serviceLevel" width="90" align="center" />
<el-table-column :label="colCargo" width="200" align="center">
<el-table-column :label="colSc" min-width="200">
<template #default="{ row }">
<el-tag v-if="row.cargoAttr" type="primary" size="small" effect="plain">{{ row.cargoAttr }}</el-tag>
<span v-else>-</span>
<surcharge-tags :list="productSurcharges(row)" :empty-text="noneSc" />
</template>
</el-table-column>
<el-table-column :label="colRegion" prop="destRegion" width="90" align="center" />
<el-table-column :label="colAction" width="220" align="center" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click="openPrice(row)">编辑价格</el-button>
@@ -211,6 +208,7 @@
import ExcelImportDialog from '@/components/ExcelImportDialog'
import PriceEditDrawer from './PriceEditDrawer.vue'
import SurchargePickerDialog from './SurchargePickerDialog.vue'
import SurchargeTags from '../SurchargeTags.vue'
import { useDetailCascade } from '../../composables/usePriceSetRefData'
import {
createEmptyDetailRow,
@@ -271,10 +269,8 @@ const phKeyword = '产品代码/名称'
const phTax = '全部税模式'
const colCode = '产品代码'
const colName = '产品名称'
const colLevel = '时效等级'
const colCargo = '走货属性'
const colRegion = '目的区域'
// const colTax = '税模式'
const colSc = '附加费'
const noneSc = '无'
const colAction = '操作'
const colDiscount = '产品折扣'
@@ -505,14 +501,24 @@ const productGroups = computed(() => {
return (props.products || []).filter(p => p && p.productCode).map(p => ({
productCode: p.productCode,
productName: p.productName || p.productCode,
serviceLevel: p.serviceLevel,
cargoAttr: p.cargoAttr,
destRegion: p.destRegion,
taxMode: p.taxMode,
rows: detailByProduct[p.productCode] || []
}))
})
/** 产品级附加费:合并该产品下所有明细行的 scId(去重) */
function productSurcharges(product) {
const map = new Map()
for (const r of product?.rows || []) {
for (const s of r?.surcharges || []) {
if (!s || s.scId == null) continue
const key = String(s.scId)
if (!map.has(key)) map.set(key, s)
}
}
return [...map.values()]
}
const filteredProducts = computed(() => {
const kw = (query.keyword || '').trim().toLowerCase()
return productGroups.value.filter(p => {
@@ -632,6 +638,46 @@ watch(
{ immediate: true }
)
/** 编辑页:按版本一次拉齐明细,供产品表展示附加费 */
async function preloadVersionDetails() {
if (!props.livePersist) {
const byCode = {}
for (const d of props.details || []) {
if (!d?.productCode) continue
if (!byCode[d.productCode]) byCode[d.productCode] = []
byCode[d.productCode].push(d)
}
Object.keys(detailByProduct).forEach(k => delete detailByProduct[k])
Object.assign(detailByProduct, byCode)
return
}
const psvId = props.psvId || resolvedPsvId.value
if (!psvId) return
try {
const res = await api.listSetDetailByVersion(psvId)
const byCode = {}
for (const raw of res.data || []) {
if (!raw?.productCode) continue
const d = hydrateRow(raw, props.setType)
if (!byCode[d.productCode]) byCode[d.productCode] = []
byCode[d.productCode].push(d)
}
Object.keys(detailByProduct).forEach(k => delete detailByProduct[k])
Object.assign(detailByProduct, byCode)
if (Array.isArray(props.details)) {
props.details.splice(0, props.details.length, ...Object.values(byCode).flat())
}
} catch (e) {
/* 预加载失败不阻断编辑;点附加费时仍会按产品拉取 */
}
}
watch(
() => [props.livePersist, props.psvId, props.products?.length],
() => { preloadVersionDetails() },
{ immediate: true }
)
async function openImport() {
if (!(await canOpenImport())) return
importRef.value && importRef.value.open()
@@ -21,14 +21,11 @@
<template #default="{ row }"><b>{{ row.productCode }}</b></template>
</el-table-column>
<el-table-column :label="colName" prop="productName" min-width="140" show-overflow-tooltip />
<el-table-column :label="colLevel" prop="serviceLevel" width="90" align="center" />
<el-table-column :label="colCargo" min-width="140" align="center" show-overflow-tooltip>
<el-table-column :label="colSc" min-width="200">
<template #default="{ row }">
<el-tag v-if="row.cargoAttr" type="primary" size="small" effect="plain">{{ row.cargoAttr }}</el-tag>
<span v-else>-</span>
<surcharge-tags :list="row.surcharges || []" :empty-text="noneSc" />
</template>
</el-table-column>
<el-table-column :label="colRegion" prop="destRegion" width="100" align="center" />
<el-table-column :label="colAction" width="110" align="center" fixed="right">
<template #default="{ row }">
<el-button link type="primary" @click.stop="openProductDetail(row)">查看明细</el-button>
@@ -159,9 +156,6 @@ const emptyProduct = '暂无产品'
const emptyDetail = '暂无明细'
const colCode = '产品代码'
const colName = '产品名称'
const colLevel = '时效等级'
const colCargo = '走货属性'
const colRegion = '目的区域'
const colAction = '操作'
const colCountry = '国家'
const colZone = '分区'
@@ -300,13 +294,30 @@ function normalizeProducts(list) {
.map(p => ({
productCode: p.productCode || p.code,
productName: p.productName || p.name || p.productCode || p.code,
serviceLevel: p.serviceLevel,
cargoAttr: p.cargoAttr,
destRegion: p.destRegion,
taxMode: p.taxMode
taxMode: p.taxMode,
surcharges: []
}))
}
/** 按产品汇总版本明细上的附加费(scId 去重) */
function attachProductSurcharges(productList, detailRows) {
const byCode = new Map()
for (const d of detailRows || []) {
if (!d?.productCode) continue
if (!byCode.has(d.productCode)) byCode.set(d.productCode, new Map())
const map = byCode.get(d.productCode)
for (const s of d.surcharges || []) {
if (!s || s.scId == null) continue
const key = String(s.scId)
if (!map.has(key)) map.set(key, s)
}
}
return (productList || []).map(p => ({
...p,
surcharges: [...(byCode.get(p.productCode)?.values() || [])]
}))
}
async function loadProducts() {
const v = props.version || {}
const psvId = v.psvId
@@ -316,14 +327,16 @@ async function loadProducts() {
}
loading.value = true
try {
const fromVersion = normalizeProducts(v.products)
if (fromVersion.length) {
products.value = fromVersion
return
let list = normalizeProducts(v.products)
if (!list.length) {
const res = await api.listSetDetailOptions(psvId)
const data = res.data || {}
list = normalizeProducts(data.products || [])
}
const res = await api.listSetDetailOptions(psvId)
const data = res.data || {}
products.value = normalizeProducts(data.products || [])
const detailRes = await api.listSetDetailByVersion(psvId)
products.value = attachProductSurcharges(list, detailRes.data || [])
} catch (e) {
products.value = normalizeProducts(v.products)
} finally {
loading.value = false
}