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

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; private List<LblExtraLine> extraLines;
/** 邮编→分区(保存时按产品同步到 prc_zone LABEL,不落产品子表) */ /** 邮编→分区(保存时按产品同步到 prc_zone LABEL;元素含 postcode+matchType) */
private Map<String, List<String>> zonePostcodes; private Map<String, List<PrcZoneDetail>> zonePostcodes;
/** 编辑保存删除标记(不落库) */ /** 编辑保存删除标记(不落库) */
private Boolean deleted; private Boolean deleted;
@@ -2,6 +2,7 @@ package com.bms.price.domain;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.Locale;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data; import lombok.Data;
@@ -11,11 +12,41 @@ public class PrcZoneDetail implements Serializable
{ {
private static final long serialVersionUID = 1L; 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 detailId;
private Long zoneId; private Long zoneId;
private String postcode; private String postcode;
/** FULL / PREFIX,默认 FULL */
private String matchType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime; private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime; 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, public static PayOrderCostResult calculate(LblProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus) 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(); PayOrderCostResult result = new PayOrderCostResult();
result.setFees(new ArrayList<PayCostLine>()); result.setFees(new ArrayList<PayCostLine>());
@@ -52,7 +59,14 @@ public final class LblCostCalculator
return result; 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); Set<String> zones = zoneNames(all);
if (zones.size() > 1 && (zoneName == null || zoneName.isBlank())) if (zones.size() > 1 && (zoneName == null || zoneName.isBlank()))
{ {
@@ -102,9 +116,21 @@ public final class LblCostCalculator
} }
if (!hasFreightLine) if (!hasFreightLine)
{ {
result.setMessage(outOfRange(product, all, weight, zoneName)); // 价卡仅有处理费/偏远、无派送费段时(如 NL-DHL),允许按已算费用出账;附加费基数用处理费
result.getFees().clear(); if (!hasFreightTypeBands(all) && result.getFees() != null && !result.getFees().isEmpty())
return result; {
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; return base;
} }
BigDecimal over = weight.subtract(first); 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) if (band.getPrice() == null)
{ {
@@ -305,6 +334,23 @@ public final class LblCostCalculator
return band.getPrice(); 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) private static BigDecimal firstKg(LblWeightBand band)
{ {
if (band.getCalcParam() != null && !band.getCalcParam().isBlank()) if (band.getCalcParam() != null && !band.getCalcParam().isBlank())
@@ -379,6 +425,132 @@ public final class LblCostCalculator
return "基础运费"; 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) private static Set<String> zoneNames(List<LblWeightBand> bands)
{ {
Set<String> zones = new LinkedHashSet<String>(); Set<String> zones = new LinkedHashSet<String>();
@@ -94,6 +94,23 @@ public final class LblTexts
return bounds; 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) public static boolean looksLikeWeight(String text)
{ {
if (text == null) if (text == null)
@@ -1611,8 +1611,9 @@ public class LblWorkbookParser
} }
else if (remoteHandle) else if (remoteHandle)
{ {
band.setFeeType(com.bms.price.domain.LblFeeType.REMOTE); // CTT 等:「偏远附加费」实为派送费(FREIGHT),按邮编前缀命中,不落 REMOTE
band.setChargeName(chargeTitle(parent[col])); band.setFeeType(com.bms.price.domain.LblFeeType.FREIGHT);
band.setChargeName("派送费");
band.setZoneName(zoneName); band.setZoneName(zoneName);
applyRemotePostcode(band, rawZone); applyRemotePostcode(band, rawZone);
band.setPrice(price); band.setPrice(price);
@@ -4378,7 +4379,8 @@ public class LblWorkbookParser
} }
/** /**
* 价表中与派送费并排的偏远列:落重量段 fee_type=REMOTE,不进附加费表。 * 价表中「偏远附加费」列/表头:CTT 等按派送费 FREIGHT+邮编前缀落库;
* Evri 等非首重/续重并排列仍可落 REMOTE。
*/ */
private static boolean isRemoteHandleHead(String head) 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 org.apache.poi.ss.usermodel.Workbook;
import com.bms.price.domain.LblProduct; import com.bms.price.domain.LblProduct;
import com.bms.price.domain.LblWeightBand; import com.bms.price.domain.LblWeightBand;
import com.bms.price.domain.PrcZoneDetail;
/** /**
* 打单价卡「邮编分区」表抽取为 zone→postcodes,保存时同步到分区管理 prc_zone。 * 打单价卡「邮编分区」表抽取为 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 public final class LblZonePostcodeAttach
{ {
@@ -43,6 +45,11 @@ public final class LblZonePostcodeAttach
continue; continue;
} }
String sheetName = sheet.getSheetName() == null ? "" : sheet.getSheetName().trim(); String sheetName = sheet.getSheetName() == null ? "" : sheet.getSheetName().trim();
if (isUkSurchargeSheet(sheetName))
{
attachUkEvri(sheet, sheetName, products);
continue;
}
if (!isZonePostcodeSheet(sheetName)) if (!isZonePostcodeSheet(sheetName))
{ {
continue; continue;
@@ -52,17 +59,32 @@ public final class LblZonePostcodeAttach
attachImile(sheet, sheetName, products); attachImile(sheet, sheetName, products);
continue; continue;
} }
Map<String, List<String>> zoneMap = parseSheet(sheet);
if (zoneMap.isEmpty())
{
continue;
}
LblProduct target = matchProduct(products, sheetName); LblProduct target = matchProduct(products, sheetName);
if (target == null) if (target == null)
{ {
continue; 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); linkSheet(target, sheetName);
} }
} }
@@ -95,9 +117,18 @@ public final class LblZonePostcodeAttach
{ {
return m.group(1); 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 ""; return "";
} }
private static boolean isZonePostcodeSheet(String sheetName) private static boolean isZonePostcodeSheet(String sheetName)
{ {
if (sheetName == null || sheetName.isBlank()) if (sheetName == null || sheetName.isBlank())
@@ -107,6 +138,257 @@ public final class LblZonePostcodeAttach
return sheetName.contains("邮编") && sheetName.contains("分区"); 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) private static Map<String, List<String>> parseSheet(Sheet sheet)
{ {
Map<String, List<String>> poste = parsePosteItaliane(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) private static Map<String, List<String>> parseCtt(Sheet sheet)
{ {
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>(); Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
@@ -433,7 +725,8 @@ public final class LblZonePostcodeAttach
LblProduct germany = productOf(products, "DE-iMile"); LblProduct germany = productOf(products, "DE-iMile");
int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS); int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS);
int header = -1; 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); Row row = sheet.getRow(r);
if (row == null) if (row == null)
@@ -443,11 +736,20 @@ public final class LblZonePostcodeAttach
StringBuilder line = new StringBuilder(); StringBuilder line = new StringBuilder();
for (int c = 0; c < row.getLastCellNum(); c++) 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(); 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; header = r;
break; break;
} }
@@ -520,12 +822,12 @@ public final class LblZonePostcodeAttach
} }
if (italy != null && !itMap.isEmpty()) if (italy != null && !itMap.isEmpty())
{ {
mergeZonePostcodes(italy, itMap); mergeZonePostcodes(italy, itMap, PrcZoneDetail.MATCH_FULL);
linkSheet(italy, sheetName); linkSheet(italy, sheetName);
} }
if (germany != null && !deMap.isEmpty()) if (germany != null && !deMap.isEmpty())
{ {
mergeZonePostcodes(germany, deMap); mergeZonePostcodes(germany, deMap, PrcZoneDetail.MATCH_FULL);
linkSheet(germany, sheetName); linkSheet(germany, sheetName);
} }
} }
@@ -550,6 +852,10 @@ public final class LblZonePostcodeAttach
private static LblProduct productOf(List<LblProduct> products, String name) private static LblProduct productOf(List<LblProduct> products, String name)
{ {
if (products == null || name == null || name.isBlank())
{
return null;
}
for (LblProduct product : products) for (LblProduct product : products)
{ {
if (name.equals(product.getSheetName()) || name.equals(product.getProductName()) if (name.equals(product.getSheetName()) || name.equals(product.getProductName())
@@ -558,6 +864,16 @@ public final class LblZonePostcodeAttach
return product; 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; return null;
} }
@@ -615,22 +931,49 @@ public final class LblZonePostcodeAttach
return null; 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) if (current == null)
{ {
current = new LinkedHashMap<String, List<String>>(); current = new LinkedHashMap<String, List<PrcZoneDetail>>();
product.setZonePostcodes(current); product.setZonePostcodes(current);
} }
String type = PrcZoneDetail.normalizeMatchType(matchType);
for (Map.Entry<String, List<String>> e : incoming.entrySet()) 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()) 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,不碰其他产品/常规分区。 * 按打单产品同步 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); applyProductCodeMapping(bill, request);
} }
// 已有真实销售产品名时不覆盖;仅缺失或与编码相同时才用报价结果补全
if (result != null && StringUtils.isNotEmpty(result.getProductName())) 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) if (StringUtils.isEmpty(bill.getCountryCode()) && result != null)
{ {
@@ -219,12 +219,20 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override @Override
public int insertPrcZoneDetail(PrcZoneDetail detail) public int insertPrcZoneDetail(PrcZoneDetail detail)
{ {
if (detail != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.insertPrcZoneDetail(detail); return detailMapper.insertPrcZoneDetail(detail);
} }
@Override @Override
public int updatePrcZoneDetail(PrcZoneDetail detail) public int updatePrcZoneDetail(PrcZoneDetail detail)
{ {
if (detail != null && detail.getMatchType() != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.updatePrcZoneDetail(detail); return detailMapper.updatePrcZoneDetail(detail);
} }
@@ -281,7 +289,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
unmatched.add(item.countryHint + "(" + item.sheetName + ")"); unmatched.add(item.countryHint + "(" + item.sheetName + ")");
continue; continue;
} }
int[] counts = replaceRegionZones(region, zonePostcodes); int[] counts = replaceRegionZones(region, zonePostcodes, item.matchType);
countryCount += 1; countryCount += 1;
zoneCount += counts[0]; zoneCount += counts[0];
detailCount += counts[1]; detailCount += counts[1];
@@ -398,6 +406,10 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail(); PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId()); detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode.trim()); detail.setPostcode(postcode.trim());
if (detail.getMatchType() == null || detail.getMatchType().isBlank())
{
detail.setMatchType(PrcZoneDetail.MATCH_FULL);
}
batch.add(detail); batch.add(detail);
if (batch.size() >= BATCH_SIZE) if (batch.size() >= BATCH_SIZE)
{ {
@@ -418,7 +430,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override @Override
@Transactional(rollbackFor = Exception.class) @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) if (productId == null)
{ {
@@ -456,9 +468,9 @@ public class PrcZoneServiceImpl implements IPrcZoneService
} }
int zoneUpsert = 0; int zoneUpsert = 0;
int detailInserted = 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()))); 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()); String label = StringUtils.trim(entry.getKey());
if (StringUtils.isEmpty(label)) if (StringUtils.isEmpty(label))
@@ -501,21 +513,26 @@ public class PrcZoneServiceImpl implements IPrcZoneService
detailMapper.deletePrcZoneDetailByZoneId(zone.getZoneId()); detailMapper.deletePrcZoneDetailByZoneId(zone.getZoneId());
} }
zoneUpsert++; zoneUpsert++;
Set<String> uniquePostcodes = new LinkedHashSet<String>(); Map<String, PrcZoneDetail> unique = new LinkedHashMap<String, PrcZoneDetail>();
if (entry.getValue() != null) 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); 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); batch.add(detail);
if (batch.size() >= BATCH_SIZE) if (batch.size() >= BATCH_SIZE)
{ {
@@ -534,11 +551,17 @@ public class PrcZoneServiceImpl implements IPrcZoneService
} }
private int[] replaceRegionZones(BmsRegion region, Map<String, List<String>> zonePostcodes) 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())) if (StringUtils.isEmpty(region.getCountryCode2()))
{ {
throw new ServiceException(MessageUtils.message("price.zone.countryCode.empty")); throw new ServiceException(MessageUtils.message("price.zone.countryCode.empty"));
} }
matchType = PrcZoneDetail.normalizeMatchType(matchType);
Long regionId = region.getRegionId(); Long regionId = region.getRegionId();
detailMapper.deletePrcZoneDetailByRegionId(regionId); detailMapper.deletePrcZoneDetailByRegionId(regionId);
zoneMapper.deletePrcZoneByRegionId(regionId); zoneMapper.deletePrcZoneByRegionId(regionId);
@@ -570,6 +593,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail(); PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId()); detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode); detail.setPostcode(postcode);
detail.setMatchType(matchType);
batch.add(detail); batch.add(detail);
if (batch.size() >= BATCH_SIZE) if (batch.size() >= BATCH_SIZE)
{ {
@@ -592,12 +616,19 @@ public class PrcZoneServiceImpl implements IPrcZoneService
private final String sheetName; private final String sheetName;
private final String countryHint; private final String countryHint;
private final Map<String, List<String>> zonePostcodes; private final Map<String, List<String>> zonePostcodes;
private final String matchType;
private SheetImport(String sheetName, String countryHint, Map<String, List<String>> zonePostcodes) 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.sheetName = sheetName;
this.countryHint = countryHint; this.countryHint = countryHint;
this.zonePostcodes = zonePostcodes; this.zonePostcodes = zonePostcodes;
this.matchType = PrcZoneDetail.normalizeMatchType(matchType);
} }
} }
@@ -646,7 +677,11 @@ public class PrcZoneServiceImpl implements IPrcZoneService
{ {
countryHint = sheetName; 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; return list;
} }
@@ -73,6 +73,7 @@ import com.bms.price.search.IBillSearchStore;
import com.bms.price.service.ILblProductService; import com.bms.price.service.ILblProductService;
import com.bms.price.service.IPayProductService; import com.bms.price.service.IPayProductService;
import com.bms.price.label.LblCostCalculator; import com.bms.price.label.LblCostCalculator;
import com.bms.price.label.LblSurchargeRules;
import com.bms.price.label.LblProductPayAdapter; import com.bms.price.label.LblProductPayAdapter;
import com.bms.price.domain.LblFeeType; import com.bms.price.domain.LblFeeType;
import com.bms.price.domain.LblProduct; import com.bms.price.domain.LblProduct;
@@ -739,7 +740,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
throw ex; throw ex;
} }
PayOrderCostResult cost = LblCostCalculator.calculate(lblProduct, weight, length, width, height, 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 (cost == null || cost.getFees() == null || cost.getFees().isEmpty())
{ {
if (request instanceof TmsPriceBillRequest) if (request instanceof TmsPriceBillRequest)
@@ -779,6 +780,12 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return countryFreight.get(0); return countryFreight.get(0);
} }
List<String> candidates = countryFreight.isEmpty() ? zoneNames : countryFreight; 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) if (product == null || product.getProductId() == null)
{ {
throw new ServiceException("邮编未匹配到产品分区"); throw new ServiceException("邮编未匹配到产品分区");
@@ -787,6 +794,13 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
product.getProductId(), normalizePostcode(destPostcode)); product.getProductId(), normalizePostcode(destPostcode));
if (resolved == null) 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("邮编未匹配到产品分区"); throw new ServiceException("邮编未匹配到产品分区");
} }
String mapped = PayZoneMatcher.mapRegion(candidates, resolved.getZoneCode()); String mapped = PayZoneMatcher.mapRegion(candidates, resolved.getZoneCode());
@@ -803,6 +817,69 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return mapped; 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) private static List<String> labelBandZoneNames(LblProduct product)
{ {
LinkedHashSet<String> names = new LinkedHashSet<String>(); LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -825,7 +902,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return new ArrayList<String>(names); return new ArrayList<String>(names);
} }
/** 该国家下运费(FREIGHT)分区列名;偏远行不算入。 */ /** 该国家下运费(FREIGHT)分区列名(含带邮编前缀的岛屿派送费)。 */
private static List<String> labelFreightZonesForCountry(LblProduct product, String countryCode) private static List<String> labelFreightZonesForCountry(LblProduct product, String countryCode)
{ {
LinkedHashSet<String> names = new LinkedHashSet<String>(); LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -980,8 +1057,8 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
{ {
incomeTotal = freightAmount.add(registrationFee).add(surchargeAmount).setScale(2, rm); 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(); TmsPriceQuoteResult r = new TmsPriceQuoteResult();
r.setMatchSource(SRC_LABEL); r.setMatchSource(SRC_LABEL);
r.setMatchMessage("hit label package pay card V" 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.setVersionNo(product.getVersionNo() == null ? null : ("V" + product.getVersionNo()));
r.setCustomerId(bind.getCustomerId()); r.setCustomerId(bind.getCustomerId());
r.setProductCode(productCode); r.setProductCode(productCode);
r.setProductName(labelProductName); r.setProductName(keepProductName);
r.setCountryCode(countryCode); r.setCountryCode(countryCode);
r.setCountryName(countryName); r.setCountryName(countryName);
r.setWeight(weight); r.setWeight(weight);
@@ -8,12 +8,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<id property="detailId" column="detail_id" /> <id property="detailId" column="detail_id" />
<result property="zoneId" column="zone_id" /> <result property="zoneId" column="zone_id" />
<result property="postcode" column="postcode" /> <result property="postcode" column="postcode" />
<result property="matchType" column="match_type" />
<result property="createTime" column="create_time" /> <result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" /> <result property="updateTime" column="update_time" />
</resultMap> </resultMap>
<sql id="selectPrcZoneDetailVo"> <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 from prc_zone_detail
</sql> </sql>
@@ -51,18 +52,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
insert into prc_zone_detail ( insert into prc_zone_detail (
<if test="zoneId != null">zone_id,</if> <if test="zoneId != null">zone_id,</if>
<if test="postcode != null and postcode != ''">postcode,</if> <if test="postcode != null and postcode != ''">postcode,</if>
match_type,
create_time create_time
) values ( ) values (
<if test="zoneId != null">#{zoneId},</if> <if test="zoneId != null">#{zoneId},</if>
<if test="postcode != null and postcode != ''">#{postcode},</if> <if test="postcode != null and postcode != ''">#{postcode},</if>
#{matchType},
sysdate() sysdate()
) )
</insert> </insert>
<insert id="insertPrcZoneDetailBatch"> <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=","> <foreach collection="list" item="item" separator=",">
(#{item.zoneId}, #{item.postcode}, sysdate()) (#{item.zoneId}, #{item.postcode}, #{item.matchType}, sysdate())
</foreach> </foreach>
</insert> </insert>
@@ -71,6 +74,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<set> <set>
<if test="zoneId != null">zone_id = #{zoneId},</if> <if test="zoneId != null">zone_id = #{zoneId},</if>
<if test="postcode != null and postcode != ''">postcode = #{postcode},</if> <if test="postcode != null and postcode != ''">postcode = #{postcode},</if>
<if test="matchType != null and matchType != ''">match_type = #{matchType},</if>
update_time = sysdate() update_time = sysdate()
</set> </set>
where detail_id = #{detailId} where detail_id = #{detailId}
@@ -120,8 +124,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and z.product_id is null and z.product_id is null
and upper(ifnull(z.country_code,'')) = upper(#{countryCode}) and upper(ifnull(z.country_code,'')) = upper(#{countryCode})
and ( 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 order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end, 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' where z.zone_type = 'LABEL'
and z.product_id = #{productId} and z.product_id = #{productId}
and ( 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 order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end, case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end,
@@ -0,0 +1,78 @@
-- 众升 2026-11-19 渠道变更:prc_order_bill 同步修改产品名称+产品代码(66 单)
-- 守卫带旧产品代码,防误改;执行后核对查询应看到 6 组新值、无旧值残留
-- 备份(回滚用,可不执行)
-- CREATE TABLE bak_prc_order_bill_20261119 AS
-- SELECT * FROM prc_order_bill WHERE order_no IN (
-- 'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
-- 'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
-- 'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
-- 'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
-- 'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
-- 'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
-- 'MS20261103235057005', 'JH20261107111V', 'YDM11071749901S', 'MMP43', 'I020261104550165010176YYYYYY', 'OA23201B', '1327110118498773', 'T210---1',
-- 'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'YWLT11091749882', 'OA23332', 'YWLT11111549923',
-- 'XM2GRX3010155', 'MS20261105040758061'
-- );
-- 1. 标快服装-包税(限定)(WSP117) -> 标快普货-包税(限定)(WSP118),49 单
UPDATE prc_order_bill
SET product_name = '标快普货-包税(限定)', product_code = 'WSP118'
WHERE product_code = 'WSP117' AND order_no IN (
'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
'MS20261103235057005'
);
-- 2. 标快球衣-包税(WSP037) -> 球衣服装-包税(WSP099),2 单
UPDATE prc_order_bill
SET product_name = '球衣服装-包税', product_code = 'WSP099'
WHERE product_code = 'WSP037' AND order_no IN (
'JH20261107111V', 'YDM11071749901S'
);
-- 3. 全球标快-球衣(WSP020) -> 标快服装-球衣(WSP098),2 单
UPDATE prc_order_bill
SET product_name = '标快服装-球衣', product_code = 'WSP098'
WHERE product_code = 'WSP020' AND order_no IN (
'MMP43', 'I020261104550165010176YYYYYY'
);
-- 4. 标快鞋盒-硬包(WSP067) -> 全球标快-球衣(WSP020),4 单
UPDATE prc_order_bill
SET product_name = '全球标快-球衣', product_code = 'WSP020'
WHERE product_code = 'WSP067' AND order_no IN (
'OA23201B', 'YWLT11091749882', 'YWLT11111549923', 'XM2GRX3010155'
);
-- 5. 标快鞋盒-包税(WSP066) -> 标快球衣-包税(WSP037),8 单
UPDATE prc_order_bill
SET product_name = '标快球衣-包税', product_code = 'WSP037'
WHERE product_code = 'WSP066' AND order_no IN (
'1327110118498773', 'T210---1', 'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'OA23332'
);
-- 6. 标快服装-包税(限定)(WSP117) -> 标快鞋盒-包税(WSP066),1 单
UPDATE prc_order_bill
SET product_name = '标快鞋盒-包税', product_code = 'WSP066'
WHERE product_code = 'WSP117' AND order_no IN (
'MS20261105040758061'
);
-- 核对:应只剩 6 组新值,总 66 单
SELECT product_name, product_code, COUNT(*) AS 单数
FROM prc_order_bill WHERE order_no IN (
'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
'MS20261103235057005', 'JH20261107111V', 'YDM11071749901S', 'MMP43', 'I020261104550165010176YYYYYY', 'OA23201B', '1327110118498773', 'T210---1',
'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'YWLT11091749882', 'OA23332', 'YWLT11111549923',
'XM2GRX3010155', 'MS20261105040758061'
) GROUP BY product_name, product_code ORDER BY 单数 DESC;
+1
View File
@@ -1596,6 +1596,7 @@ CREATE TABLE `prc_zone_detail` (
`detail_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'detail id', `detail_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'detail id',
`zone_id` bigint(20) NOT NULL COMMENT 'zone id', `zone_id` bigint(20) NOT NULL COMMENT 'zone id',
`postcode` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'postcode', `postcode` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'postcode',
`match_type` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'FULL' COMMENT 'FULL exact / PREFIX starts with',
`create_time` datetime DEFAULT NULL COMMENT 'created at', `create_time` datetime DEFAULT NULL COMMENT 'created at',
`update_time` datetime DEFAULT NULL COMMENT 'updated at', `update_time` datetime DEFAULT NULL COMMENT 'updated at',
PRIMARY KEY (`detail_id`), PRIMARY KEY (`detail_id`),
@@ -0,0 +1,13 @@
-- prc_zone_detail.match_type: FULL exact / PREFIX starts-with
-- Idempotent. Column default is FULL. No bulk rewrite of existing rows.
SET @db := DATABASE();
SELECT COUNT(*) INTO @col_match_type
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_zone_detail' AND COLUMN_NAME = 'match_type';
SET @sql := IF(@col_match_type = 0,
'ALTER TABLE prc_zone_detail ADD COLUMN match_type varchar(16) NOT NULL DEFAULT ''FULL'' COMMENT ''FULL exact match / PREFIX starts with'' AFTER postcode',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
@@ -0,0 +1,7 @@
-- One-shot: undo earlier mistaken "all rows = PREFIX" migration.
-- Default display/billing type becomes FULL.
-- After running, re-import Evri / UK / Canada remote sheets if those need PREFIX.
UPDATE prc_zone_detail
SET match_type = 'FULL'
WHERE match_type IS NULL OR match_type = '' OR UPPER(match_type) = 'PREFIX';
@@ -171,13 +171,20 @@ function scheduleAutoCollapse() {
} }
function open(filterQuery, autoStart) { function open(filterQuery, autoStart) {
// Already running / finished: just reopen progress view (same as order-list rebill). // Still running: only reopen progress (do not start another task).
if (loading.value || finished.value) { if (loading.value) {
visible.value = true visible.value = true
return return
} }
// Finished + reopen only (float click): show last result.
if (finished.value && !autoStart && filterQuery == null) {
visible.value = true
return
}
// New sync: clear previous result first.
query.value = { ...(filterQuery || {}) } query.value = { ...(filterQuery || {}) }
asyncTaskIdRef.value = '' asyncTaskIdRef.value = ''
pollGeneration.value += 1
progress.value = { progress.value = {
percent: 0, percent: 0,
message: '', message: '',
@@ -357,7 +364,11 @@ onBeforeUnmount(() => {
pollGeneration.value += 1 pollGeneration.value += 1
}) })
defineExpose({ open }) function reopen() {
visible.value = true
}
defineExpose({ open, reopen })
</script> </script>
<style scoped> <style scoped>
@@ -2,7 +2,7 @@
<div class="app-container order-source-page"> <div class="app-container order-source-page">
<div v-if="syncFloatVisible" class="retry-status-float"> <div v-if="syncFloatVisible" class="retry-status-float">
<el-tooltip :content="syncFloatTooltip" placement="bottom"> <el-tooltip :content="syncFloatTooltip" placement="bottom">
<el-button class="retry-status-button" type="primary" plain size="small" @click="openFilterSync()"> <el-button class="retry-status-button" type="primary" plain size="small" @click="reopenSyncProgress()">
<span class="retry-progress-ring" :style="{ '--retry-progress': syncProgressDegree + 'deg' }" aria-hidden="true"> <span class="retry-progress-ring" :style="{ '--retry-progress': syncProgressDegree + 'deg' }" aria-hidden="true">
<span class="retry-progress-value">{{ syncProgressText }}</span> <span class="retry-progress-value">{{ syncProgressText }}</span>
</span> </span>
@@ -458,12 +458,28 @@ function onCompareFillSearch(payload) {
tableRef.value?.handleQuery?.() tableRef.value?.handleQuery?.()
} }
function reopenSyncProgress() {
const dlg = syncDialogRef.value
if (dlg && typeof dlg.reopen === 'function') {
dlg.reopen()
} else {
dlg?.open(null, false)
}
}
function openFilterSync() { function openFilterSync() {
// Running / just finished: reopen progress dialog (same as order-list float click). // Running: reopen progress; finished result must not block a new sync.
if (syncFloat.value && (syncFloat.value.loading || syncFloat.value.finished)) { if (syncFloat.value?.loading) {
syncDialogRef.value?.open(null, false) reopenSyncProgress()
return return
} }
if (syncFloat.value?.finished) {
if (syncFloatHideTimer) {
clearTimeout(syncFloatHideTimer)
syncFloatHideTimer = null
}
syncFloat.value = null
}
const q = buildFilterQuery() const q = buildFilterQuery()
const identifierCount = (q.orderIdentifiers || []).length const identifierCount = (q.orderIdentifiers || []).length
const hasIdentifier = identifierCount > 0 const hasIdentifier = identifierCount > 0
@@ -25,6 +25,11 @@
<el-table v-loading="loading" :data="list" border row-key="detailId" empty-text="暂无邮编"> <el-table v-loading="loading" :data="list" border row-key="detailId" empty-text="暂无邮编">
<el-table-column label="ID" prop="detailId" align="center" width="90" /> <el-table-column label="ID" prop="detailId" align="center" width="90" />
<el-table-column label="邮编" prop="postcode" align="center" min-width="140" /> <el-table-column label="邮编" prop="postcode" align="center" min-width="140" />
<el-table-column label="匹配类型" prop="matchType" align="center" min-width="140">
<template #default="{ row }">
{{ matchTypeText(row.matchType) }}
</template>
</el-table-column>
<el-table-column label="操作" align="center" width="160"> <el-table-column label="操作" align="center" width="160">
<template #default="{ row }"> <template #default="{ row }">
<el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['price:zone:edit']">编辑</el-button> <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['price:zone:edit']">编辑</el-button>
@@ -96,6 +101,11 @@ function loadList() {
}) })
} }
function matchTypeText(type) {
if (String(type || '').toUpperCase() === 'PREFIX') return '匹配邮编开头'
return '全匹配'
}
function handleAdd() { function handleAdd() {
postcodeFormRef.value.open(selectedZone.value) postcodeFormRef.value.open(selectedZone.value)
} }
@@ -1,9 +1,15 @@
<template> <template>
<el-dialog :title="title" v-model="visible" width="420px" append-to-body> <el-dialog :title="title" v-model="visible" width="480px" append-to-body>
<el-form ref="postcodeFormRef" :model="form" :rules="rules" label-width="80px"> <el-form ref="postcodeFormRef" :model="form" :rules="rules" label-width="100px">
<el-form-item label="邮编" prop="postcode"> <el-form-item label="邮编" prop="postcode">
<el-input v-model="form.postcode" placeholder="请输入邮编" maxlength="32" /> <el-input v-model="form.postcode" placeholder="请输入邮编" maxlength="32" />
</el-form-item> </el-form-item>
<el-form-item label="匹配类型" prop="matchType">
<el-radio-group v-model="form.matchType">
<el-radio label="FULL">全匹配</el-radio>
<el-radio label="PREFIX">匹配邮编开头</el-radio>
</el-radio-group>
</el-form-item>
</el-form> </el-form>
<template #footer> <template #footer>
<div class="dialog-footer"> <div class="dialog-footer">
@@ -26,17 +32,19 @@ const title = ref('')
const postcodeFormRef = ref() const postcodeFormRef = ref()
const form = ref({}) const form = ref({})
const rules = { const rules = {
postcode: [{ required: true, message: '邮编不能为空', trigger: 'blur' }] postcode: [{ required: true, message: '邮编不能为空', trigger: 'blur' }],
matchType: [{ required: true, message: '请选择匹配类型', trigger: 'change' }]
} }
/** zone 为所属分区;row 传空为新增,传邮编行为编辑 */ /** zone 为所属分区;row 传空为新增,传邮编行为编辑 */
function open(zone, row) { function open(zone, row) {
form.value = row form.value = row
? { ...row } ? { ...row, matchType: row.matchType || 'FULL' }
: { : {
detailId: undefined, detailId: undefined,
zoneId: zone?.zoneId, zoneId: zone?.zoneId,
postcode: undefined postcode: undefined,
matchType: 'FULL'
} }
title.value = row ? '编辑邮编' : '新增邮编' title.value = row ? '编辑邮编' : '新增邮编'
visible.value = true visible.value = true
@@ -48,7 +56,8 @@ function submitForm() {
if (!valid) return if (!valid) return
const payload = { const payload = {
...form.value, ...form.value,
postcode: String(form.value.postcode || '').trim() postcode: String(form.value.postcode || '').trim(),
matchType: form.value.matchType || 'FULL'
} }
const req = payload.detailId != null ? updateDetail(payload) : addDetail(payload) const req = payload.detailId != null ? updateDetail(payload) : addDetail(payload)
req.then(() => { req.then(() => {
+50 -4
View File
@@ -166,7 +166,7 @@ const pageBanner = computed(() => {
return `新建版本:${name}(${code})` return `新建版本:${name}(${code})`
}) })
const headerTip = computed(() => { const headerTip = computed(() => {
if (editVersionMode.value) return '可重新导入或修改明细;完成后按ID更新/新增/删除,不新增版本号' if (editVersionMode.value) return '可重新导入或修改明细;再导入按产品合并(同名覆盖、其余保留),完成后按ID更新/新增/删除,不新增版本号'
if (newVersionMode.value) return '导入后生成待生效新版本;生效时间请回详情页设置' if (newVersionMode.value) return '导入后生成待生效新版本;生效时间请回详情页设置'
return '打单价卡与应付独立;解析后回填到此表,可删除不需要的产品,编辑明细后点完成保存' return '打单价卡与应付独立;解析后回填到此表,可删除不需要的产品,编辑明细后点完成保存'
}) })
@@ -246,6 +246,23 @@ function productKey(row) {
return row?.rowKey || `${row?.sheetName || ''}-${row?.productName || ''}` return row?.rowKey || `${row?.sheetName || ''}-${row?.productName || ''}`
} }
/** 用于编辑再导入时判断同一产品(dict/名称/表名任一相等即命中) */
function productTokens(row) {
return [row?.dictValue, row?.productName, row?.sheetName]
.map(s => String(s || '').toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]/g, ''))
.filter(Boolean)
}
function productIdentity(row) {
return productTokens(row)[0] || ''
}
function sameProduct(left, right) {
const a = new Set(productTokens(left))
const b = productTokens(right)
return b.some(token => a.has(token))
}
function aliveDetailRows(list) { function aliveDetailRows(list) {
return (list || []).filter(row => row && row.deleted !== true) return (list || []).filter(row => row && row.deleted !== true)
} }
@@ -319,14 +336,43 @@ async function removeSelectedProducts() {
} }
function onImportConfirm(payload) { function onImportConfirm(payload) {
const incoming = (payload?.products || []).filter(Boolean)
if (editVersionMode.value) { if (editVersionMode.value) {
for (const row of productRows.value || []) { // 编辑再导入:按产品合并,不清空其它产品;同名则用新价卡覆盖
if (row?.versionId || row?.productId) markProductRemoved(row) const matched = new Set()
const replaced = []
for (const neu of incoming) {
const key = productIdentity(neu)
if (!key) {
replaced.push(neu)
continue
}
const old = (productRows.value || []).find(row => sameProduct(row, neu))
if (old) {
for (const token of productTokens(old)) matched.add(token)
for (const token of productTokens(neu)) matched.add(token)
if (old.versionId || old.productId) {
markProductRemoved(old)
}
replaced.push({
...neu,
productId: old.productId ?? neu.productId,
versionId: null,
termId: null,
rowKey: `${neu.sheetName || ''}-${neu.productName || ''}-${old.productId || old.versionId || ''}`,
duplicated: true
})
} else {
for (const token of productTokens(neu)) matched.add(token)
replaced.push(neu)
}
} }
const kept = (productRows.value || []).filter(row => !productTokens(row).some(token => matched.has(token)))
productRows.value = [...kept, ...replaced]
} else { } else {
removedProducts.value = [] removedProducts.value = []
productRows.value = incoming
} }
productRows.value = payload?.products || []
selectedProducts.value = [] selectedProducts.value = []
importMeta.sourceFile = payload?.sourceFile || '' importMeta.sourceFile = payload?.sourceFile || ''
importMeta.supplierName = payload?.supplierName || '' importMeta.supplierName = payload?.supplierName || ''