应付计算evri和CTT模板调整计费

This commit is contained in:
liuminghui
2026-11-19 16:49:30 +08:00
parent 43a8bd61e8
commit 908975a7d6
13 changed files with 824 additions and 120 deletions
@@ -50,11 +50,41 @@ class PayCostCalculatorTest
PayOrderCostResult over = PayCostCalculator.calculate(product, new BigDecimal("7"),
null, null, null, null, "Mainland / Mad High Density", null, 1);
assertTrue(hasFee(over, "基础运费", "3.18"));
assertTrue(hasFee(over, "每公斤续重", "0.54"));
assertTrue(hasFee(over, "基础运费", "3.72"));
assertTrue(over.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
assertEquals(new BigDecimal("3.72"), over.getPayTotal());
}
@Test
void continuationChargesAFullStepWhenTheExcessIsUnderOneKilogram()
{
PayProduct product = new PayProduct();
product.setProductName("CTT 48H");
product.setCurrency("EUR");
PayWeightBand first = band("0", "1", "2.40", "Medium");
first.setSectionName("派送费");
first.setChargeName("派送费");
first.setPriceUnit("EUR/ITEM");
product.setWeightBands(new ArrayList<>(List.of(first)));
PaySurcharge extra = fee(11L, "每公斤续重", "0.34", "EUR", "EXTRA_KG", "1");
extra.setSectionName("派送费");
extra.setZoneName("Medium");
extra.setPriceUnit("EUR/KG");
extra.setChargeText("每增加 1Kg 0.34 EUR/KG");
product.setSurcharges(List.of(extra));
PayOrderCostResult partial = PayCostCalculator.calculate(product, new BigDecimal("1.2"),
null, null, null, null, "Medium", null, 1);
assertTrue(hasFee(partial, "基础运费", "2.74"));
assertTrue(partial.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
assertEquals(new BigDecimal("2.74"), partial.getPayTotal());
PayOrderCostResult twoSteps = PayCostCalculator.calculate(product, new BigDecimal("2.2"),
null, null, null, null, "Medium", null, 1);
assertTrue(hasFee(twoSteps, "基础运费", "3.08"));
assertTrue(twoSteps.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
}
@Test
void boundSurchargesKeepTheCardContinuation()
{
@@ -81,8 +111,8 @@ class PayCostCalculatorTest
PayOrderCostResult over = PayCostCalculator.calculate(product, new BigDecimal("3"),
null, null, null, "KY4 0DN", "UK Mainland", null, 1);
assertTrue(hasFee(over, "基础运费", "10"));
assertTrue(hasFee(over, "每公斤续重", "4"));
assertTrue(hasFee(over, "基础运费", "14"));
assertTrue(over.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
assertTrue(hasFee(over, "燃油", "1"));
assertFalse(over.getFees().stream().anyMatch(fee -> fee.getFeeName().contains("偏远")));
assertFalse(over.getFees().stream().anyMatch(fee -> "超重续收".equals(fee.getFeeName())));
@@ -166,9 +196,8 @@ class PayCostCalculatorTest
PayOrderCostResult over = PayCostCalculator.calculate(product, new BigDecimal("2"),
null, null, null, null, "Canary Islands / Minor Islands", null, 1);
assertTrue(hasFee(over, "基础运费", "13.12"));
assertTrue(hasFee(over, "每公斤续重", "1.86"));
assertEquals(1, over.getFees().stream().filter(fee -> "每公斤续重".equals(fee.getFeeName())).count());
assertTrue(hasFee(over, "基础运费", "14.98"));
assertTrue(over.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
assertEquals(new BigDecimal("14.98"), over.getPayTotal());
}
@@ -233,6 +262,43 @@ class PayCostCalculatorTest
assertTrue(mainland.getFees().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName())));
}
@Test
void evriRemoteWeightBandAddsTheSameWeightRow()
{
PayProduct product = new PayProduct();
product.setProductName("Evri 48H");
product.setCurrency("GBP");
PayWeightBand mainlandLight = band("0", "1", "1.51", "UK Mainland\n英国大陆");
mainlandLight.setChargeName("派送费");
mainlandLight.setSectionName("派送费");
PayWeightBand mainlandNext = band("1", "2", "1.53", "UK Mainland\n英国大陆");
mainlandNext.setChargeName("派送费");
mainlandNext.setSectionName("派送费");
PayWeightBand highlandsLight = band("0", "1", "5.95", "Highlands& Islands\n高地和岛屿");
highlandsLight.setChargeName("偏远附加费");
highlandsLight.setSectionName("偏远附加费");
PayWeightBand highlandsNext = band("1", "2", "5.95", "Highlands& Islands\n高地和岛屿");
highlandsNext.setChargeName("偏远附加费");
highlandsNext.setSectionName("偏远附加费");
PayWeightBand heavyRemote = band("15", "20", "8.2", "Highlands& Islands\n高地和岛屿");
heavyRemote.setChargeName("偏远附加费");
heavyRemote.setSectionName("偏远附加费");
product.setWeightBands(new ArrayList<>(List.of(mainlandLight, mainlandNext, highlandsLight, highlandsNext, heavyRemote)));
PayOrderCostResult mainland = PayCostCalculator.calculate(product, new BigDecimal("0.5"),
null, null, null, "LL22 8PJ", "UK Mainland\n英国大陆", null, 1);
assertTrue(hasFee(mainland, "基础运费", "1.51"));
assertTrue(mainland.getFees().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName())));
assertEquals(new BigDecimal("1.51"), mainland.getPayTotal());
PayOrderCostResult remote = PayCostCalculator.calculate(product, new BigDecimal("0.5"),
null, null, null, "IV1 1AA", "Highlands& Islands\n高地和岛屿", null, 1);
assertTrue(hasFee(remote, "基础运费", "1.51"));
assertTrue(hasFee(remote, "偏远附加费", "5.95"));
assertEquals(1, remote.getFees().stream().filter(fee -> "偏远附加费".equals(fee.getFeeName())).count());
assertEquals(new BigDecimal("7.46"), remote.getPayTotal());
}
@Test
void spanishPrefixChargesFirstWeightThenExtraKg()
{
@@ -284,9 +350,11 @@ class PayCostCalculatorTest
PayWeightBand lineHaul = band("0", "1", "0.09", "Mad High Density 马德里高密度地区");
lineHaul.setSectionName("额外线路运输费");
lineHaul.setChargeName("额外线路运输费");
PayWeightBand remote = band("0", "1", "7.1", "Balearic Islands 07邮编开头");
PayWeightBand remote = band("0", "1", "7.1", "Balearic Islands");
remote.setSectionName("偏远附加费");
remote.setChargeName("偏远附加费");
remote.setCalcRule("POSTCODE");
remote.setCalcParam("07");
product.setWeightBands(new ArrayList<>(List.of(delivery, lineHaul, remote)));
PaySurcharge deliveryExtra = fee(11L, "每公斤续重", "0.29", "EUR", "EXTRA_KG", "1");
deliveryExtra.setSectionName("派送费");
@@ -296,21 +364,19 @@ class PayCostCalculatorTest
lineExtra.setZoneName("Mad High Density 马德里高密度地区");
PaySurcharge remoteExtra = fee(13L, "每公斤续重", "4", "EUR", "EXTRA_KG", "1");
remoteExtra.setSectionName("偏远附加费");
remoteExtra.setZoneName("Balearic Islands 07邮编开头");
remoteExtra.setZoneName("Balearic Islands");
product.setSurcharges(List.of(deliveryExtra, lineExtra, remoteExtra));
PayOrderCostResult island = PayCostCalculator.calculate(product, new BigDecimal("3"),
null, null, null, "07008", "Mad High Density 马德里高密度地区", null, 1);
assertTrue(hasFee(island, "基础运费", "2.05"));
assertTrue(hasFee(island, "每公斤续重", "0.58"));
assertTrue(hasFee(island, "额外线路运输费", "0.09"));
assertTrue(hasFee(island, "额外线路运输费", "0.10"));
assertTrue(hasFee(island, "偏远附加费", "7.1"));
assertTrue(hasFee(island, "偏远附加费", "8"));
null, null, null, "07008", "Mad High Density 马德里高密度地区", null, 1, List.of(), true, true, "ES", "西班牙");
assertTrue(hasFee(island, "基础运费", "15.1"));
assertTrue(island.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())
|| fee.getAmount().compareTo(new BigDecimal("2.05")) == 0
|| fee.getFeeName().contains("额外线路") || "偏远附加费".equals(fee.getFeeName())));
PayOrderCostResult mainland = PayCostCalculator.calculate(product, new BigDecimal("3"),
null, null, null, "28001", "Mad High Density 马德里高密度地区", null, 1);
assertTrue(hasFee(mainland, "基础运费", "2.05"));
assertTrue(hasFee(mainland, "基础运费", "2.63"));
assertTrue(hasFee(mainland, "额外线路运输费", "0.09"));
assertTrue(mainland.getFees().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName())));
assertEquals("07", PaySurchargeRules.remotePrefixes("Balearic Islands 07邮编开头"));
@@ -319,6 +385,40 @@ class PayCostCalculatorTest
assertEquals("", PaySurchargeRules.remotePrefixes("岛屿邮编地区"));
}
@Test
void weightBandConditionSelectsSizeOrWeightTier()
{
PayProduct product = new PayProduct();
product.setProductName("尺寸重量");
product.setCurrency("EUR");
PayWeightBand normal = band("0", "30", "2.00", "普通");
normal.setSectionName("派送费");
normal.setChargeName("派送费");
PayWeightBand heavy = band("0", "30", "8.00", "超重");
heavy.setSectionName("派送费");
heavy.setChargeName("派送费");
heavy.setCalcRule("WEIGHT");
heavy.setCalcParam("5");
PayWeightBand bulky = band("0", "30", "12.00", "超尺寸");
bulky.setSectionName("派送费");
bulky.setChargeName("派送费");
bulky.setCalcRule("SIZE");
bulky.setCalcParam("side:100");
product.setWeightBands(new ArrayList<>(List.of(normal, heavy, bulky)));
PayOrderCostResult plain = PayCostCalculator.calculate(product, new BigDecimal("2"),
new BigDecimal("40"), new BigDecimal("30"), new BigDecimal("20"), "28001", "普通", null, 1);
assertTrue(hasFee(plain, "基础运费", "2"));
PayOrderCostResult overWeight = PayCostCalculator.calculate(product, new BigDecimal("6"),
new BigDecimal("40"), new BigDecimal("30"), new BigDecimal("20"), "28001", "普通", null, 1);
assertTrue(hasFee(overWeight, "基础运费", "8"));
PayOrderCostResult overSize = PayCostCalculator.calculate(product, new BigDecimal("6"),
new BigDecimal("120"), new BigDecimal("30"), new BigDecimal("20"), "28001", "普通", null, 1);
assertTrue(hasFee(overSize, "基础运费", "12"));
}
@Test
void productPostcodeBookChoosesTheMatchingRemoteFee()
{
@@ -37,8 +37,24 @@ class PayWorkbookParserTest
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getWeightLabel() != null && band.getWeightLabel().contains("首重") && decimal(band, "2.05")));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> band.getWeightLabel() != null && band.getWeightLabel().contains("每增加")));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> "每公斤续重".equals(fee.getFeeName()) && fee.getAmount() != null && fee.getAmount().compareTo(new BigDecimal("0.29")) == 0));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getChargeName() != null && band.getChargeName().contains("偏远") && decimal(band, "7.1")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getChargeName() != null && (band.getChargeName().contains("额外") || band.getChargeName().toLowerCase().contains("line-haul")) && decimal(band, "0.09")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "西班牙(ES)".equals(band.getCountryName()) && "ES".equals(band.getCountryCode())
&& band.getZoneName() != null && band.getZoneName().contains("马德里") && decimal(band, "2.05")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "葡萄牙(PT)".equals(band.getCountryName()) && "PT".equals(band.getCountryCode())
&& band.getZoneName() != null && band.getZoneName().contains("Mainland") && decimal(band, "2.63")));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> band.getCountryName() != null && band.getCountryName().contains("西班牙") && band.getCountryName().contains("葡萄牙")));
assertEquals(1, ctt.getWeightBands().stream().filter(band -> "葡萄牙(PT)".equals(band.getCountryName()) && "派送费".equals(band.getChargeName())).count());
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getChargeName() != null && band.getChargeName().contains("偏远")
&& "西班牙(ES)".equals(band.getCountryName()) && "Balearic Islands".equals(band.getZoneName())
&& "POSTCODE".equals(band.getCalcRule()) && "07".equals(band.getCalcParam()) && decimal(band, "7.1")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getChargeName() != null && band.getChargeName().contains("偏远")
&& "葡萄牙(PT)".equals(band.getCountryName()) && "Portuguese Island".equals(band.getZoneName())
&& "POSTCODE".equals(band.getCalcRule()) && "9".equals(band.getCalcParam())));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> band.getZoneName() != null && band.getZoneName().contains("邮编")));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> "每公斤续重".equals(fee.getFeeName()) && fee.getSectionName() != null && fee.getSectionName().contains("偏远")
&& fee.getZoneName() != null && "Balearic Islands".equals(fee.getZoneName())
&& fee.getAmount() != null && fee.getAmount().compareTo(new BigDecimal("4")) == 0));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> band.getChargeName() != null && (band.getChargeName().contains("额外") || band.getChargeName().toLowerCase().contains("line-haul"))));
assertTrue(ctt.getSurcharges().stream().noneMatch(fee -> fee.getFeeName() != null && (fee.getFeeName().contains("额外线路") || fee.getFeeName().toLowerCase().contains("line-haul") || fee.getSectionName() != null && fee.getSectionName().toLowerCase().contains("line-haul"))));
}
@Test
@@ -225,14 +241,24 @@ class PayWorkbookParserTest
assertEquals("Evri 48H", evri.getDictValue());
assertEquals("Evri 48H", evri.getSheetName());
assertFalse(evri.getWeightBands().isEmpty());
assertTrue(evri.getWeightBands().stream().allMatch(band -> "派送费".equals(band.getChargeName())));
assertTrue(evri.getWeightBands().stream().noneMatch(band -> bandText(band).contains("偏远") || bandText(band).contains("Highlands")));
assertTrue(evri.getWeightBands().stream().anyMatch(band -> decimal(band, "1.51") && band.getZoneName().contains("Mainland")));
PaySurcharge highlands = evri.getSurcharges().stream()
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Highlands") && decimalFee(fee, "5.95"))
assertTrue(evri.getWeightBands().stream().filter(band -> "派送费".equals(band.getChargeName()))
.allMatch(band -> band.getZoneName() != null && band.getZoneName().contains("Mainland")));
assertTrue(evri.getWeightBands().stream().anyMatch(band -> decimal(band, "1.51") && band.getZoneName().contains("Mainland")
&& "派送费".equals(band.getChargeName())));
PayWeightBand highlands = evri.getWeightBands().stream()
.filter(band -> "偏远附加费".equals(band.getChargeName()) && band.getZoneName().contains("Highlands") && decimal(band, "5.95"))
.findFirst().orElseThrow();
assertEquals("ZONE", highlands.getCalcRule());
assertTrue(highlands.getWeightMax() != null && highlands.getWeightMax().compareTo(java.math.BigDecimal.ONE) == 0);
assertTrue(highlands.getWeightMin() != null && highlands.getWeightMin().compareTo(java.math.BigDecimal.ZERO) == 0);
assertEquals(5, evri.getWeightBands().stream()
.filter(band -> "偏远附加费".equals(band.getChargeName()) && band.getWeightMax() != null
&& band.getWeightMax().compareTo(java.math.BigDecimal.ONE) == 0)
.count());
assertTrue(evri.getWeightBands().stream().anyMatch(band -> "偏远附加费".equals(band.getChargeName())
&& band.getZoneName().contains("Isle of Man") && decimal(band, "8.2")
&& band.getWeightMin() != null && band.getWeightMin().compareTo(new java.math.BigDecimal("15")) == 0));
assertTrue(evri.getSurcharges().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName()) && decimalFee(fee, "5.95")));
assertTrue(evri.getSurcharges().stream().anyMatch(fee -> "战争附加费".equals(fee.getFeeName())));
}
@Test
@@ -458,29 +484,18 @@ class PayWorkbookParserTest
PayPreview preview = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(), "CTT 48H",
List.of("CTT 48H"));
PayProduct ctt = preview.getProducts().get(0);
assertTrue(ctt.getWeightBands().stream().allMatch(band -> "派送费".equals(band.getChargeName())),
ctt.getWeightBands().stream().map(band -> band.getChargeName() + "/" + band.getZoneName() + "/" + band.getPrice()).toList().toString());
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> decimal(band, "2.05") && band.getZoneName().contains("马德里")));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> bandText(band).contains("偏远") || bandText(band).contains("额外")
|| bandText(band).toLowerCase().contains("line-haul")));
PaySurcharge balearic = ctt.getSurcharges().stream()
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Balearic") && decimalFee(fee, "7.1"))
.findFirst().orElseThrow();
assertTrue(balearic.getFeeDesc().contains("首重"));
assertEquals("POSTCODE", balearic.getCalcRule());
assertTrue(balearic.getCalcParam() != null && balearic.getCalcParam().contains("07"));
assertTrue(balearic.getWeightMax() != null && balearic.getWeightMax().compareTo(new java.math.BigDecimal("1")) == 0);
PaySurcharge canary = ctt.getSurcharges().stream()
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Canary") && decimalFee(fee, "4.5")
&& fee.getChargeText().contains("KG"))
.findFirst().orElseThrow();
assertEquals("EXTRA_KG", canary.getCalcRule());
assertEquals("1", canary.getCalcParam());
assertTrue(canary.getPostcodeParam() != null && canary.getPostcodeParam().contains("35") && canary.getPostcodeParam().contains("38"));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费") && "MANUAL".equals(fee.getCalcRule())));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费") && decimalFee(fee, "0.09")));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费")
&& fee.getFeeDesc().contains("800公里")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "派送费".equals(band.getChargeName()) && "西班牙(ES)".equals(band.getCountryName())
&& decimal(band, "2.05") && band.getZoneName().contains("马德里")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "派送费".equals(band.getChargeName()) && "葡萄牙(PT)".equals(band.getCountryName())
&& band.getZoneName() != null && band.getZoneName().contains("Mainland")));
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> band.getChargeName() != null && band.getChargeName().contains("偏远")
&& "西班牙(ES)".equals(band.getCountryName()) && band.getZoneName() != null && band.getZoneName().contains("Balearic") && decimal(band, "7.1")));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> "每公斤续重".equals(fee.getFeeName()) && fee.getSectionName() != null
&& fee.getSectionName().contains("偏远") && fee.getZoneName() != null && fee.getZoneName().contains("Canary") && decimalFee(fee, "4.5")));
assertTrue(ctt.getWeightBands().stream().noneMatch(band -> band.getChargeName() != null
&& (band.getChargeName().contains("额外") || band.getChargeName().toLowerCase().contains("line-haul"))));
assertTrue(ctt.getSurcharges().stream().noneMatch(fee -> (fee.getFeeName() != null && (fee.getFeeName().contains("额外线路") || fee.getFeeName().toLowerCase().contains("line-haul")))
|| (fee.getSectionName() != null && (fee.getSectionName().contains("额外线路") || fee.getSectionName().toLowerCase().contains("line-haul")))));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> "超重附加费".equals(fee.getFeeName()) && decimalFee(fee, "5.98")));
}
@@ -588,13 +603,13 @@ class PayWorkbookParserTest
PayOrderCostResult twoKg = PayCostCalculator.calculate(ctt, new java.math.BigDecimal("2"), null, null, null, null,
"Balearic Islands Economy 48H / Majorca", null, 1);
assertEquals(new java.math.BigDecimal("4.24"), twoKg.getPayTotal());
assertEquals(1, twoKg.getFees().stream().filter(fee -> "每公斤续重".equals(fee.getFeeName())
&& fee.getAmount().compareTo(new java.math.BigDecimal("0.85")) == 0).count());
assertTrue(twoKg.getFees().stream().anyMatch(fee -> "基础运费".equals(fee.getFeeName())
&& fee.getAmount().compareTo(new java.math.BigDecimal("4.24")) == 0));
assertTrue(twoKg.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
PayOrderCostResult island = PayCostCalculator.calculate(ctt, new java.math.BigDecimal("2"), null, null, null, null,
"Portuguese Island / Island", null, 1);
assertEquals(new java.math.BigDecimal("12.41"), island.getPayTotal());
assertEquals(1, island.getFees().stream().filter(fee -> "每公斤续重".equals(fee.getFeeName())
&& fee.getAmount().compareTo(new java.math.BigDecimal("3.34")) == 0).count());
assertTrue(island.getFees().stream().noneMatch(fee -> "每公斤续重".equals(fee.getFeeName())));
}
@Test
@@ -29,6 +29,12 @@ public class PayWeightBand
/** 价格列名称,例如英国大陆、马德里高密度 */
private String zoneName;
/** 计费条件类型。POSTCODE 邮编,SIZE 尺寸,WEIGHT 重量。空表示这一档只按分区 */
private String calcRule;
/** 条件参数。邮编如 07 或 35,38;尺寸如 side:80;sum:180 或 box:60*40*30;重量如 30 表示超过 30kg */
private String calcParam;
/** 重量段原文 */
private String weightLabel;
@@ -473,13 +473,43 @@ public final class LabelArCostCalculator
{
return;
}
BigDecimal steps = PaySurchargeRules.extraSteps(fee, weight);
if (steps.compareTo(BigDecimal.ZERO) <= 0)
{
return;
}
BigDecimal over = weight.subtract(threshold);
BigDecimal amount = fee.getAmount().multiply(over).setScale(2, RoundingMode.HALF_UP);
BigDecimal amount = fee.getAmount().multiply(steps).setScale(2, RoundingMode.HALF_UP);
String billed = plain(steps.multiply(PaySurchargeRules.extraStepKg(fee)));
PayCostLine freightLine = freightLine(fees);
if (freightLine != null && "每公斤续重".equals(blank(fee.getFeeName())))
{
freightLine.setAmount(freightLine.getAmount().add(amount).setScale(2, RoundingMode.HALF_UP));
String remark = blank(freightLine.getRemark());
freightLine.setRemark((remark.isEmpty() ? "" : remark + ";") + "续重 " + billed + "kg × " + plain(fee.getAmount()));
return;
}
long scId = fee.getSurchargeId() == null ? 0L : fee.getSurchargeId();
String remark = "超出 " + plain(over) + "kg × " + plain(fee.getAmount()) + " " + blank(fee.getPriceUnit());
String remark = "超出 " + plain(over) + "kg,按 " + billed + "kg × " + plain(fee.getAmount()) + " " + blank(fee.getPriceUnit());
fees.add(line("SURCHARGE", blank(fee.getFeeName()), scId, amount, currency, remark));
}
private static PayCostLine freightLine(List<PayCostLine> fees)
{
if (fees == null)
{
return null;
}
for (PayCostLine row : fees)
{
if (row != null && "BASIC_FREIGHT".equals(row.getFeeType()))
{
return row;
}
}
return null;
}
/** 同一地区有多张服务表时,续重只跟本次首重所在的那一张表。 */
private static boolean sameSection(String feeSection, String freightSection)
{
@@ -128,48 +128,63 @@ public final class PayCostCalculator
result.setMessage(PaymentMesEnum.BMS_PAY_NO_WEIGHT.getCnMes());
return result;
}
List<PayWeightBand> usable = usableBands(product.getWeightBands());
List<PayWeightBand> bands = forZone(usable, zoneName);
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty() && hasZoneFee(product, zoneName))
PayWeightBand remoteHit = conditionBand(product, postcode, countryCode, weight, length, width, height);
PayWeightBand band;
String pricedZone = zoneName;
if (remoteHit != null)
{
bands = deliveryBands(usable, product);
}
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty())
{
result.setMessage("邮编对应的地区「" + zoneName + "」不在价卡重量段里");
return result;
}
Set<String> zones = zones(bands);
if (zones.size() > 1)
{
result.setMessage("产品「" + product.getProductName() + "」有多个地区(" + String.join("、", zones)
+ "),邮编没有对上其中的地区,无法确定运费");
return result;
}
PayWeightBand band = matchBand(bands, weight);
if (band == null)
{
PayWeightBand top = highestBand(bands);
if (top == null || weight.compareTo(top.getWeightMax()) <= 0
|| !hasExtraKg(product, zoneName, top.getWeightMax(), top.getSectionName()))
band = remoteHit;
if (!blank(remoteHit.getZoneName()).isEmpty())
{
result.setMessage(outOfRange(product, bands, weight));
pricedZone = remoteHit.getZoneName();
}
}
else
{
List<PayWeightBand> usable = usableBands(product.getWeightBands());
List<PayWeightBand> bands = forZone(usable, zoneName);
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty()
&& (hasZoneFee(product, zoneName) || hasRemoteWeightBand(product, zoneName)))
{
bands = deliveryBands(usable, product);
}
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty())
{
result.setMessage("邮编对应的地区「" + zoneName + "」不在价卡重量段里");
return result;
}
band = top;
Set<String> zones = zones(bands);
if (zones.size() > 1)
{
result.setMessage("产品「" + product.getProductName() + "」有多个地区(" + String.join("、", zones)
+ "),邮编没有对上其中的地区,无法确定运费");
return result;
}
band = matchBand(bands, weight);
if (band == null)
{
PayWeightBand top = highestBand(bands);
if (top == null || weight.compareTo(top.getWeightMax()) <= 0
|| !hasExtraKg(product, zoneName, top.getWeightMax(), top.getSectionName()))
{
result.setMessage(outOfRange(product, bands, weight));
return result;
}
band = top;
}
}
String currency = currencyOf(product, band);
BigDecimal freight = bandAmount(band, weight);
String freightRemark = band.getWeightLabel() + " " + plain(band.getPrice()) + " " + blank(band.getPriceUnit());
if (zoneName != null && !zoneName.isBlank())
if (pricedZone != null && !pricedZone.isBlank())
{
freightRemark = freightRemark + ",地区 " + zoneName.replace('\n', ' ');
freightRemark = freightRemark + ",地区 " + pricedZone.replace('\n', ' ');
}
PayCostLine freightLine = line("BASIC_FREIGHT", "基础运费", 0L, freight, currency, freightRemark);
result.getFees().add(freightLine);
result.setCurrency(currency);
addZoneFeeBands(result, product, band, weight, postcode, currency);
addSurcharges(product, weight, length, width, height, postcode, zoneName, bizDate, orderStatus, freight, currency,
addZoneFeeBands(result, product, band, weight, postcode, currency, zoneName);
addSurcharges(product, weight, length, width, height, postcode, pricedZone, bizDate, orderStatus, freight, currency,
band.getSectionName(), remoteHits, postcodeOn, zoneOn, countryCode, countryName, result);
BigDecimal total = BigDecimal.ZERO;
for (PayCostLine fee : result.getFees())
@@ -181,6 +196,24 @@ public final class PayCostCalculator
return result;
}
/** 偏远费写在重量段里,和派送费按同一重量行对齐。分区对上时,运费仍用派送档。 */
private static boolean hasRemoteWeightBand(PayProduct product, String zoneName)
{
if (product.getWeightBands() == null || zoneName == null || zoneName.isBlank())
{
return false;
}
for (PayWeightBand band : product.getWeightBands())
{
if (band != null && zoneFeeBand(band) && blank(band.getCalcRule()).isEmpty()
&& PayZoneMatcher.sameZone(band.getZoneName(), zoneName))
{
return true;
}
}
return false;
}
/** 邮编落到偏远分区,而价卡重量段只有大陆派送费时,运费用大陆档。 */
private static boolean hasZoneFee(PayProduct product, String zoneName)
{
@@ -533,13 +566,43 @@ public final class PayCostCalculator
{
return;
}
BigDecimal steps = PaySurchargeRules.extraSteps(fee, weight);
if (steps.compareTo(BigDecimal.ZERO) <= 0)
{
return;
}
BigDecimal over = weight.subtract(threshold);
BigDecimal amount = fee.getAmount().multiply(over).setScale(2, RoundingMode.HALF_UP);
BigDecimal amount = fee.getAmount().multiply(steps).setScale(2, RoundingMode.HALF_UP);
String billed = plain(steps.multiply(PaySurchargeRules.extraStepKg(fee)));
PayCostLine freightLine = freightLine(fees);
if (freightLine != null && "每公斤续重".equals(blank(fee.getFeeName())))
{
freightLine.setAmount(freightLine.getAmount().add(amount).setScale(2, RoundingMode.HALF_UP));
String remark = blank(freightLine.getRemark());
freightLine.setRemark((remark.isEmpty() ? "" : remark + ";") + "续重 " + billed + "kg × " + plain(fee.getAmount()));
return;
}
long scId = feeRef(fee);
String remark = "超出 " + plain(over) + "kg × " + plain(fee.getAmount()) + " " + blank(fee.getPriceUnit());
String remark = "超出 " + plain(over) + "kg,按 " + billed + "kg × " + plain(fee.getAmount()) + " " + blank(fee.getPriceUnit());
fees.add(line("SURCHARGE", blank(fee.getFeeName()), scId, amount, currency, remark));
}
private static PayCostLine freightLine(List<PayCostLine> fees)
{
if (fees == null)
{
return null;
}
for (PayCostLine row : fees)
{
if (row != null && "BASIC_FREIGHT".equals(row.getFeeType()))
{
return row;
}
}
return null;
}
/** 同一地区有多张服务表时,续重只跟本次首重所在的那一张表。 */
private static boolean sameSection(String feeSection, String freightSection)
{
@@ -957,9 +1020,137 @@ public final class PayCostCalculator
return name.contains("偏远") || name.contains("额外") || name.contains("line-haul") || name.contains("linehaul") || name.contains("运输费");
}
/** 和首重同一地区的线路费直接加;带邮编前缀的偏远费按邮编加。超出首重再加该费用自己的续重价。 */
/**
* 重量段写了计费条件时,按条件选用这一档的金额和续重。没写条件的价卡仍按分区计费。
* 邮编取更长前缀,重量取更高门槛,尺寸取排序靠后的一条。不同类型同时命中时,邮编优先于尺寸,尺寸优先于重量。
*/
private static PayWeightBand conditionBand(PayProduct product, String postcode, String countryCode, BigDecimal weight,
BigDecimal length, BigDecimal width, BigDecimal height)
{
if (product.getWeightBands() == null)
{
return null;
}
PayWeightBand best = null;
int bestRank = 0;
int bestPrefix = 0;
BigDecimal bestWeight = null;
int bestIndex = -1;
int index = 0;
for (PayWeightBand band : product.getWeightBands())
{
int rank = conditionRank(band, postcode, countryCode, weight, length, width, height);
if (rank > bestRank)
{
best = band;
bestRank = rank;
bestPrefix = prefixScore(band, postcode);
bestWeight = weightGate(band);
bestIndex = index;
}
else if (rank > 0 && rank == bestRank)
{
if (rank == 3 && prefixScore(band, postcode) > bestPrefix)
{
best = band;
bestPrefix = prefixScore(band, postcode);
bestIndex = index;
}
else if (rank == 1)
{
BigDecimal gate = weightGate(band);
if (gate != null && (bestWeight == null || gate.compareTo(bestWeight) > 0))
{
best = band;
bestWeight = gate;
bestIndex = index;
}
}
else if (rank == 2 && index > bestIndex)
{
best = band;
bestIndex = index;
}
}
index++;
}
return best;
}
/** 邮编 3,尺寸 2,重量 1。没有命中返回 0。 */
private static int conditionRank(PayWeightBand band, String postcode, String countryCode, BigDecimal weight,
BigDecimal length, BigDecimal width, BigDecimal height)
{
if (band == null || band.getPrice() == null || !countryFits(band.getCountryCode(), countryCode))
{
return 0;
}
String rule = blank(band.getCalcRule()).toUpperCase(Locale.ROOT);
String param = blank(band.getCalcParam());
if (rule.isEmpty() || param.isEmpty())
{
return 0;
}
if (PaySurchargeRules.POSTCODE.equals(rule) && PaySurchargeRules.matchesPostcode(param, postcode))
{
return 3;
}
if (PaySurchargeRules.SIZE.equals(rule) && PaySurchargeRules.matchesSize(param, length, width, height))
{
return 2;
}
if (PaySurchargeRules.WEIGHT.equals(rule) && PaySurchargeRules.matchesWeight(param, weight))
{
return 1;
}
return 0;
}
private static int prefixScore(PayWeightBand band, String postcode)
{
int length = prefixLength(blank(band.getCalcParam()), postcode);
return length == 0 ? 1 : length;
}
private static BigDecimal weightGate(PayWeightBand band)
{
try
{
return new BigDecimal(blank(band.getCalcParam()).trim());
}
catch (NumberFormatException ex)
{
return null;
}
}
private static boolean countryFits(String bandCountry, String orderCountry)
{
if (bandCountry == null || bandCountry.isBlank() || orderCountry == null || orderCountry.isBlank())
{
return true;
}
return bandCountry.trim().equalsIgnoreCase(orderCountry.trim());
}
private static int prefixLength(String prefixes, String postcode)
{
String digits = postcode.replaceAll("\\D", "");
int best = 0;
for (String token : prefixes.split(","))
{
String value = token.trim();
if (value.matches("\\d{1,5}") && !digits.isEmpty() && digits.startsWith(value) && value.length() > best)
{
best = value.length();
}
}
return best;
}
/** 没有邮编条件的分区费用仍按地区加在已选运费上。写了邮编条件的档已经当作运费本身。 */
private static void addZoneFeeBands(PayOrderCostResult result, PayProduct product, PayWeightBand freight, BigDecimal weight,
String postcode, String currency)
String postcode, String currency, String orderZone)
{
if (product.getWeightBands() == null || freight == null)
{
@@ -967,7 +1158,8 @@ public final class PayCostCalculator
}
for (PayWeightBand band : product.getWeightBands())
{
if (band == null || band.getPrice() == null || !zoneFeeBand(band) || !zoneFeeHits(band, freight, postcode))
if (band == null || band.getPrice() == null || !zoneFeeBand(band) || !blank(band.getCalcRule()).isEmpty()
|| !sameWeightRow(band, freight) || !zoneFeeHits(band, freight, postcode, orderZone))
{
continue;
}
@@ -979,13 +1171,29 @@ public final class PayCostCalculator
}
}
private static boolean zoneFeeHits(PayWeightBand band, PayWeightBand freight, String postcode)
/** 偏远行和本次派送费是同一重量段,才按这一行加价。 */
private static boolean sameWeightRow(PayWeightBand band, PayWeightBand freight)
{
if (band.getWeightMin() == null || band.getWeightMax() == null || freight.getWeightMin() == null || freight.getWeightMax() == null)
{
return true;
}
return band.getWeightMin().compareTo(freight.getWeightMin()) == 0
&& band.getWeightMax().compareTo(freight.getWeightMax()) == 0;
}
private static boolean zoneFeeHits(PayWeightBand band, PayWeightBand freight, String postcode, String orderZone)
{
String prefixes = PaySurchargeRules.remotePrefixes(band.getZoneName());
if (!prefixes.isEmpty())
{
return PaySurchargeRules.matchesPostcode(prefixes, postcode);
}
String label = blank(band.getChargeName()) + " " + blank(band.getSectionName());
if (label.contains("偏远"))
{
return orderZone != null && !orderZone.isBlank() && PayZoneMatcher.sameZone(band.getZoneName(), orderZone);
}
return PayZoneMatcher.sameZone(band.getZoneName(), freight.getZoneName());
}
@@ -1010,11 +1218,17 @@ public final class PayCostCalculator
{
continue;
}
BigDecimal steps = PaySurchargeRules.extraSteps(fee, weight);
if (steps.compareTo(BigDecimal.ZERO) <= 0)
{
return;
}
BigDecimal over = weight.subtract(band.getWeightMax());
BigDecimal amount = fee.getAmount().multiply(over).setScale(2, RoundingMode.HALF_UP);
BigDecimal amount = fee.getAmount().multiply(steps).setScale(2, RoundingMode.HALF_UP);
long scId = feeRef(fee);
result.getFees().add(line("SURCHARGE", name, scId, amount, currency,
"超出 " + plain(over) + "kg × " + plain(fee.getAmount()) + " " + blank(fee.getPriceUnit())));
"超出 " + plain(over) + "kg,按 " + plain(steps.multiply(PaySurchargeRules.extraStepKg(fee))) + "kg × "
+ plain(fee.getAmount()) + " " + blank(fee.getPriceUnit())));
return;
}
}
@@ -1028,7 +1242,8 @@ public final class PayCostCalculator
}
for (PayWeightBand band : bands)
{
if (band != null && band.getPrice() != null && band.getWeightMin() != null && band.getWeightMax() != null && !zoneFeeBand(band))
if (band != null && band.getPrice() != null && band.getWeightMin() != null && band.getWeightMax() != null
&& !zoneFeeBand(band) && blank(band.getCalcRule()).isEmpty())
{
usable.add(band);
}
@@ -54,6 +54,8 @@ public final class PaySurchargeRules
private static final Pattern KG = Pattern.compile("(?i)(\\d+(?:\\.\\d+)?)\\s*(?:kg|公斤|千克)");
private static final Pattern EXTRA_STEP = Pattern.compile("(?i)(?:每增加|每超过|每超出)\\s*(\\d+(?:\\.\\d+)?)\\s*(?:kg|公斤|千克)");
private PaySurchargeRules()
{
}
@@ -660,6 +662,45 @@ public final class PaySurchargeRules
}
}
/** 续重计费步长。价卡写了每增加若干公斤时用该步长,否则按 1kg。 */
public static BigDecimal extraStepKg(PaySurcharge fee)
{
if (fee != null)
{
String blob = (fee.getChargeText() == null ? "" : fee.getChargeText()) + " "
+ (fee.getFeeDesc() == null ? "" : fee.getFeeDesc());
Matcher matcher = EXTRA_STEP.matcher(blob);
if (matcher.find())
{
try
{
BigDecimal step = new BigDecimal(matcher.group(1));
if (step.compareTo(BigDecimal.ZERO) > 0)
{
return step;
}
}
catch (NumberFormatException ex)
{
return BigDecimal.ONE;
}
}
}
return BigDecimal.ONE;
}
/** 超出起重后的续重档数。不足一个计重单位也按一整档收取。 */
public static BigDecimal extraSteps(PaySurcharge fee, BigDecimal weight)
{
BigDecimal threshold = extraStartKg(fee);
if (threshold == null || weight == null || weight.compareTo(threshold) <= 0)
{
return BigDecimal.ZERO;
}
BigDecimal step = extraStepKg(fee);
return weight.subtract(threshold).divide(step, 0, RoundingMode.CEILING);
}
/** 命中邮编。独立字段优先,其次是原来的邮编列和导入文本。 */
public static String feePostcodes(PaySurcharge fee)
{
@@ -428,6 +428,8 @@ public class PayWorkbookParser
copy.setCountryName(band.getCountryName());
copy.setCountryCode(band.getCountryCode());
copy.setZoneName(band.getZoneName());
copy.setCalcRule(band.getCalcRule());
copy.setCalcParam(band.getCalcParam());
copy.setWeightLabel(band.getWeightLabel());
copy.setWeightMin(band.getWeightMin());
copy.setWeightMax(band.getWeightMax());
@@ -1151,7 +1153,7 @@ public class PayWorkbookParser
}
if (isFeeRateHeader(grid, row))
{
row = readFeeRateTable(grid, row, product);
row = isLineHaulHeader(grid, row) ? skipRateTable(grid, row) : readFeeRateTable(grid, row, product);
pending = "";
continue;
}
@@ -1239,7 +1241,7 @@ public class PayWorkbookParser
private int readFeeRateTable(ExcelGrid grid, int header, PayProduct product)
{
int data = header + 1;
int subHeader = -1;
List<Integer> labelRows = new ArrayList<>();
while (data < grid.rows() && !grid.blankRow(data) && !isHardHeader(grid, data))
{
if (countNumbers(grid, data) > 0 || rowHasWeight(grid, data))
@@ -1248,17 +1250,20 @@ public class PayWorkbookParser
}
if (countText(grid, data) >= 2)
{
subHeader = data;
labelRows.add(data);
}
data++;
}
int[] heads = countryAndZoneRows(grid, labelRows);
int countryRow = heads[0];
int zoneRow = heads[1];
int[] kind = new int[grid.cols()];
String[] parent = new String[grid.cols()];
String[] sub = new String[grid.cols()];
String carry = "";
for (int col = 0; col < grid.cols(); col++)
{
if (strayColumn(grid, header, col, subHeader))
if (strayColumn(grid, header, col, zoneRow))
{
parent[col] = "";
sub[col] = "";
@@ -1275,7 +1280,7 @@ public class PayWorkbookParser
head = carry;
}
parent[col] = head;
sub[col] = subHeader < 0 ? "" : grid.text(subHeader, col);
sub[col] = zoneRow < 0 ? "" : spanned(grid, zoneRow, col);
kind[col] = columnKind(head, numericBelow(grid, col, data));
}
int added = product.getSurcharges().size();
@@ -1324,13 +1329,16 @@ public class PayWorkbookParser
String zone = zoneOf(sub[col], parent[col]).replace('\n', ' ').replaceAll("\\s+", " ").trim();
if (zoneFeeName(feeName))
{
String grouped = countryRow < 0 ? "" : countryAt(grid, countryRow, col);
String prefixes = PaySurchargeRules.remotePrefixes(zone);
String place = prefixes.isEmpty() ? zone : zoneWithoutPostcode(zone);
if (stepWeight(weight))
{
addExtraKg(product, feeName, zone, weight, price, firstLimit(product, feeName, zone));
addExtraKg(product, feeName, place, weight, price, firstLimit(product, feeName, place));
}
else
{
addZoneFeeBand(product, feeName, zone, weight, price, parent[col]);
addZoneFeeBand(product, feeName, place, weight, price, parent[col], countryLabel(grouped), countryCodeOf(grouped), prefixes);
}
continue;
}
@@ -1378,8 +1386,8 @@ public class PayWorkbookParser
private int readPriceTable(ExcelGrid grid, int header, String pending, PayProduct product, StringBuilder note)
{
int data = header + 1;
int subHeader = -1;
String section = cleanTitle(pending);
List<Integer> labelRows = new ArrayList<>();
while (data < grid.rows() && !grid.blankRow(data) && !isHardHeader(grid, data))
{
if (countNumbers(grid, data) > 0 || rowHasWeight(grid, data))
@@ -1388,7 +1396,7 @@ public class PayWorkbookParser
}
if (countText(grid, data) >= 2)
{
subHeader = data;
labelRows.add(data);
}
else if (section.isEmpty())
{
@@ -1396,13 +1404,16 @@ public class PayWorkbookParser
}
data++;
}
int[] heads = countryAndZoneRows(grid, labelRows);
int countryRow = heads[0];
int zoneRow = heads[1];
int[] kind = new int[grid.cols()];
String[] parent = new String[grid.cols()];
String[] sub = new String[grid.cols()];
String carry = "";
for (int col = 0; col < grid.cols(); col++)
{
if (strayColumn(grid, header, col, subHeader))
if (strayColumn(grid, header, col, zoneRow))
{
parent[col] = "";
sub[col] = "";
@@ -1419,7 +1430,7 @@ public class PayWorkbookParser
head = carry;
}
parent[col] = head;
sub[col] = subHeader < 0 ? "" : grid.text(subHeader, col);
sub[col] = zoneRow < 0 ? "" : spanned(grid, zoneRow, col);
kind[col] = columnKind(head, numericBelow(grid, col, data));
}
if (section.isEmpty())
@@ -1507,7 +1518,27 @@ public class PayWorkbookParser
priced = true;
if (isSurchargePriceHead(parent[col]))
{
addPricedSurcharge(product, blankTo(section, "价格"), parent[col], zoneOf(sub[col], parent[col]), weight, price);
String feeName = chargeTitle(parent[col]);
if (zoneFeeName(feeName))
{
String remoteCountry = country;
String remoteCode = countryCode;
if (countryRow >= 0)
{
String grouped = countryAt(grid, countryRow, col);
if (!grouped.isBlank())
{
remoteCountry = countryLabel(grouped);
remoteCode = countryCodeOf(grouped);
}
}
addZoneFeeBand(product, feeName, zoneOf(sub[col], parent[col]), weight, price, parent[col],
remoteCountry, remoteCode, "");
}
else
{
addPricedSurcharge(product, blankTo(section, "价格"), parent[col], zoneOf(sub[col], parent[col]), weight, price);
}
continue;
}
boolean feeHead = isPriceHead(parent[col]);
@@ -1518,10 +1549,21 @@ public class PayWorkbookParser
addExtraKg(product, sectionName, zone, weight, price, firstLimit(product, sectionName, zone));
continue;
}
String bandCountry = country;
String bandCode = countryCode;
if (countryRow >= 0)
{
String grouped = countryAt(grid, countryRow, col);
if (!grouped.isBlank())
{
bandCountry = countryLabel(grouped);
bandCode = countryCodeOf(grouped);
}
}
PayWeightBand band = new PayWeightBand();
band.setSectionName(blankTo(section, "价格"));
band.setCountryName(country);
band.setCountryCode(countryCode);
band.setCountryName(bandCountry);
band.setCountryCode(bandCode);
band.setWeightLabel(weight);
BigDecimal[] bounds = PayTexts.weightBounds(weight);
band.setWeightMin(bounds[0]);
@@ -2159,12 +2201,32 @@ public class PayWorkbookParser
product.getSurcharges().add(fee);
}
/** 偏远附加费、额外线路运输费的首重,作为重量段里的费用项。 */
private static void addZoneFeeBand(PayProduct product, String feeName, String zone, String weight, BigDecimal price, String head)
/** 分区里的“07邮编开头”“35、38邮编开头”拆出去,地区名单独留下。 */
private static String zoneWithoutPostcode(String zone)
{
if (zone == null || zone.isBlank())
{
return zone;
}
String cleaned = zone.replaceAll("\\d+(?:[、,,\\s]+\\d+)*\\s*邮编开头", "");
cleaned = cleaned.replaceAll("\\s+", " ").trim();
return cleaned.isEmpty() ? zone : cleaned;
}
/** 偏远附加费的首重记进重量段。邮编写成计费条件,分区只留地区名。 */
private static void addZoneFeeBand(PayProduct product, String feeName, String zone, String weight, BigDecimal price, String head,
String country, String countryCode, String postcodeParam)
{
PayWeightBand band = new PayWeightBand();
band.setSectionName(feeName);
band.setCountryName(country == null || country.isBlank() ? null : country);
band.setCountryCode(countryCode == null || countryCode.isBlank() ? null : countryCode);
band.setZoneName(zone);
if (postcodeParam != null && !postcodeParam.isBlank())
{
band.setCalcRule(PaySurchargeRules.POSTCODE);
band.setCalcParam(postcodeParam);
}
band.setWeightLabel(weight);
BigDecimal[] bounds = PayTexts.weightBounds(weight);
band.setWeightMin(bounds[0]);
@@ -2204,15 +2266,184 @@ public class PayWorkbookParser
return compact.contains("每增加") || compact.contains("additionalkg") || compact.contains("kg.ad");
}
/** 偏远、额外线路这类和首重同表的费用,要进重量段。超重、超尺寸仍走附加费。 */
/** 偏远附加费进重量段。额外线路运输费先不解析。超重、超尺寸仍走附加费。 */
private static boolean zoneFeeName(String name)
{
if (name == null)
return name != null && name.contains("偏远");
}
/** 表头下先是国家、再是分区时两行都认。只有一行时当作分区。 */
private static int[] countryAndZoneRows(ExcelGrid grid, List<Integer> labelRows)
{
int country = -1;
int zone = labelRows == null || labelRows.isEmpty() ? -1 : labelRows.get(labelRows.size() - 1);
if (labelRows != null && labelRows.size() >= 2 && countryGroupRow(grid, labelRows.get(0)))
{
return false;
country = labelRows.get(0);
}
String text = name.toLowerCase(Locale.ROOT);
return text.contains("偏远") || text.contains("额外") || text.contains("line-haul") || text.contains("linehaul") || text.contains("运输费");
return new int[] { country, zone };
}
private static boolean countryGroupRow(ExcelGrid grid, int row)
{
int countries = 0;
for (int col = 0; col < grid.cols(); col++)
{
String text = spanned(grid, row, col);
if (text.isBlank())
{
continue;
}
if (zoneMarker(text))
{
return false;
}
if (countryWord(text))
{
countries++;
}
}
return countries >= 1;
}
private static boolean countryWord(String text)
{
String lower = text.toLowerCase(Locale.ROOT);
return text.contains("西班牙") || text.contains("葡萄牙") || text.contains("英国") || text.contains("法国")
|| text.contains("德国") || text.contains("意大利") || text.contains("荷兰")
|| lower.contains("spain") || lower.contains("portugal");
}
private static boolean zoneMarker(String text)
{
String lower = text.toLowerCase(Locale.ROOT);
return text.contains("地区") || text.contains("邮编") || text.contains("密度")
|| lower.contains("density") || lower.contains("island") || lower.contains("mainland");
}
private static String countryLabel(String country)
{
if (country == null || country.isBlank())
{
return country;
}
String code = countryCodeOf(country);
if (code.isEmpty() || country.contains("("))
{
return country;
}
return country + "(" + code + ")";
}
private static String countryCodeOf(String country)
{
if (country == null || country.isBlank())
{
return "";
}
if (country.contains("西班牙") || country.toLowerCase(Locale.ROOT).contains("spain"))
{
return "ES";
}
if (country.contains("葡萄牙") || country.toLowerCase(Locale.ROOT).contains("portugal"))
{
return "PT";
}
if (country.contains("英国"))
{
return "GB";
}
if (country.contains("法国"))
{
return "FR";
}
if (country.contains("德国"))
{
return "DE";
}
if (country.contains("意大利"))
{
return "IT";
}
if (country.contains("荷兰"))
{
return "NL";
}
return "";
}
/** 国家表头按列向左找到这一列所属国家。合并格和只写在左上角的国家都能认到。 */
private static String countryAt(ExcelGrid grid, int row, int col)
{
if (row < 0)
{
return "";
}
String own = spanned(grid, row, col);
if (!own.isBlank())
{
return own;
}
for (int left = col - 1; left >= 0; left--)
{
String text = spanned(grid, row, left);
if (text.isBlank())
{
continue;
}
return countryWord(text) ? text : "";
}
return "";
}
/** 合并单元格只在左上角有字,右侧列沿用这一格。 */
private static String spanned(ExcelGrid grid, int row, int col)
{
String text = grid.text(row, col).replace('\n', ' ').replaceAll("\\s+", " ").trim();
if (!text.isBlank())
{
return text;
}
for (int left = col - 1; left >= 0; left--)
{
if (grid.colSpan(row, left) > 1 && left + grid.colSpan(row, left) - 1 >= col)
{
return grid.text(row, left).replace('\n', ' ').replaceAll("\\s+", " ").trim();
}
}
return "";
}
private static boolean isLineHaulHeader(ExcelGrid grid, int row)
{
for (int col = 0; col < grid.cols(); col++)
{
String text = grid.text(row, col).toLowerCase(Locale.ROOT);
if (text.contains("line-haul") || text.contains("linehaul") || text.contains("额外线路") || text.contains("额外路线"))
{
return true;
}
}
return false;
}
/** 额外线路运输费整表跳过,留到下一块表头。 */
private int skipRateTable(ExcelGrid grid, int header)
{
int data = header + 1;
while (data < grid.rows() && !grid.blankRow(data) && !isHardHeader(grid, data))
{
if (countNumbers(grid, data) > 0 || rowHasWeight(grid, data))
{
break;
}
data++;
}
while (data < grid.rows() && !grid.blankRow(data) && !isHardHeader(grid, data))
{
data++;
}
return data;
}
private static boolean sameSectionText(String left, String right)
@@ -4384,7 +4615,7 @@ public class PayWorkbookParser
}
}
/** 价格表里和派送费并排的偏远列,按分区和重量区间记附加费,不进重量段。 */
/** 价格表里和派送费并排、又不是偏远的费用列,按分区和重量区间记附加费。偏远列记进重量段。 */
private void addPricedSurcharge(PayProduct product, String section, String head, String zone, String weight, BigDecimal price)
{
String feeName = shortCharge(head);
@@ -2188,6 +2188,8 @@ public class PayProductServiceImpl implements IPayProductService
band.setCountryName(cut(band.getCountryName(), 200));
band.setCountryCode(cut(band.getCountryCode(), 32));
band.setZoneName(cut(band.getZoneName(), 200));
band.setCalcRule(cut(band.getCalcRule(), 32));
band.setCalcParam(cut(band.getCalcParam(), 1000));
band.setWeightLabel(cut(band.getWeightLabel(), 100));
band.setVolumeText(cut(band.getVolumeText(), 40));
band.setChargeName(cut(band.getChargeName(), 200));
@@ -109,6 +109,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and (b.weight_label like concat('%', #{weightKeyword}, '%')
or b.charge_name like concat('%', #{weightKeyword}, '%')
or b.zone_name like concat('%', #{weightKeyword}, '%')
or b.calc_param like concat('%', #{weightKeyword}, '%')
or b.country_name like concat('%', #{weightKeyword}, '%')
or b.section_name like concat('%', #{weightKeyword}, '%')
or b.volume_text like concat('%', #{weightKeyword}, '%'))
@@ -320,12 +321,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertWeightBands">
insert into pay_weight_band (
product_id, term_id, version_no, section_name, country_name, country_code, zone_name, weight_label, weight_min, weight_max,
product_id, term_id, version_no, section_name, country_name, country_code, zone_name, calc_rule, calc_param, weight_label, weight_min, weight_max,
volume_text, charge_name, price, price_unit, sort_no
) values
<foreach collection="list" item="row" separator=",">
(#{row.productId}, #{row.termId}, ifnull(#{row.versionNo}, 1), #{row.sectionName}, #{row.countryName}, #{row.countryCode}, #{row.zoneName},
#{row.weightLabel}, #{row.weightMin}, #{row.weightMax}, #{row.volumeText}, #{row.chargeName}, #{row.price},
#{row.calcRule}, #{row.calcParam}, #{row.weightLabel}, #{row.weightMin}, #{row.weightMax}, #{row.volumeText}, #{row.chargeName}, #{row.price},
#{row.priceUnit}, #{row.sortNo})
</foreach>
</insert>
@@ -352,7 +353,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectWeightBands" resultType="com.bms.price.domain.PayWeightBand">
select band_id as bandId, product_id as productId, term_id as termId, version_no as versionNo, section_name as sectionName, country_name as countryName,
country_code as countryCode, zone_name as zoneName, weight_label as weightLabel, weight_min as weightMin,
country_code as countryCode, zone_name as zoneName, calc_rule as calcRule, calc_param as calcParam, weight_label as weightLabel, weight_min as weightMin,
weight_max as weightMax, volume_text as volumeText, charge_name as chargeName, price, price_unit as priceUnit, sort_no as sortNo
from pay_weight_band
where product_id in
@@ -362,7 +363,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectWeightBandsByTerm" resultType="com.bms.price.domain.PayWeightBand">
select band_id as bandId, product_id as productId, term_id as termId, version_no as versionNo, section_name as sectionName, country_name as countryName,
country_code as countryCode, zone_name as zoneName, weight_label as weightLabel, weight_min as weightMin,
country_code as countryCode, zone_name as zoneName, calc_rule as calcRule, calc_param as calcParam, weight_label as weightLabel, weight_min as weightMin,
weight_max as weightMax, volume_text as volumeText, charge_name as chargeName, price, price_unit as priceUnit, sort_no as sortNo
from pay_weight_band
where term_id in
@@ -0,0 +1,8 @@
-- `pay_weight_band` 表中添加`calc_rule` 属性
ALTER TABLE `bms`.`pay_weight_band` ADD COLUMN `calc_rule` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '计费条件类型:POSTCODE邮编、SIZE尺寸、WEIGHT重量。空表示按分区计费' AFTER `zone_name`;
-- `pay_weight_band` 表中添加`calc_param` 属性
ALTER TABLE `bms`.`pay_weight_band` ADD COLUMN `calc_param` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '计费条件参数。邮编如07或35,38;尺寸如side:80;sum:180或box:60*40*30;重量如30表示超过30kg' AFTER `calc_rule`;
-- 原邮编条件改为通用计费条件
UPDATE `bms`.`pay_weight_band` SET `calc_rule` = 'POSTCODE', `calc_param` = `postcode_param` WHERE `postcode_param` IS NOT NULL AND TRIM(`postcode_param`) <> '';
-- `pay_weight_band` 去掉只表示邮编的字段
ALTER TABLE `bms`.`pay_weight_band` DROP COLUMN `postcode_param`;
@@ -0,0 +1,18 @@
-- `pay_weight_band` 表中添加`postcode_param` 属性
ALTER TABLE `bms`.`pay_weight_band` ADD COLUMN `postcode_param` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '邮编条件,如07或35,38。有值时按邮编选用这一档金额和续重' AFTER `zone_name`;
-- 巴利阿里偏远档的邮编条件从分区拆出
UPDATE `bms`.`pay_weight_band` SET `postcode_param` = '07', `zone_name` = TRIM(REPLACE(`zone_name`, '07邮编开头', '')) WHERE `zone_name` LIKE '%07邮编开头%';
-- 加那利偏远档的邮编条件从分区拆出
UPDATE `bms`.`pay_weight_band` SET `postcode_param` = '35,38', `zone_name` = TRIM(REPLACE(`zone_name`, '35、38邮编开头', '')) WHERE `zone_name` LIKE '%35、38邮编开头%';
-- 休达和梅利利亚偏远档的邮编条件从分区拆出
UPDATE `bms`.`pay_weight_band` SET `postcode_param` = '51,52', `zone_name` = TRIM(REPLACE(`zone_name`, '51、52邮编开头', '')) WHERE `zone_name` LIKE '%51、52邮编开头%';
-- 葡萄牙岛屿偏远档的邮编条件从分区拆出
UPDATE `bms`.`pay_weight_band` SET `postcode_param` = '9', `zone_name` = TRIM(REPLACE(`zone_name`, '9邮编开头', '')) WHERE `zone_name` LIKE '%9邮编开头%';
-- 巴利阿里续重分区去掉邮编字样
UPDATE `bms`.`pay_surcharge` SET `zone_name` = TRIM(REPLACE(`zone_name`, '07邮编开头', '')) WHERE `zone_name` LIKE '%07邮编开头%';
-- 加那利续重分区去掉邮编字样
UPDATE `bms`.`pay_surcharge` SET `zone_name` = TRIM(REPLACE(`zone_name`, '35、38邮编开头', '')) WHERE `zone_name` LIKE '%35、38邮编开头%';
-- 休达和梅利利亚续重分区去掉邮编字样
UPDATE `bms`.`pay_surcharge` SET `zone_name` = TRIM(REPLACE(`zone_name`, '51、52邮编开头', '')) WHERE `zone_name` LIKE '%51、52邮编开头%';
-- 葡萄牙岛屿续重分区去掉邮编字样
UPDATE `bms`.`pay_surcharge` SET `zone_name` = TRIM(REPLACE(`zone_name`, '9邮编开头', '')) WHERE `zone_name` LIKE '%9邮编开头%';
@@ -36,6 +36,19 @@
<el-table-column prop="zoneName" label="分区" min-width="140" show-overflow-tooltip>
<template #default="{ row }"><cell-text v-model="row.zoneName" :edit="isRowEditing(row)" /></template>
</el-table-column>
<el-table-column prop="calcRule" label="计费条件" width="110" align="center">
<template #default="{ row }">
<el-select v-if="isRowEditing(row)" v-model="row.calcRule" clearable size="small" placeholder="不限">
<el-option label="邮编" value="POSTCODE" />
<el-option label="尺寸" value="SIZE" />
<el-option label="重量" value="WEIGHT" />
</el-select>
<span v-else>{{ bandRuleLabel(row.calcRule) }}</span>
</template>
</el-table-column>
<el-table-column prop="calcParam" label="条件参数" min-width="150" show-overflow-tooltip>
<template #default="{ row }"><cell-text v-model="row.calcParam" :edit="isRowEditing(row)" /></template>
</el-table-column>
<el-table-column prop="weightLabel" label="重量段" min-width="120" show-overflow-tooltip>
<template #default="{ row }"><cell-text v-model="row.weightLabel" :edit="isRowEditing(row)" /></template>
</el-table-column>
@@ -539,7 +552,7 @@ watch(source, (list) => {
}, { immediate: true })
function filteredBands(pane) {
return filterRows(pane.item.weightBands || [], pane.bandKeyword, ['sectionName', 'countryName', 'countryCode', 'zoneName', 'weightLabel', 'chargeName', 'priceUnit'])
return filterRows(pane.item.weightBands || [], pane.bandKeyword, ['sectionName', 'countryName', 'countryCode', 'zoneName', 'calcRule', 'calcParam', 'weightLabel', 'chargeName', 'priceUnit'])
}
function filteredFees(pane) {
@@ -718,6 +731,14 @@ function filterRows(rows, keyword, fields) {
return rows.filter(row => fields.some(field => String(row?.[field] ?? '').toLowerCase().includes(text)))
}
function bandRuleLabel(rule) {
const value = String(rule || '').toUpperCase()
if (value === 'POSTCODE') return '邮编'
if (value === 'SIZE') return '尺寸'
if (value === 'WEIGHT') return '重量'
return ''
}
function pageOf(rows, pageNo) {
const start = (pageNo - 1) * pageSize
return rows.slice(start, start + pageSize)
@@ -66,6 +66,18 @@
<el-table-column label="分区" min-width="120">
<template #default="{ row }"><el-input v-model="row.zoneName" size="small" placeholder="不分区可空" /></template>
</el-table-column>
<el-table-column label="计费条件" width="110">
<template #default="{ row }">
<el-select v-model="row.calcRule" clearable size="small" placeholder="不限">
<el-option label="邮编" value="POSTCODE" />
<el-option label="尺寸" value="SIZE" />
<el-option label="重量" value="WEIGHT" />
</el-select>
</template>
</el-table-column>
<el-table-column label="条件参数" min-width="160">
<template #default="{ row }"><el-input v-model="row.calcParam" size="small" placeholder="07 / side:80 / 30" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType !== 'EXTRA'" label="重量下限KG" width="120">
<template #default="{ row }"><el-input v-model="row.weightMin" size="small" /></template>
</el-table-column>
@@ -186,7 +198,7 @@ function onMode() {
}
function blankRow() {
return { countryName: '', countryCode: '', zoneName: '', weightMin: '0', weightMax: '', price: '', extraPrice: '' }
return { countryName: '', countryCode: '', zoneName: '', calcRule: '', calcParam: '', weightMin: '0', weightMax: '', price: '', extraPrice: '' }
}
function addRow() {
@@ -235,6 +247,8 @@ async function submit() {
countryName: row.countryName,
countryCode: row.countryCode,
zoneName: row.zoneName,
calcRule: row.calcRule,
calcParam: row.calcParam,
weightMin: 0,
weightMax: firstKg,
price
@@ -253,6 +267,8 @@ async function submit() {
countryName: row.countryName,
countryCode: row.countryCode,
zoneName: row.zoneName,
calcRule: row.calcRule,
calcParam: row.calcParam,
weightMin: min,
weightMax: max,
price