优化邮编分区管理,新增匹配类型字段及相关逻辑

This commit is contained in:
wuweihua
2026-11-20 12:43:23 +08:00
parent a0b9b58291
commit 2e05616f85
20 changed files with 971 additions and 77 deletions
@@ -105,8 +105,8 @@ public class LblProduct extends BaseEntity
private List<LblExtraLine> extraLines;
/** 邮编→分区(保存时按产品同步到 prc_zone LABEL,不落产品子表) */
private Map<String, List<String>> zonePostcodes;
/** 邮编→分区(保存时按产品同步到 prc_zone LABEL;元素含 postcode+matchType) */
private Map<String, List<PrcZoneDetail>> zonePostcodes;
/** 编辑保存删除标记(不落库) */
private Boolean deleted;
@@ -2,6 +2,7 @@ package com.bms.price.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@@ -11,11 +12,41 @@ public class PrcZoneDetail implements Serializable
{
private static final long serialVersionUID = 1L;
/** 全匹配邮编 */
public static final String MATCH_FULL = "FULL";
/** 匹配邮编开头 */
public static final String MATCH_PREFIX = "PREFIX";
private Long detailId;
private Long zoneId;
private String postcode;
/** FULL / PREFIX,默认 FULL */
private String matchType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public static String normalizeMatchType(String raw)
{
if (raw == null || raw.isBlank())
{
return MATCH_FULL;
}
String value = raw.trim().toUpperCase(Locale.ROOT);
if (MATCH_PREFIX.equals(value) || "START".equals(value) || "STARTS".equals(value))
{
return MATCH_PREFIX;
}
return MATCH_FULL;
}
public static PrcZoneDetail of(String postcode, String matchType)
{
PrcZoneDetail detail = new PrcZoneDetail();
detail.setPostcode(postcode);
detail.setMatchType(normalizeMatchType(matchType));
return detail;
}
}
@@ -35,6 +35,13 @@ public final class LblCostCalculator
public static PayOrderCostResult calculate(LblProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus)
{
return calculate(product, weight, length, width, height, postcode, zoneName, bizDate, orderStatus, null, null);
}
public static PayOrderCostResult calculate(LblProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus,
String countryCode, String countryName)
{
PayOrderCostResult result = new PayOrderCostResult();
result.setFees(new ArrayList<PayCostLine>());
@@ -52,7 +59,14 @@ public final class LblCostCalculator
return result;
}
List<LblWeightBand> all = product.getWeightBands() == null ? List.of() : product.getWeightBands();
List<LblWeightBand> raw = product.getWeightBands() == null ? List.of() : product.getWeightBands();
List<LblWeightBand> all = filterByCountry(raw, countryCode, countryName);
if (all.isEmpty() && !raw.isEmpty() && hasCountryCode(countryCode, countryName))
{
result.setMessage("产品「" + nz(product.getProductName()) + "」没有命中国家 "
+ nz(countryCode) + (nz(countryName).isEmpty() ? "" : "/" + nz(countryName)) + " 的价卡");
return result;
}
Set<String> zones = zoneNames(all);
if (zones.size() > 1 && (zoneName == null || zoneName.isBlank()))
{
@@ -102,9 +116,21 @@ public final class LblCostCalculator
}
if (!hasFreightLine)
{
result.setMessage(outOfRange(product, all, weight, zoneName));
result.getFees().clear();
return result;
// 价卡仅有处理费/偏远、无派送费段时(如 NL-DHL),允许按已算费用出账;附加费基数用处理费
if (!hasFreightTypeBands(all) && result.getFees() != null && !result.getFees().isEmpty())
{
freight = sumFeeAmounts(result, "REGISTRATION_FEE");
if (freight.compareTo(BigDecimal.ZERO) == 0)
{
freight = sumAllFeeAmounts(result);
}
}
else
{
result.setMessage(outOfRange(product, all, weight, zoneName));
result.getFees().clear();
return result;
}
}
}
@@ -287,11 +313,14 @@ public final class LblCostCalculator
return base;
}
BigDecimal over = weight.subtract(first);
if (over.compareTo(BigDecimal.ZERO) < 0)
if (over.compareTo(BigDecimal.ZERO) <= 0)
{
over = BigDecimal.ZERO;
return base;
}
return base.add(extra.multiply(over));
// 首重+续重:超出部分按「每增加 X Kg」向上取整档数(不按公斤比例)
BigDecimal step = extraStepKg(band, first);
BigDecimal steps = over.divide(step, 0, RoundingMode.CEILING);
return base.add(extra.multiply(steps));
}
if (band.getPrice() == null)
{
@@ -305,6 +334,23 @@ public final class LblCostCalculator
return band.getPrice();
}
/**
* 续重步长:优先解析重量段「每增加 X」;否则用首重;再否则 1kg。
*/
private static BigDecimal extraStepKg(LblWeightBand band, BigDecimal firstKg)
{
BigDecimal fromLabel = LblTexts.extraStepKg(band == null ? null : band.getWeightLabel());
if (fromLabel != null && fromLabel.compareTo(BigDecimal.ZERO) > 0)
{
return fromLabel;
}
if (firstKg != null && firstKg.compareTo(BigDecimal.ZERO) > 0)
{
return firstKg;
}
return BigDecimal.ONE;
}
private static BigDecimal firstKg(LblWeightBand band)
{
if (band.getCalcParam() != null && !band.getCalcParam().isBlank())
@@ -379,6 +425,132 @@ public final class LblCostCalculator
return "基础运费";
}
/** 按订单国家收窄重量段;有国别代码时不允许误用其他国。 */
private static List<LblWeightBand> filterByCountry(List<LblWeightBand> bands, String countryCode, String countryName)
{
if (bands == null || bands.isEmpty() || !hasCountryCode(countryCode, countryName))
{
return bands == null ? List.of() : bands;
}
List<LblWeightBand> matched = new ArrayList<LblWeightBand>();
List<LblWeightBand> blank = new ArrayList<LblWeightBand>();
for (LblWeightBand band : bands)
{
if (band == null)
{
continue;
}
if (bandCountryBlank(band))
{
blank.add(band);
continue;
}
if (bandMatchesCountry(band, countryCode, countryName))
{
matched.add(band);
}
}
return matched.isEmpty() ? blank : matched;
}
private static boolean hasCountryCode(String countryCode, String countryName)
{
return (countryCode != null && !countryCode.isBlank()) || (countryName != null && !countryName.isBlank());
}
private static boolean bandCountryBlank(LblWeightBand band)
{
return nz(band.getCountryCode()).isEmpty() && nz(band.getCountryName()).isEmpty();
}
private static boolean bandMatchesCountry(LblWeightBand band, String countryCode, String countryName)
{
String orderCc = nz(countryCode).toUpperCase(Locale.ROOT);
String bandCc = nz(band.getCountryCode()).toUpperCase(Locale.ROOT);
if (!orderCc.isEmpty() && !bandCc.isEmpty())
{
for (String part : bandCc.split("[,;/\\s]+"))
{
if (part != null && orderCc.equals(part.trim()))
{
return true;
}
}
String bandNameU = nz(band.getCountryName()).toUpperCase(Locale.ROOT).replace(" ", "");
if (bandNameU.contains("(" + orderCc + ")") || bandNameU.endsWith(orderCc))
{
return true;
}
}
String orderName = nz(countryName);
String bandName = nz(band.getCountryName());
if (!orderName.isEmpty() && !bandName.isEmpty())
{
String bare = bandName.replaceAll("\\([^)]*\\)", "").trim();
if (bandName.contains(orderName) || (!bare.isEmpty() && orderName.contains(bare)))
{
return true;
}
}
return false;
}
/** 当前国家收窄后是否存在派送费(FREIGHT)段;空 fee_type 视为 FREIGHT */
private static boolean hasFreightTypeBands(List<LblWeightBand> bands)
{
if (bands == null || bands.isEmpty())
{
return false;
}
for (LblWeightBand band : bands)
{
if (band == null)
{
continue;
}
String ft = nz(band.getFeeType());
if (ft.isEmpty() || LblFeeType.FREIGHT.equals(ft))
{
return true;
}
}
return false;
}
private static BigDecimal sumFeeAmounts(PayOrderCostResult result, String feeType)
{
BigDecimal sum = BigDecimal.ZERO;
if (result == null || result.getFees() == null || feeType == null)
{
return sum;
}
for (PayCostLine fee : result.getFees())
{
if (fee != null && feeType.equals(fee.getFeeType()) && fee.getAmount() != null)
{
sum = sum.add(fee.getAmount());
}
}
return sum;
}
private static BigDecimal sumAllFeeAmounts(PayOrderCostResult result)
{
BigDecimal sum = BigDecimal.ZERO;
if (result == null || result.getFees() == null)
{
return sum;
}
for (PayCostLine fee : result.getFees())
{
if (fee != null && fee.getAmount() != null)
{
sum = sum.add(fee.getAmount());
}
}
return sum;
}
private static Set<String> zoneNames(List<LblWeightBand> bands)
{
Set<String> zones = new LinkedHashSet<String>();
@@ -94,6 +94,23 @@ public final class LblTexts
return bounds;
}
/**
* 从「每增加 X Kg」取续重步长;解不出返 null。
*/
public static BigDecimal extraStepKg(String label)
{
if (label == null || label.isBlank())
{
return null;
}
Matcher step = STEP_WEIGHT.matcher(label);
if (step.find())
{
return decimal(step.group(1));
}
return null;
}
public static boolean looksLikeWeight(String text)
{
if (text == null)
@@ -1611,8 +1611,9 @@ public class LblWorkbookParser
}
else if (remoteHandle)
{
band.setFeeType(com.bms.price.domain.LblFeeType.REMOTE);
band.setChargeName(chargeTitle(parent[col]));
// CTT 等:「偏远附加费」实为派送费(FREIGHT),按邮编前缀命中,不落 REMOTE
band.setFeeType(com.bms.price.domain.LblFeeType.FREIGHT);
band.setChargeName("派送费");
band.setZoneName(zoneName);
applyRemotePostcode(band, rawZone);
band.setPrice(price);
@@ -4378,7 +4379,8 @@ public class LblWorkbookParser
}
/**
* 价表中与派送费并排的偏远列:落重量段 fee_type=REMOTE,不进附加费表。
* 价表中「偏远附加费」列/表头:CTT 等按派送费 FREIGHT+邮编前缀落库;
* Evri 等非首重/续重并排列仍可落 REMOTE。
*/
private static boolean isRemoteHandleHead(String head)
{
@@ -14,10 +14,12 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.bms.price.domain.LblProduct;
import com.bms.price.domain.LblWeightBand;
import com.bms.price.domain.PrcZoneDetail;
/**
* 打单价卡「邮编分区」表抽取为 zone→postcodes,保存时同步到分区管理 prc_zone。
* 支持 Corres/双列、Colissimo Densite、CTT Density、PosteItaliane 三列、iMile IT/DE。
* 支持 Corres/双列、Colissimo Densite、CTT Density、PosteItaliane 三列、iMile IT/DE;
* 以及「英国附加费」中 EVRI 偏远邮编前缀(挂到 Evri 产品)。
*/
public final class LblZonePostcodeAttach
{
@@ -43,6 +45,11 @@ public final class LblZonePostcodeAttach
continue;
}
String sheetName = sheet.getSheetName() == null ? "" : sheet.getSheetName().trim();
if (isUkSurchargeSheet(sheetName))
{
attachUkEvri(sheet, sheetName, products);
continue;
}
if (!isZonePostcodeSheet(sheetName))
{
continue;
@@ -52,17 +59,32 @@ public final class LblZonePostcodeAttach
attachImile(sheet, sheetName, products);
continue;
}
Map<String, List<String>> zoneMap = parseSheet(sheet);
if (zoneMap.isEmpty())
{
continue;
}
LblProduct target = matchProduct(products, sheetName);
if (target == null)
{
continue;
}
mergeZonePostcodes(target, zoneMap);
Map<String, List<String>> poste = parsePosteItaliane(sheet);
if (!poste.isEmpty())
{
Map<String, List<String>> city = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> rural = new LinkedHashMap<String, List<String>>();
if (poste.get("City") != null) city.put("City", poste.get("City"));
if (poste.get("Province") != null) city.put("Province", poste.get("Province"));
if (poste.get("Rural") != null) rural.put("Rural", poste.get("Rural"));
mergeZonePostcodes(target, city, PrcZoneDetail.MATCH_PREFIX);
mergeZonePostcodes(target, rural, PrcZoneDetail.MATCH_FULL);
linkSheet(target, sheetName);
continue;
}
Map<String, List<String>> zoneMap = parseSheet(sheet);
if (zoneMap.isEmpty())
{
continue;
}
// 表名含「邮编开头」或单元格带 * 时按前缀;否则全匹配
String matchType = sheetName.contains("邮编开头") ? PrcZoneDetail.MATCH_PREFIX : PrcZoneDetail.MATCH_FULL;
mergeZonePostcodes(target, zoneMap, matchType);
linkSheet(target, sheetName);
}
}
@@ -95,9 +117,18 @@ public final class LblZonePostcodeAttach
{
return m.group(1);
}
// IT-iMile / DE-iMile:从表名/产品名推导
String blob = compact(nz(product.getSheetName()) + nz(product.getProductName()) + nz(product.getDictValue()));
if (blob.contains("itimile") || blob.startsWith("itimile") || blob.contains("italyimile"))
{
return "IT";
}
if (blob.contains("deimile") || blob.contains("germanyimile"))
{
return "DE";
}
return "";
}
private static boolean isZonePostcodeSheet(String sheetName)
{
if (sheetName == null || sheetName.isBlank())
@@ -107,6 +138,257 @@ public final class LblZonePostcodeAttach
return sheetName.contains("邮编") && sheetName.contains("分区");
}
/** 英国附加费:Royal Mail / EVRI 偏远邮编前缀表。 */
private static boolean isUkSurchargeSheet(String sheetName)
{
if (sheetName == null || sheetName.isBlank())
{
return false;
}
return sheetName.contains("英国") && sheetName.contains("附加费");
}
/**
* 从「英国附加费」右侧 EVRI 列抽取偏远邮编,映射为 Evri 价表分区名后挂到 Evri 产品。
*/
private static void attachUkEvri(Sheet sheet, String sheetName, List<LblProduct> products)
{
Map<String, List<String>> zoneMap = parseUkEvriZonePostcodes(sheet);
if (zoneMap.isEmpty())
{
return;
}
LblProduct target = matchEvriProduct(products);
if (target == null)
{
return;
}
mergeZonePostcodes(target, zoneMap, PrcZoneDetail.MATCH_PREFIX);
linkSheet(target, sheetName);
}
private static Map<String, List<String>> parseUkEvriZonePostcodes(Sheet sheet)
{
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS);
int headerRow = -1;
int enCol = 4;
int zhCol = 5;
int postcodeCol = 6;
for (int r = 0; r <= Math.min(lastRow, 8); r++)
{
Row row = sheet.getRow(r);
if (row == null)
{
continue;
}
boolean hasEvriTitle = false;
boolean hasPcHead = false;
for (int c = 0; c < row.getLastCellNum(); c++)
{
String val = cellText(row.getCell(c));
String up = val.toUpperCase(Locale.ROOT);
if (up.contains("EVRI"))
{
hasEvriTitle = true;
}
if (val.contains("邮编开头") && c >= 3)
{
hasPcHead = true;
}
}
if (hasEvriTitle && !hasPcHead)
{
Row next = sheet.getRow(r + 1);
if (next != null)
{
int foundEn = -1;
int foundZh = -1;
int foundPc = -1;
for (int c = 0; c < next.getLastCellNum(); c++)
{
String val = cellText(next.getCell(c));
if (c < 3)
{
continue;
}
if (val.contains("偏远地区") && val.contains("英文") && foundEn < 0)
{
foundEn = c;
}
else if (val.contains("偏远地区") && val.contains("中文") && foundZh < 0)
{
foundZh = c;
}
else if (val.contains("邮编开头") && foundPc < 0)
{
foundPc = c;
}
}
if (foundPc >= 0)
{
headerRow = r + 1;
if (foundEn >= 0)
{
enCol = foundEn;
}
if (foundZh >= 0)
{
zhCol = foundZh;
}
postcodeCol = foundPc;
break;
}
}
}
if (hasPcHead)
{
int foundEn = -1;
int foundZh = -1;
int foundPc = -1;
for (int c = 0; c < row.getLastCellNum(); c++)
{
String val = cellText(row.getCell(c));
if (c < 3)
{
continue;
}
if (val.contains("偏远地区") && val.contains("英文") && foundEn < 0)
{
foundEn = c;
}
else if (val.contains("偏远地区") && val.contains("中文") && foundZh < 0)
{
foundZh = c;
}
else if (val.contains("邮编开头") && foundPc < 0)
{
foundPc = c;
}
}
if (foundPc >= 0)
{
headerRow = r;
if (foundEn >= 0)
{
enCol = foundEn;
}
if (foundZh >= 0)
{
zhCol = foundZh;
}
postcodeCol = foundPc;
break;
}
}
}
if (headerRow < 0)
{
headerRow = 1;
enCol = 4;
zhCol = 5;
postcodeCol = 6;
}
String lastEn = "";
String lastZh = "";
for (int r = headerRow + 1; r <= lastRow; r++)
{
Row row = sheet.getRow(r);
if (row == null)
{
continue;
}
String en = normalizeZone(cellText(row.getCell(enCol)));
String zh = normalizeZone(cellText(row.getCell(zhCol)));
if (!en.isEmpty())
{
lastEn = en;
}
if (!zh.isEmpty())
{
lastZh = zh;
}
String postcode = stripTrailingStar(normalizePostcode(cellText(row.getCell(postcodeCol)), 0));
if (postcode.isEmpty() || (lastEn.isEmpty() && lastZh.isEmpty()))
{
continue;
}
String zone = mapEvriZoneName(lastEn, lastZh);
if (zone.isEmpty())
{
continue;
}
List<String> list = map.computeIfAbsent(zone, k -> new ArrayList<String>());
if (!list.contains(postcode))
{
list.add(postcode);
}
}
return map;
}
/** 映射为与 Evri 48H 价表分区列可对上的名称。 */
private static String mapEvriZoneName(String en, String zh)
{
String blob = ((en == null ? "" : en) + " " + (zh == null ? "" : zh)).toLowerCase(Locale.ROOT);
if (blob.contains("bfpo"))
{
return "BFPO";
}
if (blob.contains("isle of man") || blob.contains("马恩"))
{
return "Isle of Man";
}
if (blob.contains("northern ireland") || blob.contains("北爱尔兰"))
{
return "Northern Ireland";
}
if (blob.contains("channel") || blob.contains("scilly") || blob.contains("海峡") || blob.contains("锡利"))
{
return "Channel Islands / Isle of Scilly";
}
if (blob.contains("scottish") || blob.contains("shetland") || blob.contains("highland") || blob.contains("h&i")
|| blob.contains("高地"))
{
return "Highlands & Islands";
}
String fallback = normalizeZone(en);
if (!fallback.isEmpty())
{
return fallback;
}
return normalizeZone(zh);
}
private static LblProduct matchEvriProduct(List<LblProduct> products)
{
LblProduct hit = null;
int count = 0;
for (LblProduct product : products)
{
String blob = compact(nz(product.getProductName()) + nz(product.getSheetName()) + nz(product.getDictValue()));
if (blob.contains("evri"))
{
hit = product;
count++;
}
}
if (count == 1)
{
return hit;
}
return null;
}
private static String stripTrailingStar(String text)
{
if (text == null || text.isEmpty())
{
return "";
}
return text.replaceAll("\\*+\\s*$", "").trim();
}
private static Map<String, List<String>> parseSheet(Sheet sheet)
{
Map<String, List<String>> poste = parsePosteItaliane(sheet);
@@ -209,6 +491,16 @@ public final class LblZonePostcodeAttach
}
}
private static String detectMatchType(String raw, String fallback)
{
String text = raw == null ? "" : raw.trim();
if (text.endsWith("*") || text.contains("邮编开头"))
{
return PrcZoneDetail.MATCH_PREFIX;
}
return PrcZoneDetail.normalizeMatchType(fallback);
}
private static Map<String, List<String>> parseCtt(Sheet sheet)
{
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
@@ -433,7 +725,8 @@ public final class LblZonePostcodeAttach
LblProduct germany = productOf(products, "DE-iMile");
int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS);
int header = -1;
for (int r = 0; r <= Math.min(lastRow, 6); r++)
// 不能只认「邮编」:标题行「IT-iMile邮编分区」也含该字,须同时有列名(城市/分区/ZIP)
for (int r = 0; r <= Math.min(lastRow, 8); r++)
{
Row row = sheet.getRow(r);
if (row == null)
@@ -443,11 +736,20 @@ public final class LblZonePostcodeAttach
StringBuilder line = new StringBuilder();
for (int c = 0; c < row.getLastCellNum(); c++)
{
line.append(cellText(row.getCell(c)));
line.append(cellText(row.getCell(c))).append(' ');
}
String text = line.toString();
if (text.contains("邮编") || text.toLowerCase(Locale.ROOT).contains("zip"))
String low = text.toLowerCase(Locale.ROOT);
boolean hasItHead = text.contains("邮编") && (text.contains("分区") || text.contains("城市"));
boolean hasDeHead = low.contains("zip");
if (hasItHead || hasDeHead)
{
// 排除纯标题:仅有「xxx邮编分区」无列名
if (text.contains("邮编分区") && !text.contains("城市") && !low.contains("zip")
&& !text.contains("邮编(") && !text.contains("邮编("))
{
continue;
}
header = r;
break;
}
@@ -520,12 +822,12 @@ public final class LblZonePostcodeAttach
}
if (italy != null && !itMap.isEmpty())
{
mergeZonePostcodes(italy, itMap);
mergeZonePostcodes(italy, itMap, PrcZoneDetail.MATCH_FULL);
linkSheet(italy, sheetName);
}
if (germany != null && !deMap.isEmpty())
{
mergeZonePostcodes(germany, deMap);
mergeZonePostcodes(germany, deMap, PrcZoneDetail.MATCH_FULL);
linkSheet(germany, sheetName);
}
}
@@ -550,6 +852,10 @@ public final class LblZonePostcodeAttach
private static LblProduct productOf(List<LblProduct> products, String name)
{
if (products == null || name == null || name.isBlank())
{
return null;
}
for (LblProduct product : products)
{
if (name.equals(product.getSheetName()) || name.equals(product.getProductName())
@@ -558,6 +864,16 @@ public final class LblZonePostcodeAttach
return product;
}
}
// IT-iMile / DE-iMile:允许 sheet/dict 含同名 token
String key = compact(name);
for (LblProduct product : products)
{
String blob = compact(nz(product.getProductName()) + nz(product.getSheetName()) + nz(product.getDictValue()));
if (!key.isEmpty() && blob.contains(key))
{
return product;
}
}
return null;
}
@@ -615,22 +931,49 @@ public final class LblZonePostcodeAttach
return null;
}
private static void mergeZonePostcodes(LblProduct product, Map<String, List<String>> incoming)
private static void mergeZonePostcodes(LblProduct product, Map<String, List<String>> incoming, String matchType)
{
Map<String, List<String>> current = product.getZonePostcodes();
if (product == null || incoming == null || incoming.isEmpty())
{
return;
}
Map<String, List<PrcZoneDetail>> current = product.getZonePostcodes();
if (current == null)
{
current = new LinkedHashMap<String, List<String>>();
current = new LinkedHashMap<String, List<PrcZoneDetail>>();
product.setZonePostcodes(current);
}
String type = PrcZoneDetail.normalizeMatchType(matchType);
for (Map.Entry<String, List<String>> e : incoming.entrySet())
{
List<String> list = current.computeIfAbsent(e.getKey(), k -> new ArrayList<String>());
List<PrcZoneDetail> list = current.computeIfAbsent(e.getKey(), k -> new ArrayList<PrcZoneDetail>());
for (String pc : e.getValue())
{
if (!list.contains(pc))
if (pc == null || pc.isBlank())
{
list.add(pc);
continue;
}
String postcode = pc.trim();
String rowType = detectMatchType(postcode, type);
// 落库前去掉尾部 *
postcode = stripTrailingStar(postcode);
if (postcode.isEmpty())
{
continue;
}
boolean exists = false;
for (PrcZoneDetail item : list)
{
if (item != null && postcode.equalsIgnoreCase(item.getPostcode()))
{
item.setMatchType(rowType);
exists = true;
break;
}
}
if (!exists)
{
list.add(PrcZoneDetail.of(postcode, rowType));
}
}
}
@@ -55,5 +55,5 @@ public interface IPrcZoneService
/**
* 按打单产品同步 LABEL 邮编分区:仅覆盖本次出现的 zone,不碰其他产品/常规分区。
*/
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<String>> zonePostcodes);
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<PrcZoneDetail>> zonePostcodes);
}
@@ -2075,9 +2075,17 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
applyProductCodeMapping(bill, request);
}
// 已有真实销售产品名时不覆盖;仅缺失或与编码相同时才用报价结果补全
if (result != null && StringUtils.isNotEmpty(result.getProductName()))
{
bill.setProductName(result.getProductName());
String existing = StringUtils.trim(bill.getProductName());
String code = StringUtils.trim(bill.getProductCode());
boolean missingOrCodeOnly = StringUtils.isEmpty(existing)
|| (StringUtils.isNotEmpty(code) && existing.equalsIgnoreCase(code));
if (missingOrCodeOnly)
{
bill.setProductName(result.getProductName());
}
}
if (StringUtils.isEmpty(bill.getCountryCode()) && result != null)
{
@@ -219,12 +219,20 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override
public int insertPrcZoneDetail(PrcZoneDetail detail)
{
if (detail != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.insertPrcZoneDetail(detail);
}
@Override
public int updatePrcZoneDetail(PrcZoneDetail detail)
{
if (detail != null && detail.getMatchType() != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.updatePrcZoneDetail(detail);
}
@@ -281,7 +289,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
unmatched.add(item.countryHint + "(" + item.sheetName + ")");
continue;
}
int[] counts = replaceRegionZones(region, zonePostcodes);
int[] counts = replaceRegionZones(region, zonePostcodes, item.matchType);
countryCount += 1;
zoneCount += counts[0];
detailCount += counts[1];
@@ -398,6 +406,10 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode.trim());
if (detail.getMatchType() == null || detail.getMatchType().isBlank())
{
detail.setMatchType(PrcZoneDetail.MATCH_FULL);
}
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -418,7 +430,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override
@Transactional(rollbackFor = Exception.class)
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<String>> zonePostcodes)
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<PrcZoneDetail>> zonePostcodes)
{
if (productId == null)
{
@@ -456,9 +468,9 @@ public class PrcZoneServiceImpl implements IPrcZoneService
}
int zoneUpsert = 0;
int detailInserted = 0;
List<Map.Entry<String, List<String>>> entries = new ArrayList<>(zonePostcodes.entrySet());
List<Map.Entry<String, List<PrcZoneDetail>>> entries = new ArrayList<>(zonePostcodes.entrySet());
entries.sort(Comparator.comparingInt(e -> extractZoneSort(e.getKey())));
for (Map.Entry<String, List<String>> entry : entries)
for (Map.Entry<String, List<PrcZoneDetail>> entry : entries)
{
String label = StringUtils.trim(entry.getKey());
if (StringUtils.isEmpty(label))
@@ -501,21 +513,26 @@ public class PrcZoneServiceImpl implements IPrcZoneService
detailMapper.deletePrcZoneDetailByZoneId(zone.getZoneId());
}
zoneUpsert++;
Set<String> uniquePostcodes = new LinkedHashSet<String>();
Map<String, PrcZoneDetail> unique = new LinkedHashMap<String, PrcZoneDetail>();
if (entry.getValue() != null)
{
uniquePostcodes.addAll(entry.getValue());
for (PrcZoneDetail item : entry.getValue())
{
if (item == null || StringUtils.isEmpty(item.getPostcode()))
{
continue;
}
String pc = item.getPostcode().trim();
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(pc);
detail.setMatchType(PrcZoneDetail.normalizeMatchType(item.getMatchType()));
unique.put(pc.toUpperCase(Locale.ROOT), detail);
}
}
List<PrcZoneDetail> batch = new ArrayList<>(BATCH_SIZE);
for (String postcode : uniquePostcodes)
for (PrcZoneDetail detail : unique.values())
{
if (StringUtils.isEmpty(postcode))
{
continue;
}
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode.trim());
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -534,11 +551,17 @@ public class PrcZoneServiceImpl implements IPrcZoneService
}
private int[] replaceRegionZones(BmsRegion region, Map<String, List<String>> zonePostcodes)
{
return replaceRegionZones(region, zonePostcodes, PrcZoneDetail.MATCH_FULL);
}
private int[] replaceRegionZones(BmsRegion region, Map<String, List<String>> zonePostcodes, String matchType)
{
if (StringUtils.isEmpty(region.getCountryCode2()))
{
throw new ServiceException(MessageUtils.message("price.zone.countryCode.empty"));
}
matchType = PrcZoneDetail.normalizeMatchType(matchType);
Long regionId = region.getRegionId();
detailMapper.deletePrcZoneDetailByRegionId(regionId);
zoneMapper.deletePrcZoneByRegionId(regionId);
@@ -570,6 +593,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode);
detail.setMatchType(matchType);
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -592,12 +616,19 @@ public class PrcZoneServiceImpl implements IPrcZoneService
private final String sheetName;
private final String countryHint;
private final Map<String, List<String>> zonePostcodes;
private final String matchType;
private SheetImport(String sheetName, String countryHint, Map<String, List<String>> zonePostcodes)
{
this(sheetName, countryHint, zonePostcodes, PrcZoneDetail.MATCH_FULL);
}
private SheetImport(String sheetName, String countryHint, Map<String, List<String>> zonePostcodes, String matchType)
{
this.sheetName = sheetName;
this.countryHint = countryHint;
this.zonePostcodes = zonePostcodes;
this.matchType = PrcZoneDetail.normalizeMatchType(matchType);
}
}
@@ -646,7 +677,11 @@ public class PrcZoneServiceImpl implements IPrcZoneService
{
countryHint = sheetName;
}
list.add(new SheetImport(sheetName, countryHint, parsed));
// 英国/偏远/邮编开头类表才落 PREFIX;其余默认 FULL
String matchType = (sheetName.contains("英国") || sheetName.contains("邮编开头")
|| sheetName.contains("偏远") || sheetName.contains("加拿大"))
? PrcZoneDetail.MATCH_PREFIX : PrcZoneDetail.MATCH_FULL;
list.add(new SheetImport(sheetName, countryHint, parsed, matchType));
}
return list;
}
@@ -73,6 +73,7 @@ import com.bms.price.search.IBillSearchStore;
import com.bms.price.service.ILblProductService;
import com.bms.price.service.IPayProductService;
import com.bms.price.label.LblCostCalculator;
import com.bms.price.label.LblSurchargeRules;
import com.bms.price.label.LblProductPayAdapter;
import com.bms.price.domain.LblFeeType;
import com.bms.price.domain.LblProduct;
@@ -739,7 +740,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
throw ex;
}
PayOrderCostResult cost = LblCostCalculator.calculate(lblProduct, weight, length, width, height,
request.getDestPostcode(), freightZone, bizDate, orderStatus);
request.getDestPostcode(), freightZone, bizDate, orderStatus, countryCode, countryName);
if (cost == null || cost.getFees() == null || cost.getFees().isEmpty())
{
if (request instanceof TmsPriceBillRequest)
@@ -779,6 +780,12 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return countryFreight.get(0);
}
List<String> candidates = countryFreight.isEmpty() ? zoneNames : countryFreight;
// 优先:派送费重量段上的邮编前缀(如 CTT 加那利 35/38)
String byParam = labelFreightZoneByPostcodeParam(product, cc, destPostcode, candidates);
if (byParam != null)
{
return byParam;
}
if (product == null || product.getProductId() == null)
{
throw new ServiceException("邮编未匹配到产品分区");
@@ -787,6 +794,13 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
product.getProductId(), normalizePostcode(destPostcode));
if (resolved == null)
{
// 未命中偏远前缀时,若价卡有大陆列则走大陆(Evri UK Mainland)
PayZoneMatcher.Decision mainland = PayZoneMatcher.resolve(candidates, java.util.Collections.emptyList(),
destPostcode);
if (mainland != null && mainland.getZoneName() != null)
{
return mainland.getZoneName();
}
throw new ServiceException("邮编未匹配到产品分区");
}
String mapped = PayZoneMatcher.mapRegion(candidates, resolved.getZoneCode());
@@ -803,6 +817,69 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return mapped;
}
/**
* 按派送费重量段 postcodeParam(如 35,38)命中分区名。
*/
private static String labelFreightZoneByPostcodeParam(LblProduct product, String countryCode, String postcode,
List<String> candidates)
{
if (product == null || product.getWeightBands() == null || StringUtils.isEmpty(postcode))
{
return null;
}
String best = null;
int bestScore = -1;
for (LblWeightBand band : product.getWeightBands())
{
if (band == null)
{
continue;
}
String ft = band.getFeeType();
if (ft != null && !ft.isEmpty() && !LblFeeType.FREIGHT.equals(ft))
{
continue;
}
if (StringUtils.isNotEmpty(countryCode) && !bandCountryMatches(band.getCountryCode(), countryCode))
{
continue;
}
String param = band.getPostcodeParam();
if (StringUtils.isEmpty(param))
{
continue;
}
if (!LblSurchargeRules.matchesPostcode(param, postcode) && !PaySurchargeRules.matchesPostcode(param, postcode))
{
continue;
}
String zone = band.getZoneName();
if (zone == null || zone.isBlank())
{
continue;
}
zone = zone.trim();
if (candidates != null && !candidates.isEmpty())
{
for (String c : candidates)
{
if (zone.equals(c) || PayZoneMatcher.sameZone(c, zone))
{
zone = c;
break;
}
}
}
int score = param.replace(",", "").length();
if (score > bestScore)
{
bestScore = score;
best = zone;
}
}
return best;
}
private static List<String> labelBandZoneNames(LblProduct product)
{
LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -825,7 +902,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return new ArrayList<String>(names);
}
/** 该国家下运费(FREIGHT)分区列名;偏远行不算入。 */
/** 该国家下运费(FREIGHT)分区列名(含带邮编前缀的岛屿派送费)。 */
private static List<String> labelFreightZonesForCountry(LblProduct product, String countryCode)
{
LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -980,8 +1057,8 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
{
incomeTotal = freightAmount.add(registrationFee).add(surchargeAmount).setScale(2, rm);
}
String labelProductName = StringUtils.isNotEmpty(product.getProductName())
? product.getProductName() : productName;
// 保留订单/上游销售产品名,不用打单价卡产品名覆盖(含义不同)
String keepProductName = StringUtils.isNotEmpty(productName) ? productName : product.getProductName();
TmsPriceQuoteResult r = new TmsPriceQuoteResult();
r.setMatchSource(SRC_LABEL);
r.setMatchMessage("hit label package pay card V"
@@ -990,7 +1067,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
r.setVersionNo(product.getVersionNo() == null ? null : ("V" + product.getVersionNo()));
r.setCustomerId(bind.getCustomerId());
r.setProductCode(productCode);
r.setProductName(labelProductName);
r.setProductName(keepProductName);
r.setCountryCode(countryCode);
r.setCountryName(countryName);
r.setWeight(weight);
@@ -8,12 +8,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<id property="detailId" column="detail_id" />
<result property="zoneId" column="zone_id" />
<result property="postcode" column="postcode" />
<result property="matchType" column="match_type" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectPrcZoneDetailVo">
select detail_id, zone_id, postcode, create_time, update_time
select detail_id, zone_id, postcode, match_type, create_time, update_time
from prc_zone_detail
</sql>
@@ -51,18 +52,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
insert into prc_zone_detail (
<if test="zoneId != null">zone_id,</if>
<if test="postcode != null and postcode != ''">postcode,</if>
match_type,
create_time
) values (
<if test="zoneId != null">#{zoneId},</if>
<if test="postcode != null and postcode != ''">#{postcode},</if>
#{matchType},
sysdate()
)
</insert>
<insert id="insertPrcZoneDetailBatch">
insert into prc_zone_detail (zone_id, postcode, create_time) values
insert into prc_zone_detail (zone_id, postcode, match_type, create_time) values
<foreach collection="list" item="item" separator=",">
(#{item.zoneId}, #{item.postcode}, sysdate())
(#{item.zoneId}, #{item.postcode}, #{item.matchType}, sysdate())
</foreach>
</insert>
@@ -71,6 +74,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<set>
<if test="zoneId != null">zone_id = #{zoneId},</if>
<if test="postcode != null and postcode != ''">postcode = #{postcode},</if>
<if test="matchType != null and matchType != ''">match_type = #{matchType},</if>
update_time = sysdate()
</set>
where detail_id = #{detailId}
@@ -120,8 +124,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and z.product_id is null
and upper(ifnull(z.country_code,'')) = upper(#{countryCode})
and (
replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
or replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
(
upper(ifnull(d.match_type, 'FULL')) = 'FULL'
and replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
)
or
(
upper(ifnull(d.match_type, 'FULL')) = 'PREFIX'
and replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
)
)
order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end,
@@ -147,8 +158,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where z.zone_type = 'LABEL'
and z.product_id = #{productId}
and (
replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
or replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
(
upper(ifnull(d.match_type, 'FULL')) = 'FULL'
and replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
)
or
(
upper(ifnull(d.match_type, 'FULL')) = 'PREFIX'
and replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
)
)
order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end,