调整应付配置和应付列表订单的费用重算

This commit is contained in:
liuminghui
2026-11-17 17:47:01 +08:00
parent 9483bb4899
commit 6b2b205083
45 changed files with 1448 additions and 2131 deletions
@@ -1,6 +1,7 @@
package com.bms.price.airbill.domain;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
/** 待分摊的一条提单费用,供费用处理弹框展示。 */
@@ -29,6 +30,9 @@ public class SrvBillAirAllocFee
private String currency;
/** 费用录入时间,用来取汇率 */
private Date createTime;
/** 分摊维度:1订单 2重量 */
private String allocDim;
@@ -61,7 +61,7 @@ public class PayProduct extends BaseEntity
@Excel(name = "国家/口岸", width = 18)
private String countryScope;
/** 字典 order_charge_type:续重计费、单票价、常规计重价 */
/** 字典 order_charge_type:PER_KG 常规计费、FLAT 一口价、EXTRA 续重价 */
@Excel(name = "费用类型", width = 14)
private String chargeType;
@@ -1,118 +0,0 @@
package com.bms.price.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
/** 应付附加费配置在某一产品版本上的操作记录。 */
public class PaySurchargeRuleLog
{
private Long logId;
private Long productId;
private Long termId;
private Integer versionNo;
/** 1新增 2修改 3删除 */
private String operationType;
private String ruleKey;
private String changeContent;
private String createBy;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
public Long getLogId()
{
return logId;
}
public void setLogId(Long logId)
{
this.logId = logId;
}
public Long getProductId()
{
return productId;
}
public void setProductId(Long productId)
{
this.productId = productId;
}
public Long getTermId()
{
return termId;
}
public void setTermId(Long termId)
{
this.termId = termId;
}
public Integer getVersionNo()
{
return versionNo;
}
public void setVersionNo(Integer versionNo)
{
this.versionNo = versionNo;
}
public String getOperationType()
{
return operationType;
}
public void setOperationType(String operationType)
{
this.operationType = operationType;
}
public String getRuleKey()
{
return ruleKey;
}
public void setRuleKey(String ruleKey)
{
this.ruleKey = ruleKey;
}
public String getChangeContent()
{
return changeContent;
}
public void setChangeContent(String changeContent)
{
this.changeContent = changeContent;
}
public String getCreateBy()
{
return createBy;
}
public void setCreateBy(String createBy)
{
this.createBy = createBy;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
}
@@ -1,28 +0,0 @@
package com.bms.price.domain;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
/**
* 把同一套计费条件写到若干产品的当前版本。每个版本只保留这一份。
*/
@Data
public class PaySurchargeRuleSave
{
private List<PaySurchargeRuleBind> products = new ArrayList<>();
private List<PaySurchargeRule> rules = new ArrayList<>();
@Data
public static class PaySurchargeRuleBind
{
private Long productId;
private Long termId;
private Integer versionNo;
private String productName;
}
}
@@ -23,6 +23,8 @@ public class TmsPriceQuoteFeeLine implements Serializable
private String currency;
private String roundMode;
private String remark;
/** CALC 计算,LADING 提单分摊,MANUAL 手工 */
private String feeSource;
/** UNBILLED / BILLED */
private String arBillStatus;
/** 0=系统 1=人工 */
@@ -1,14 +0,0 @@
package com.bms.price.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.PaySurchargeRuleLog;
public interface PaySurchargeRuleLogMapper
{
List<PaySurchargeRuleLog> selectByTerm(@Param("productId") Long productId, @Param("termId") Long termId);
List<PaySurchargeRuleLog> selectByProductIds(@Param("productIds") List<Long> productIds);
int insertBatch(@Param("list") List<PaySurchargeRuleLog> list);
}
@@ -1,19 +0,0 @@
package com.bms.price.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.PaySurchargeRule;
/** 应付附加费计费条件。一份跟产品走。 */
public interface PaySurchargeRuleMapper
{
List<PaySurchargeRule> selectByProduct(@Param("productId") Long productId, @Param("termId") Long termId);
List<PaySurchargeRule> selectByProductId(@Param("productId") Long productId);
int deleteByTerm(@Param("productId") Long productId, @Param("termId") Long termId);
int deleteByProductIds(@Param("productIds") List<Long> productIds);
int insertBatch(@Param("list") List<PaySurchargeRule> rules);
}
@@ -0,0 +1,76 @@
package com.bms.price.pay;
/**
* 应付价卡的三种计费模式,对应字典 order_charge_type 的键值。
*/
public final class PayChargeMode
{
private PayChargeMode()
{
}
/** 单价乘以公斤重 */
public static final String PER_KG = "PER_KG";
/** 重量段内按票收取固定金额 */
public static final String FLAT = "FLAT";
/** 首重一口价,超出部分按每公斤续重 */
public static final String EXTRA = "EXTRA";
/**
* 把字典键、中文名和历史名称收成这三种键值。认不出时返回空字符串。
*
* @param raw 页面或库里的计费模式
* @return PER_KG、FLAT、EXTRA 之一,空表示不是这三种
*/
public static String code(String raw)
{
if (raw == null)
{
return "";
}
String text = raw.trim();
if (text.isEmpty())
{
return "";
}
if (PER_KG.equalsIgnoreCase(text) || "常规计费".equals(text) || "常规计重价".equals(text))
{
return PER_KG;
}
if (FLAT.equalsIgnoreCase(text) || "一口价".equals(text) || "单票价".equals(text))
{
return FLAT;
}
if (EXTRA.equalsIgnoreCase(text) || "续重价".equals(text) || "续重计费".equals(text))
{
return EXTRA;
}
return "";
}
/**
* 字典上的显示名。
*
* @param raw 计费模式键值或历史名称
* @return 常规计费、一口价、续重价;认不出时退回原文
*/
public static String label(String raw)
{
String mode = code(raw);
if (PER_KG.equals(mode))
{
return "常规计费";
}
if (FLAT.equals(mode))
{
return "一口价";
}
if (EXTRA.equals(mode))
{
return "续重价";
}
return raw == null ? "" : raw.trim();
}
}
@@ -0,0 +1,73 @@
package com.bms.price.pay;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.bms.common.utils.SecurityUtils;
import com.bms.common.utils.StringUtils;
import com.bms.system.domain.BmsExchangeRate;
import com.bms.system.service.IBmsExchangeRateService;
/**
* 应付费用折算为本位币。明细保留三位,汇总另按两位四舍五入。
*/
@Component
public class PayFeeMoney
{
public static final String CNY = BmsExchangeRate.BASE_CURRENCY;
/** 折算后的费用明细小数位 */
public static final int LINE_SCALE = 3;
/** 汇总金额小数位 */
public static final int TOTAL_SCALE = 2;
@Autowired
private IBmsExchangeRateService exchangeRateService;
/**
* 按数据管理里的即期汇率把金额折成人民币。已经是人民币时只补齐小数位。
*
* @param amount 原币金额
* @param currency 原币种
* @param bizDate 汇率日期,空则按当天
* @return 人民币金额,三位小数
*/
public BigDecimal toCny(BigDecimal amount, String currency, Date bizDate)
{
if (amount == null)
{
return null;
}
String code = StringUtils.isEmpty(currency) ? CNY : currency.trim().toUpperCase();
if ("RMB".equals(code) || CNY.equals(code))
{
return amount.setScale(LINE_SCALE, RoundingMode.HALF_UP);
}
return exchangeRateService.convert(amount, code, CNY, null, bizDate).getResult()
.setScale(LINE_SCALE, RoundingMode.HALF_UP);
}
/** 汇总时四舍五入到两位。 */
public static BigDecimal total(BigDecimal amount)
{
BigDecimal value = amount == null ? BigDecimal.ZERO : amount;
return value.setScale(TOTAL_SCALE, RoundingMode.HALF_UP);
}
/** 当前登录用户的主键。没有登录信息时返回空,费用上不写账号。 */
public static String userId()
{
try
{
Long id = SecurityUtils.getUserId();
return id == null ? null : String.valueOf(id);
}
catch (Exception ex)
{
return null;
}
}
}
@@ -18,7 +18,6 @@ import com.bms.price.domain.PayPostcodeGroup;
import com.bms.price.domain.PayPostcodeLine;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PaySurcharge;
import com.bms.price.domain.PaySurchargeRule;
import com.bms.price.domain.PayWeightBand;
import com.bms.price.domain.PrcOrderBill;
import com.bms.price.domain.PrcOrderBillExt;
@@ -26,7 +25,6 @@ import com.bms.price.mapper.PayPostcodeMapper;
import com.bms.price.mapper.PrcOrderBillExtMapper;
import com.bms.price.mapper.PrcOrderBillMapper;
import com.bms.price.service.IPayProductService;
import com.bms.price.service.IPaySurchargeRuleService;
/**
* 按一票已经落库的订单,算出应付尾程运费和订单附加费。
@@ -52,9 +50,6 @@ public class PayOrderFeeCalculator
@Autowired
private PayPostcodeMapper payPostcodeMapper;
@Autowired
private IPaySurchargeRuleService paySurchargeRuleService;
/**
* 计算一票订单的尾程运费和附加费。渠道、价卡、分区或重量不齐时抛出业务异常,调用方决定是否落库。
*
@@ -73,13 +68,9 @@ public class PayOrderFeeCalculator
List<PayPostcodeGroup> linked = linkedGroups(product);
String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked);
applyCurrentSurcharge(channel.getId(), product);
List<PaySurchargeRule> billingRules = product.getBillingRules();
boolean postcodeOn = ruleOn(billingRules, PaySurchargeRules.POSTCODE);
boolean zoneOn = ruleOn(billingRules, PaySurchargeRules.ZONE);
List<PayRemoteBook.Hit> remoteHits = prefixRules(billingRules, PaySurchargeRules.POSTCODE)
? null : remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
List<PayRemoteBook.Hit> remoteHits = remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
PayOrderCostResult result = PayCostCalculator.calculate(product, weight, bill.getPkgLength(), bill.getPkgWidth(),
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, priceDate, orderStatus, remoteHits, postcodeOn, zoneOn,
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, priceDate, orderStatus, remoteHits, true, true,
bill.getCountryCode(), bill.getCountryName());
result.setBillId(bill.getBillId());
result.setChannelId(channel.getId());
@@ -189,10 +180,10 @@ public class PayOrderFeeCalculator
}
/**
* 运费仍按订单日期取版本。附加费明细和计费条件改用这个产品今天生效的版本。
* 运费仍按订单日期取版本。附加费明细改用这个产品今天生效的版本。
*
* @param channelId 渠道 ID
* @param priced 订单日期已经命中的价卡,方法会改写它的附加费和计费条件
* @param priced 订单日期已经命中的价卡,方法会改写它的附加费
*/
private void applyCurrentSurcharge(String channelId, PayProduct priced)
{
@@ -208,59 +199,6 @@ public class PayOrderFeeCalculator
{
// 今天没有生效版本时,附加费明细仍用订单日期命中的那一版
}
List<PaySurchargeRule> rules = paySurchargeRuleService.listForCalc(priced);
priced.setBillingRules(rules == null ? new ArrayList<>() : rules);
}
/**
* 这条计费条件是否启用。没有配置行时视为关闭。
*
* @param rules 当前产品的计费条件
* @param calcRule 条件编码,如 POSTCODE、ZONE
* @return 有启用行时为 true
*/
private static boolean ruleOn(List<PaySurchargeRule> rules, String calcRule)
{
if (rules == null)
{
return false;
}
for (PaySurchargeRule rule : rules)
{
if (rule != null && calcRule.equals(rule.getCalcRule()) && !"0".equals(rule.getEnabled()))
{
return true;
}
}
return false;
}
/**
* 计费条件里是否已经写了邮编前缀。写了就不再去应付邮编配置里查偏远。
*
* @param rules 当前产品的计费条件
* @param calcRule 条件编码,目前用于 POSTCODE
* @return 有非空邮编前缀时为 true
*/
private static boolean prefixRules(List<PaySurchargeRule> rules, String calcRule)
{
if (rules == null)
{
return false;
}
for (PaySurchargeRule rule : rules)
{
if (rule == null || !calcRule.equals(rule.getCalcRule()) || "0".equals(rule.getEnabled()) || rule.getDetail() == null)
{
continue;
}
Object postcodes = rule.getDetail().get("postcodes");
if (postcodes != null && !String.valueOf(postcodes).isBlank())
{
return true;
}
}
return false;
}
/**
@@ -0,0 +1,368 @@
package com.bms.price.pay;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.bms.common.exception.ServiceException;
import com.bms.price.domain.PayPreview;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PaySurcharge;
import com.bms.price.domain.PayWeightBand;
/**
* 三种应付价卡的标准模板。导入和页面新增都落成同一份重量段结构。
*/
public final class PayTemplateWorkbook
{
private static final String[] COMMON = { "产品名称", "价卡归属", "币种", "国家", "国家代码", "分区" };
private static final String[] BAND = { "重量下限KG", "重量上限KG" };
private PayTemplateWorkbook()
{
}
/**
* 写出带一行示例的空模板。
*
* @param chargeType 计费模式
* @param out 响应输出流
*/
public static void write(String chargeType, OutputStream out)
{
String mode = requireMode(chargeType);
try (XSSFWorkbook book = new XSSFWorkbook())
{
Sheet sheet = book.createSheet(PayChargeMode.label(mode));
Row header = sheet.createRow(0);
String[] titles = titles(mode);
for (int i = 0; i < titles.length; i++)
{
header.createCell(i).setCellValue(titles[i]);
sheet.setColumnWidth(i, 16 * 256);
}
Row sample = sheet.createRow(1);
String[] values = sample(mode);
for (int i = 0; i < values.length; i++)
{
sample.createCell(i).setCellValue(values[i]);
}
book.write(out);
}
catch (IOException ex)
{
throw new ServiceException("价卡模板生成失败");
}
}
/**
* 读取标准模板。示例行不入库。同一个产品名称合成一条价卡。
*
* @param bytes 上传的 xlsx
* @param filename 原始文件名
* @param chargeType 页面选中的计费模式
* @return 可预览、确认后再保存的产品
*/
public static PayPreview parse(byte[] bytes, String filename, String chargeType)
{
String mode = requireMode(chargeType);
if (bytes == null || bytes.length == 0)
{
throw new ServiceException("请上传xlsx价卡");
}
DataFormatter formatter = new DataFormatter();
try (XSSFWorkbook book = new XSSFWorkbook(new ByteArrayInputStream(bytes)))
{
if (book.getNumberOfSheets() == 0)
{
throw new ServiceException("模板里没有工作表");
}
Sheet sheet = book.getSheetAt(0);
Row header = sheet.getRow(0);
String[] titles = titles(mode);
if (!headerMatches(header, titles, formatter))
{
throw new ServiceException("表头与「" + PayChargeMode.label(mode) + "」模板不一致,请先下载对应模板");
}
Map<String, PayProduct> products = new LinkedHashMap<>();
int dataRows = 0;
for (int i = 1; i <= sheet.getLastRowNum(); i++)
{
Row row = sheet.getRow(i);
if (row == null || blankRow(row, titles.length, formatter))
{
continue;
}
String name = text(row, 0, formatter);
if (name.isEmpty() || name.startsWith("示例"))
{
continue;
}
dataRows++;
PayProduct product = products.computeIfAbsent(name, key -> newProduct(key, mode));
fillRow(product, row, mode, formatter, i + 1);
}
if (dataRows == 0)
{
throw new ServiceException("模板里没有可导入的价格行,请删除示例后填写");
}
PayPreview preview = new PayPreview();
preview.setSourceFile(filename == null ? "价卡模板.xlsx" : filename);
preview.getProducts().addAll(products.values());
for (PayProduct product : preview.getProducts())
{
product.setWeightCount(product.getWeightBands().size());
product.setSurchargeCount(product.getSurcharges().size());
product.setExtraCount(0);
product.setCountryScope(countryScope(product));
}
return preview;
}
catch (ServiceException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new ServiceException("价卡模板无法读取,请使用系统下载的 xlsx");
}
}
private static String requireMode(String chargeType)
{
String mode = PayChargeMode.code(chargeType);
if (mode.isEmpty())
{
throw new ServiceException("请选择常规计费、一口价或续重价");
}
return mode;
}
private static String[] titles(String mode)
{
if (PayChargeMode.EXTRA.equals(mode))
{
return join(COMMON, new String[] { "首重KG", "首重价格", "续重单价" });
}
String price = PayChargeMode.PER_KG.equals(mode) ? "单价" : "价格";
return join(COMMON, join(BAND, new String[] { price }));
}
private static String[] sample(String mode)
{
if (PayChargeMode.EXTRA.equals(mode))
{
return new String[] { "示例(导入前删除)", "威狮", "EUR", "德国", "DE", "", "1", "3.13", "0.29" };
}
if (PayChargeMode.PER_KG.equals(mode))
{
return new String[] { "示例(导入前删除)", "威狮", "EUR", "奥地利", "AT", "", "0", "31.5", "0.29" };
}
return new String[] { "示例(导入前删除)", "威狮", "EUR", "法国", "FR", "", "0", "1", "3.03" };
}
private static PayProduct newProduct(String name, String mode)
{
PayProduct product = new PayProduct();
product.setProductName(name);
product.setDictValue(name);
product.setSheetName(PayChargeMode.label(mode));
product.setChargeType(mode);
product.setParseStatus("OK");
product.setWeightBands(new ArrayList<>());
product.setSurcharges(new ArrayList<>());
product.setExtraLines(new ArrayList<>());
return product;
}
private static void fillRow(PayProduct product, Row row, String mode, DataFormatter formatter, int lineNo)
{
String supplier = text(row, 1, formatter);
if (!supplier.isEmpty() && (product.getSupplierName() == null || product.getSupplierName().isBlank()))
{
product.setSupplierName(supplier);
}
String currency = currency(text(row, 2, formatter));
if (product.getCurrency() == null || product.getCurrency().isBlank())
{
product.setCurrency(currency);
}
String country = text(row, 3, formatter);
String code = text(row, 4, formatter).toUpperCase(Locale.ROOT);
String zone = text(row, 5, formatter);
if (PayChargeMode.EXTRA.equals(mode))
{
BigDecimal firstKg = number(row, 6, formatter, lineNo, "首重KG");
BigDecimal firstPrice = number(row, 7, formatter, lineNo, "首重价格");
BigDecimal extra = number(row, 8, formatter, lineNo, "续重单价");
if (firstKg.compareTo(BigDecimal.ZERO) <= 0)
{
throw new ServiceException("第" + lineNo + "行首重必须大于 0");
}
PayWeightBand band = band(country, code, zone, BigDecimal.ZERO, firstKg, firstPrice, currency + "/ITEM", "首重");
band.setWeightLabel("首重" + plain(firstKg) + "kg");
band.setSortNo(product.getWeightBands().size() + 1);
product.getWeightBands().add(band);
PaySurcharge fee = new PaySurcharge();
fee.setSectionName("派送费");
fee.setFeeName("每公斤续重");
fee.setZoneName(zone);
fee.setAmount(extra);
fee.setCurrency(currency);
fee.setPriceUnit(currency + "/KG");
fee.setChargeText(plain(extra) + " " + currency + "/KG");
fee.setFeeDesc("超过" + plain(firstKg) + "kg后,按超出的重量每公斤加收");
fee.setCalcRule("EXTRA_KG");
fee.setCalcParam(plain(firstKg));
fee.setChargeTiming("产生时收取");
fee.setSortNo(product.getSurcharges().size() + 1);
product.getSurcharges().add(fee);
return;
}
BigDecimal min = number(row, 6, formatter, lineNo, "重量下限KG");
BigDecimal max = number(row, 7, formatter, lineNo, "重量上限KG");
String priceTitle = PayChargeMode.PER_KG.equals(mode) ? "单价" : "价格";
BigDecimal price = number(row, 8, formatter, lineNo, priceTitle);
if (max.compareTo(min) <= 0)
{
throw new ServiceException("第" + lineNo + "行重量上限必须大于下限");
}
String unit = PayChargeMode.PER_KG.equals(mode) ? currency + "/KG" : currency + "/ITEM";
String charge = PayChargeMode.PER_KG.equals(mode) ? "单价" : "一口价";
PayWeightBand band = band(country, code, zone, min, max, price, unit, charge);
band.setWeightLabel(plain(min) + "<W≤" + plain(max));
band.setSortNo(product.getWeightBands().size() + 1);
product.getWeightBands().add(band);
}
private static PayWeightBand band(String country, String code, String zone, BigDecimal min, BigDecimal max,
BigDecimal price, String unit, String charge)
{
PayWeightBand band = new PayWeightBand();
band.setSectionName("派送费");
band.setCountryName(country);
band.setCountryCode(code);
band.setZoneName(zone);
band.setWeightMin(min);
band.setWeightMax(max);
band.setPrice(price);
band.setPriceUnit(unit);
band.setChargeName(charge);
return band;
}
private static String countryScope(PayProduct product)
{
List<String> names = new ArrayList<>();
for (PayWeightBand band : product.getWeightBands())
{
String name = band.getCountryName() == null ? "" : band.getCountryName().trim();
if (!name.isEmpty() && !names.contains(name))
{
names.add(name);
}
}
return String.join("、", names);
}
private static boolean headerMatches(Row header, String[] titles, DataFormatter formatter)
{
if (header == null)
{
return false;
}
for (int i = 0; i < titles.length; i++)
{
if (!titles[i].equals(text(header, i, formatter)))
{
return false;
}
}
return true;
}
private static boolean blankRow(Row row, int size, DataFormatter formatter)
{
for (int i = 0; i < size; i++)
{
if (!text(row, i, formatter).isEmpty())
{
return false;
}
}
return true;
}
private static String text(Row row, int index, DataFormatter formatter)
{
Cell cell = row.getCell(index);
if (cell == null)
{
return "";
}
return formatter.formatCellValue(cell).trim();
}
private static BigDecimal number(Row row, int index, DataFormatter formatter, int lineNo, String title)
{
String raw = text(row, index, formatter).replace(",", "");
if (raw.isEmpty())
{
throw new ServiceException("第" + lineNo + "行缺少" + title);
}
try
{
return new BigDecimal(raw);
}
catch (NumberFormatException ex)
{
throw new ServiceException("第" + lineNo + "行" + title + "不是数字");
}
}
private static String currency(String raw)
{
String text = raw == null ? "" : raw.trim().toUpperCase(Locale.ROOT);
if (text.isEmpty() || "欧元".equals(raw))
{
return "EUR";
}
if ("英镑".equals(raw) || "GBP".equals(text))
{
return "GBP";
}
if ("美元".equals(raw) || "USD".equals(text))
{
return "USD";
}
if ("人民币".equals(raw) || "CNY".equals(text) || "RMB".equals(text))
{
return "CNY";
}
return text.length() > 8 ? text.substring(0, 8) : text;
}
private static String plain(BigDecimal value)
{
return value.stripTrailingZeros().toPlainString();
}
private static String[] join(String[] left, String[] right)
{
String[] all = new String[left.length + right.length];
System.arraycopy(left, 0, all, 0, left.length);
System.arraycopy(right, 0, all, left.length, right.length);
return all;
}
}
@@ -1221,7 +1221,7 @@ public class PayWorkbookParser
product.setExtraCount(product.getExtraLines().size());
applyFileCountry(product);
product.setChargeType(chargeTypeOf(product));
product.setExtraPerKg("续重计费".equals(product.getChargeType()) ? extraPerKgOf(product) : null);
product.setExtraPerKg(PayChargeMode.EXTRA.equals(product.getChargeType()) ? extraPerKgOf(product) : null);
if (product.getWeightCount() + product.getSurchargeCount() + product.getExtraCount() == 0)
{
product.setParseStatus("EMPTY");
@@ -2416,13 +2416,13 @@ public class PayWorkbookParser
}
if (extraKg)
{
return "续重计费";
return PayChargeMode.EXTRA;
}
if (perKg && itemFee)
{
return "常规计重价";
return PayChargeMode.PER_KG;
}
return "单票价";
return PayChargeMode.FLAT;
}
/**
@@ -34,6 +34,12 @@ public interface IPayProductService
/** 把预览里勾选的产品写入数据库。同名字典产品再次导入时另存一版,旧价格留在有效期表里 */
String save(PaySaveCommand command);
/** 按标准模板解析,不写数据库。chargeType 为字典 order_charge_type 的键值 */
PayPreview previewTemplate(byte[] bytes, String filename, String chargeType);
/** 页面按所选计费模式新增一条公共模板 */
String saveManual(PayProduct product);
/** 一个产品的全部价格版本 */
List<PayProductTerm> listTerms(Long productId);
@@ -1,22 +0,0 @@
package com.bms.price.service;
import java.util.List;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PaySurchargeRule;
import com.bms.price.domain.PaySurchargeRuleLog;
import com.bms.price.domain.PaySurchargeRuleSave;
/** 应付附加费计费条件。一份跟产品走,计算时用当前生效版本上的附加费。 */
public interface IPaySurchargeRuleService
{
List<PaySurchargeRule> list(Long productId, Long termId);
/** 计算时读取的条件。先取产品上的一份,没有再取当前生效版本上的。 */
List<PaySurchargeRule> listForCalc(PayProduct product);
/** 覆盖所选产品的配置。不按价格版本各存一份。 */
void save(PaySurchargeRuleSave command);
/** 这个产品上的附加费配置操作记录。 */
List<PaySurchargeRuleLog> logs(Long productId, Long termId);
}
@@ -61,6 +61,9 @@ public interface IPrcOrderBillService
TmsPriceQuoteResult getBill(Long billId);
/** 应付列表订单详情。不走计费数据权限,同时带出应收和应付费用。 */
TmsPriceQuoteResult getPayOrderBill(Long billId);
/** 订单列表弹窗使用的计费失败原因(带数据权限)。 */
OrderBillFailReasonVo getBillingFailReason(Long billId);
@@ -18,7 +18,6 @@ import com.bms.price.domain.PayPostcodeGroup;
import com.bms.price.domain.PayPostcodeLine;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PaySurcharge;
import com.bms.price.domain.PaySurchargeRule;
import com.bms.price.domain.PayWeightBand;
import com.bms.price.domain.PrcOrderBill;
import com.bms.price.domain.PrcOrderBillExt;
@@ -30,6 +29,7 @@ import com.bms.price.mapper.PrcOrderBillMapper;
import com.bms.price.mapper.PrcPayBillFeeMapper;
import com.bms.price.mapper.PrcPayBillMapper;
import com.bms.price.pay.PayCostCalculator;
import com.bms.price.pay.PayFeeMoney;
import com.bms.price.pay.PaySettleSupport;
import com.bms.price.pay.PayRemoteBook;
import com.bms.price.pay.PaySurchargeRules;
@@ -37,7 +37,6 @@ import com.bms.price.pay.PayZoneMatcher;
import com.bms.price.service.IPayOrderCostService;
import com.bms.price.service.PayBillFeeLogService;
import com.bms.price.service.IPayProductService;
import com.bms.price.service.IPaySurchargeRuleService;
import com.bms.price.service.IPrcPayBillFeeService;
/**
@@ -77,7 +76,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
private PayPostcodeMapper payPostcodeMapper;
@Autowired
private IPaySurchargeRuleService paySurchargeRuleService;
private PayFeeMoney payFeeMoney;
/**
* 重算一票订单的尾程应付并落库。
@@ -141,16 +140,9 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
List<PayPostcodeGroup> linked = linkedGroups(product);
String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked);
applyCurrentSurcharge(channel.getId(), product);
List<PaySurchargeRule> billingRules = product.getBillingRules();
boolean postcodeOn = ruleOn(billingRules, PaySurchargeRules.POSTCODE);
boolean zoneOn = ruleOn(billingRules, PaySurchargeRules.ZONE);
List<PayRemoteBook.Hit> remoteHits = null;
if (!hasPrefixRules(billingRules, PaySurchargeRules.POSTCODE))
{
remoteHits = remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
}
List<PayRemoteBook.Hit> remoteHits = remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
PayOrderCostResult result = PayCostCalculator.calculate(product, weight, bill.getPkgLength(), bill.getPkgWidth(),
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, bizDate, orderStatus, remoteHits, postcodeOn, zoneOn,
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, bizDate, orderStatus, remoteHits, true, true,
bill.getCountryCode(), bill.getCountryName());
result.setBillId(bill.getBillId());
result.setChannelId(channel.getId());
@@ -160,6 +152,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
{
throw new ServiceException(result.getMessage() == null ? PaymentMesEnum.BMS_PAY_NO_COST.getCnMes() : result.getMessage());
}
applyCny(result, bizDate);
String operator = SecurityUtils.getUsername();
PrcPayBill payBill = saveBill(bill, result, operator);
saveFees(bill.getBillId(), payBill.getPayBillId(), result);
@@ -255,42 +248,6 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
{
// 今天没有生效版本时,附加费明细仍用订单日期命中的那一版
}
List<PaySurchargeRule> rules = paySurchargeRuleService.listForCalc(priced);
priced.setBillingRules(rules == null ? new ArrayList<>() : rules);
}
/** 附加费规则里已经写了邮编前缀时,偏远不再去应付邮编配置里查。 */
private static boolean hasPrefixRules(List<PaySurchargeRule> rules, String calcRule)
{
if (rules == null)
{
return false;
}
for (PaySurchargeRule rule : rules)
{
if (rule == null || !calcRule.equals(rule.getCalcRule()) || "0".equals(rule.getEnabled()) || rule.getDetail() == null)
{
continue;
}
Object postcodes = rule.getDetail().get("postcodes");
if (postcodes != null && !String.valueOf(postcodes).isBlank())
{
return true;
}
}
return false;
}
private static boolean ruleOn(List<PaySurchargeRule> rules, String calcRule)
{
for (PaySurchargeRule rule : rules)
{
if (rule != null && calcRule.equals(rule.getCalcRule()) && !"0".equals(rule.getEnabled()))
{
return true;
}
}
return false;
}
private List<PayPostcodeGroup> linkedGroups(PayProduct product)
@@ -686,8 +643,12 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
scId = fallback++;
}
row.setScId(scId);
String userId = PayFeeMoney.userId();
row.setAmount(fee.getAmount());
row.setCurrency(fee.getCurrency());
row.setCurrency(PayFeeMoney.CNY);
row.setFeeSource("CALC");
row.setCreateBy(userId);
row.setUpdateBy(userId);
row.setRoundMode("HALF_UP");
row.setRemark(fee.getRemark());
PrcPayBillFee old = oldCalc.remove(feeKey(row.getFeeType(), row.getScId()));
@@ -727,6 +688,25 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
result.setFeeLogType(recalc ? PayBillFeeLogService.RECALC : PayBillFeeLogService.ADD);
}
/** 按计费日汇率把本次尾程费用折成人民币,明细三位,合计两位。 */
private void applyCny(PayOrderCostResult result, Date bizDate)
{
BigDecimal sum = BigDecimal.ZERO;
List<PayCostLine> fees = result.getFees() == null ? List.of() : result.getFees();
for (PayCostLine fee : fees)
{
BigDecimal cny = payFeeMoney.toCny(fee.getAmount(), fee.getCurrency(), bizDate);
fee.setAmount(cny);
fee.setCurrency(PayFeeMoney.CNY);
if (cny != null)
{
sum = sum.add(cny);
}
}
result.setCurrency(PayFeeMoney.CNY);
result.setPayTotal(PayFeeMoney.total(sum));
}
/** 计算费用,空来源按计算费用处理。 */
private static boolean calcFee(PrcPayBillFee fee)
{
@@ -1,7 +1,6 @@
package com.bms.price.service.impl;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -30,6 +29,7 @@ import com.bms.price.domain.PayOrderRow;
import com.bms.price.domain.PrcPayBillFee;
import com.bms.price.domain.PrcPayBillFeeLog;
import com.bms.price.mapper.PayOrderListMapper;
import com.bms.price.pay.PayFeeMoney;
import com.bms.price.mapper.PrcPayBillFeeMapper;
import com.bms.price.mapper.PrcPayBillMapper;
import com.bms.price.service.IPayOrderCostService;
@@ -73,6 +73,9 @@ public class PayOrderListServiceImpl implements IPayOrderListService
@Autowired
private PayBillFeeLogService payBillFeeLogService;
@Autowired
private PayFeeMoney payFeeMoney;
@Autowired
@Lazy
private PayOrderRecalcAsyncRunner payOrderRecalcAsyncRunner;
@@ -328,16 +331,16 @@ public class PayOrderListServiceImpl implements IPayOrderListService
{
throw new ServiceException("请填写金额");
}
BigDecimal amount = line.getAmount().setScale(2, RoundingMode.HALF_UP);
if (amount.abs().compareTo(new BigDecimal("9999999999.99")) > 0)
{
throw new ServiceException("金额超出范围");
}
String currency = firstText(line.getCurrency(), "CNY").toUpperCase();
if (currency.length() > 10)
{
throw new ServiceException("币种过长");
}
BigDecimal amount = payFeeMoney.toCny(line.getAmount(), currency, order.getBizDate());
if (amount.abs().compareTo(new BigDecimal("9999999999.999")) > 0)
{
throw new ServiceException("金额超出范围");
}
String remark = line.getRemark() == null ? null : line.getRemark().trim();
if (remark != null && remark.length() > 200)
{
@@ -345,6 +348,7 @@ public class PayOrderListServiceImpl implements IPayOrderListService
}
Long orderBillId = Long.valueOf(order.getBillId().trim());
String operator = operator();
String userId = PayFeeMoney.userId();
payBillMapper.insertMissingPayBills(List.of(orderBillId), operator);
PrcPayBill payBill = payBillMapper.selectByBillId(orderBillId);
PrcPayBillFee fee = new PrcPayBillFee();
@@ -356,11 +360,11 @@ public class PayOrderListServiceImpl implements IPayOrderListService
fee.setScId(manualScId());
fee.setFeeLevel(level);
fee.setAmount(amount);
fee.setCurrency(currency);
fee.setCurrency(PayFeeMoney.CNY);
fee.setRemark(remark == null || remark.isEmpty() ? null : remark);
fee.setFeeSource("MANUAL");
fee.setCreateBy(operator);
fee.setUpdateBy(operator);
fee.setCreateBy(userId);
fee.setUpdateBy(userId);
payBillFeeMapper.insertManual(fee);
payBillFeeService.refreshTotals(List.of(orderBillId));
payBillFeeLogService.record(fee, PayBillFeeLogService.ADD);
@@ -49,6 +49,8 @@ import com.bms.price.mapper.PayProductTermMapper;
import com.bms.price.mapper.PrcPriceSetMapper;
import com.bms.price.mapper.PrcSurchargeMapper;
import com.bms.price.pay.PayParseProgressListener;
import com.bms.price.pay.PayChargeMode;
import com.bms.price.pay.PayTemplateWorkbook;
import com.bms.price.pay.PayWorkbookParser;
import com.bms.price.service.IPayProductService;
import com.bms.system.service.ISysDictTypeService;
@@ -307,6 +309,165 @@ public class PayProductServiceImpl implements IPayProductService
return "已保存" + saved + "个产品,新版本" + replaced + "个,跳过" + skipped + "个已存在的产品";
}
@Override
public PayPreview previewTemplate(byte[] bytes, String filename, String chargeType)
{
PayPreview preview = PayTemplateWorkbook.parse(bytes, filename, chargeType);
String md5 = org.springframework.util.DigestUtils.md5DigestAsHex(bytes);
String stored = storeSource(bytes, filename);
rememberSource(md5, stored);
preview.setFileMd5(md5);
preview.setFilePath(stored);
preview.setEffectiveDate(null);
for (PayProduct product : preview.getProducts())
{
product.setProductType(PAY_TYPE_AP);
product.setFileMd5(md5);
product.setSourceFile(preview.getSourceFile());
product.setFilePath(stored);
product.setEffectiveDate(null);
Long existsId = isBlank(product.getDictValue()) ? null : payProductMapper.selectTemplateId(product.getDictValue());
product.setExistsId(existsId);
product.setDuplicated(existsId != null);
}
return preview;
}
@Override
@Transactional(rollbackFor = Exception.class)
public String saveManual(PayProduct product)
{
if (product == null || isBlank(product.getProductName()))
{
throw new ServiceException("请填写产品名称");
}
String mode = PayChargeMode.code(product.getChargeType());
if (mode.isEmpty())
{
throw new ServiceException("请选择常规计费、一口价或续重价");
}
if (product.getWeightBands() == null || product.getWeightBands().isEmpty())
{
throw new ServiceException("请至少添加一行价格");
}
product.setProductName(product.getProductName().trim());
product.setChargeType(mode);
product.setDictValue(product.getProductName());
product.setSheetName(PayChargeMode.label(mode));
if (payProductMapper.selectTemplateId(product.getDictValue()) != null)
{
throw new ServiceException("产品名称已存在,请换一个名称");
}
normalizeManual(product, mode);
product.setSourceFile("手工新增");
product.setFileMd5(IdUtils.fastSimpleUUID());
product.setProductType(PAY_TYPE_AP);
product.setParseStatus("OK");
product.setEffectiveDate(null);
product.setChannelId(null);
product.setOriginId(null);
product.setProductId(null);
product.setVersionNo(1);
product.setCreateBy(SecurityUtils.getUsername());
product.setCreateTime(new Date());
prepareCounts(product);
fitColumns(product);
payProductMapper.insertPayProduct(product);
openTerm(product, false, null);
insertBands(product);
insertSurcharges(product);
insertExtras(product);
return "已保存";
}
/** 手工行补上计费单位。续重行必须带上每公斤续重,否则超过首重无法计费。 */
private static void normalizeManual(PayProduct product, String mode)
{
String currency = isBlank(product.getCurrency()) ? "EUR" : product.getCurrency().trim().toUpperCase(Locale.ROOT);
product.setCurrency(currency);
if (isBlank(product.getCountryScope()))
{
List<String> countries = new ArrayList<>();
for (PayWeightBand band : product.getWeightBands())
{
if (band != null && !isBlank(band.getCountryName()) && !countries.contains(band.getCountryName().trim()))
{
countries.add(band.getCountryName().trim());
}
}
product.setCountryScope(String.join("、", countries));
}
int index = 0;
for (PayWeightBand band : product.getWeightBands())
{
if (band == null || band.getPrice() == null || band.getWeightMax() == null)
{
throw new ServiceException("每一行都要填写重量和价格");
}
if (band.getWeightMin() == null)
{
band.setWeightMin(BigDecimal.ZERO);
}
if (band.getWeightMax().compareTo(band.getWeightMin()) <= 0)
{
throw new ServiceException("重量上限必须大于下限");
}
band.setSectionName(isBlank(band.getSectionName()) ? "派送费" : band.getSectionName());
band.setSortNo(++index);
if (PayChargeMode.PER_KG.equals(mode))
{
band.setChargeName("单价");
band.setPriceUnit(currency + "/KG");
band.setWeightLabel(plainKg(band.getWeightMin()) + "<W≤" + plainKg(band.getWeightMax()));
}
else if (PayChargeMode.FLAT.equals(mode))
{
band.setChargeName("一口价");
band.setPriceUnit(currency + "/ITEM");
band.setWeightLabel(plainKg(band.getWeightMin()) + "<W≤" + plainKg(band.getWeightMax()));
}
else
{
band.setChargeName("首重");
band.setPriceUnit(currency + "/ITEM");
band.setWeightMin(BigDecimal.ZERO);
band.setWeightLabel("首重" + plainKg(band.getWeightMax()) + "kg");
}
}
if (!PayChargeMode.EXTRA.equals(mode))
{
return;
}
if (product.getSurcharges() == null || product.getSurcharges().isEmpty())
{
throw new ServiceException("续重价要填写续重单价");
}
int feeNo = 0;
for (PaySurcharge fee : product.getSurcharges())
{
if (fee == null || fee.getAmount() == null)
{
throw new ServiceException("续重价要填写续重单价");
}
fee.setFeeName("每公斤续重");
fee.setSectionName("派送费");
fee.setCalcRule("EXTRA_KG");
fee.setCurrency(currency);
fee.setPriceUnit(currency + "/KG");
fee.setChargeTiming("产生时收取");
fee.setSortNo(++feeNo);
if (isBlank(fee.getCalcParam()) && fee.getWeightMax() != null)
{
fee.setCalcParam(plainKg(fee.getWeightMax()));
}
}
}
private static String plainKg(BigDecimal value)
{
return value.stripTrailingZeros().toPlainString();
}
@Override
@Transactional(rollbackFor = Exception.class)
public int updateDetail(PayProduct product)
@@ -473,11 +634,12 @@ public class PayProductServiceImpl implements IPayProductService
product.setWeightCount(product.getWeightBands().size());
product.setSurchargeCount(product.getSurcharges().size());
product.setExtraCount(product.getExtraLines().size());
if ("续重计费".equals(product.getChargeType()))
String chargeMode = PayChargeMode.code(product.getChargeType());
if (PayChargeMode.EXTRA.equals(chargeMode))
{
product.setExtraPerKg(PayWorkbookParser.extraPerKgOf(product));
}
else if ("单票价".equals(product.getChargeType()) || "常规计重价".equals(product.getChargeType()))
else if (PayChargeMode.FLAT.equals(chargeMode) || PayChargeMode.PER_KG.equals(chargeMode))
{
product.setExtraPerKg(null);
}
@@ -1,821 +0,0 @@
package com.bms.price.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.bms.common.exception.ServiceException;
import com.bms.common.utils.SecurityUtils;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PayProductTerm;
import com.bms.price.domain.PaySurchargeRule;
import com.bms.price.domain.PaySurchargeRuleLog;
import com.bms.price.domain.PaySurchargeRuleSave;
import com.bms.price.mapper.PayProductMapper;
import com.bms.price.mapper.PayProductTermMapper;
import com.bms.price.mapper.PaySurchargeRuleLogMapper;
import com.bms.price.mapper.PaySurchargeRuleMapper;
import com.bms.price.service.IPaySurchargeRuleService;
@Service
public class PaySurchargeRuleServiceImpl implements IPaySurchargeRuleService
{
private static final Set<String> RULES = Set.of("ALWAYS", "POSTCODE", "ZONE", "EXTRA_KG", "WEIGHT", "SIZE", "RETURN");
private static final Set<String> NUMBERS = Set.of(
"longestMin", "longestMax", "secondMin", "secondMax", "sumMin", "sumMax", "girthMin", "girthMax",
"boxLength", "boxWidth", "boxHeight", "volumeMin", "volumeMax", "cubicMax", "weightMin", "weightMax",
"exceedStepCm", "exceedRatio", "thresholdKg", "stepKg", "minCharge", "ratio");
private static final Map<String, String> RULE_LABELS = Map.of(
"ALWAYS", "每票都收", "POSTCODE", "命中邮编", "ZONE", "命中分区", "EXTRA_KG", "超重续收",
"WEIGHT", "超重", "SIZE", "超尺寸", "RETURN", "退件");
@Autowired
private PaySurchargeRuleMapper ruleMapper;
@Autowired
private PaySurchargeRuleLogMapper logMapper;
@Autowired
private PayProductMapper productMapper;
@Autowired
private PayProductTermMapper termMapper;
@Override
public List<PaySurchargeRule> list(Long productId, Long termId)
{
if (productId == null)
{
return List.of();
}
return hydrateAll(rulesOf(stableId(productId)));
}
@Override
public List<PaySurchargeRule> listForCalc(PayProduct product)
{
if (product == null || product.getProductId() == null)
{
return List.of();
}
Long stable = product.getOriginId() != null ? product.getOriginId() : stableId(product.getProductId());
return hydrateAll(rulesOf(stable));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void save(PaySurchargeRuleSave command)
{
if (command == null || command.getProducts() == null || command.getProducts().isEmpty())
{
throw new ServiceException("请选择要绑定的产品");
}
List<PaySurchargeRule> rules = normalize(command.getRules());
String operator = SecurityUtils.getUsername();
Map<Long, PaySurchargeRuleSave.PaySurchargeRuleBind> products = new LinkedHashMap<>();
for (PaySurchargeRuleSave.PaySurchargeRuleBind bind : command.getProducts())
{
if (bind == null || bind.getProductId() == null)
{
throw new ServiceException("请选择要绑定的产品");
}
products.putIfAbsent(stableId(bind.getProductId()), bind);
}
for (Long stableId : products.keySet())
{
List<Long> family = productMapper.selectFamilyIds(stableId);
if (family == null || family.isEmpty())
{
family = List.of(stableId);
}
List<PaySurchargeRule> before = hydrateAll(rulesOf(stableId));
List<PaySurchargeRuleLog> logs = diffLogs(before, rules, stableId, 0L, null, operator);
ruleMapper.deleteByProductIds(family);
if (!logs.isEmpty())
{
logMapper.insertBatch(logs);
}
if (rules.isEmpty())
{
continue;
}
List<PaySurchargeRule> rows = new ArrayList<>();
int sort = 0;
String lastRule = "";
for (PaySurchargeRule rule : rules)
{
if (!rule.getCalcRule().equals(lastRule))
{
sort = 0;
lastRule = rule.getCalcRule();
}
PaySurchargeRule row = copy(rule);
row.setProductId(stableId);
row.setTermId(0L);
row.setVersionNo(0);
row.setSortNo(sort++);
row.setCreateBy(operator);
row.setUpdateBy(operator);
rows.add(row);
}
ruleMapper.insertBatch(rows);
}
}
private static List<PaySurchargeRule> normalize(List<PaySurchargeRule> raw)
{
List<PaySurchargeRule> rules = new ArrayList<>();
if (raw == null)
{
return rules;
}
for (PaySurchargeRule rule : raw)
{
if (rule == null)
{
continue;
}
String calcRule = rule.getCalcRule() == null ? "" : rule.getCalcRule().trim().toUpperCase(Locale.ROOT);
if (!RULES.contains(calcRule))
{
throw new ServiceException("计费条件不在可选范围内");
}
PaySurchargeRule row = new PaySurchargeRule();
row.setCalcRule(calcRule);
row.setEnabled("0".equals(rule.getEnabled()) ? "0" : "1");
Map<String, Object> detail = cleanDetail(calcRule, rule.getDetail());
row.setDetail(detail);
row.setRuleDetail(detail.isEmpty() ? null : JSON.toJSONString(detail));
row.setCalcParam(trim(summary(calcRule, detail), 2000));
row.setPostcodeParam(trim(text(detail.get("postcodes")), 2000));
row.setZoneName(trim(text(detail.get("zoneName")), 200));
row.setWeightMin(weightMin(calcRule, detail));
row.setWeightMax(decimal(detail.get("weightMax"), "重量上限"));
rules.add(row);
}
Set<String> alwaysFees = new HashSet<>();
for (PaySurchargeRule row : rules)
{
if (!"ALWAYS".equals(row.getCalcRule()) || row.getDetail() == null)
{
continue;
}
String feeName = text(row.getDetail().get("feeName"));
if (feeName != null && !alwaysFees.add(feeName))
{
throw new ServiceException("存在两笔同类型的附加费:" + feeName);
}
}
return rules;
}
@Override
public List<PaySurchargeRuleLog> logs(Long productId, Long termId)
{
if (productId == null)
{
return List.of();
}
List<Long> family = productMapper.selectFamilyIds(stableId(productId));
if (family == null || family.isEmpty())
{
return List.of();
}
return logMapper.selectByProductIds(family);
}
/** 产品上的一份。还没迁到产品上时,用当前生效版本里原来那份。 */
private List<PaySurchargeRule> rulesOf(Long stableId)
{
List<PaySurchargeRule> rows = ruleMapper.selectByProductId(stableId);
if (rows != null && !rows.isEmpty())
{
return rows;
}
Long currentId = productMapper.selectEffectiveVersionId(stableId, new Date());
if (currentId == null)
{
return List.of();
}
PayProductTerm term = termMapper.selectByProductId(currentId);
if (term == null || term.getTermId() == null)
{
return List.of();
}
List<PaySurchargeRule> current = ruleMapper.selectByProduct(currentId, term.getTermId());
return current == null ? List.of() : current;
}
private Long stableId(Long productId)
{
PayProduct product = productMapper.selectPayProductById(productId);
if (product == null)
{
throw new ServiceException("应付产品不存在");
}
return product.getOriginId() == null ? product.getProductId() : product.getOriginId();
}
private static List<PaySurchargeRule> hydrateAll(List<PaySurchargeRule> rows)
{
if (rows == null || rows.isEmpty())
{
return List.of();
}
rows.forEach(PaySurchargeRuleServiceImpl::hydrate);
return rows;
}
private static void hydrate(PaySurchargeRule row)
{
Map<String, Object> detail = parse(row.getRuleDetail());
if (detail.isEmpty())
{
detail = legacy(row);
}
row.setDetail(detail.isEmpty() ? null : detail);
}
private static Map<String, Object> parse(String json)
{
if (json == null || json.isBlank())
{
return new LinkedHashMap<>();
}
Map<String, Object> parsed = JSON.parseObject(json, new TypeReference<LinkedHashMap<String, Object>>() { });
return parsed == null ? new LinkedHashMap<>() : parsed;
}
/** 还没写明细的旧行,用原来的摘要列带回弹框。 */
private static Map<String, Object> legacy(PaySurchargeRule row)
{
Map<String, Object> detail = new LinkedHashMap<>();
String calc = row.getCalcParam();
String postcode = row.getPostcodeParam();
if ("POSTCODE".equals(row.getCalcRule()))
{
put(detail, "postcodeMode", "PREFIX");
put(detail, "postcodes", postcode == null || postcode.isBlank() ? calc : postcode);
}
else if ("ZONE".equals(row.getCalcRule()))
{
put(detail, "zoneName", row.getZoneName());
}
else if ("EXTRA_KG".equals(row.getCalcRule()))
{
put(detail, "thresholdKg", row.getWeightMin() == null ? calc : row.getWeightMin());
put(detail, "postcodes", postcode);
put(detail, "weightBasis", "ACTUAL");
}
else if ("WEIGHT".equals(row.getCalcRule()))
{
put(detail, "weightMin", row.getWeightMin() == null ? calc : row.getWeightMin());
put(detail, "weightBasis", "ACTUAL");
}
else if ("SIZE".equals(row.getCalcRule()))
{
put(detail, "matchMode", "ANY");
put(detail, "remark", calc);
}
else
{
put(detail, "remark", calc);
}
if (row.getWeightMin() != null)
{
detail.putIfAbsent("weightMin", row.getWeightMin());
}
if (row.getWeightMax() != null)
{
detail.put("weightMax", row.getWeightMax());
}
return detail;
}
private static Map<String, Object> cleanDetail(String calcRule, Map<String, Object> raw)
{
Map<String, Object> detail = new LinkedHashMap<>();
if (raw != null)
{
raw.forEach((key, value) -> put(detail, key, value));
}
checkChoice(detail, "matchMode", Set.of("ANY", "ALL"), "命中方式");
checkChoice(detail, "postcodeMode", Set.of("PREFIX", "EXACT"), "邮编匹配");
checkChoice(detail, "weightBasis", Set.of("ACTUAL", "CHARGE"), "重量口径");
checkChoice(detail, "rateMode", Set.of("FIXED", "RATIO"), "计费方式");
checkChoice(detail, "chargeBase", Set.of("HANDLE", "DELIVERY", "FREIGHT_FEE"), "计费基数");
checkChoice(detail, "chargeMode", Set.of("SAME", "AIR", "ROAD", "FIXED"), "退回方式");
checkChoice(detail, "boxMode", Set.of("OVER", "UNDER"), "箱规比较");
for (String key : NUMBERS)
{
if (!detail.containsKey(key))
{
continue;
}
BigDecimal number = decimal(detail.get(key), numberLabel(key));
if (number == null)
{
detail.remove(key);
}
else
{
detail.put(key, number);
}
}
if ("SIZE".equals(calcRule))
{
require(detail.get("matchMode") != null, "超尺寸要选择任一命中或全部命中");
require(hasSize(detail), "超尺寸至少要填最长边、次长边、三边之和、围长、箱规、体积或超出步长");
require(boxComplete(detail), "箱规的长、宽、高要一起填");
}
else if ("WEIGHT".equals(calcRule))
{
require(detail.get("weightMin") != null || detail.get("weightMax") != null, "超重要填写重量下限或上限");
}
else if ("EXTRA_KG".equals(calcRule))
{
require(detail.get("thresholdKg") != null, "超重续收要填写超过多少公斤后开始续收");
}
else if ("ALWAYS".equals(calcRule))
{
require(text(detail.get("feeName")) != null, "每票都收要选择费用项");
}
else if ("POSTCODE".equals(calcRule) || "ZONE".equals(calcRule))
{
require(text(detail.get("zoneName")) != null, "命中邮编和命中分区要选择分区");
require(text(detail.get("postcodes")) != null, "命中邮编和命中分区要填写邮编前缀");
}
else if ("RETURN".equals(calcRule))
{
require(detail.get("chargeMode") != null, "退件要选择退回方式");
require(boxComplete(detail), "箱规的长、宽、高要一起填");
}
return detail;
}
private static boolean hasSize(Map<String, Object> detail)
{
return present(detail, "longestMin", "longestMax", "secondMin", "secondMax", "sumMin", "sumMax",
"girthMin", "girthMax", "boxLength", "volumeMin", "volumeMax", "cubicMax", "exceedStepCm");
}
private static boolean boxComplete(Map<String, Object> detail)
{
boolean any = present(detail, "boxLength", "boxWidth", "boxHeight");
boolean all = detail.get("boxLength") != null && detail.get("boxWidth") != null && detail.get("boxHeight") != null;
return !any || all;
}
private static boolean present(Map<String, Object> detail, String... keys)
{
for (String key : keys)
{
if (detail.get(key) != null)
{
return true;
}
}
return false;
}
private static BigDecimal weightMin(String calcRule, Map<String, Object> detail)
{
if ("EXTRA_KG".equals(calcRule) && detail.get("thresholdKg") != null)
{
return (BigDecimal) detail.get("thresholdKg");
}
return (BigDecimal) detail.get("weightMin");
}
private static String summary(String calcRule, Map<String, Object> detail)
{
if ("POSTCODE".equals(calcRule) || "ZONE".equals(calcRule))
{
List<String> located = new ArrayList<>();
add(located, text(detail.get("zoneName")));
add(located, text(detail.get("postcodes")));
add(located, text(detail.get("country")));
return located.isEmpty() ? null : String.join(";", located);
}
List<String> parts = new ArrayList<>();
add(parts, choice(detail.get("matchMode"), Map.of("ANY", "任一命中", "ALL", "全部命中")));
add(parts, choice(detail.get("postcodeMode"), Map.of("PREFIX", "邮编开头", "EXACT", "完整邮编")));
add(parts, span("最长边", detail.get("longestMin"), detail.get("longestMax"), "cm"));
add(parts, span("次长边", detail.get("secondMin"), detail.get("secondMax"), "cm"));
add(parts, span("三边之和", detail.get("sumMin"), detail.get("sumMax"), "cm"));
add(parts, span("围长", detail.get("girthMin"), detail.get("girthMax"), "cm"));
if (detail.get("boxLength") != null)
{
String mode = "UNDER".equals(detail.get("boxMode")) ? "小于" : "超过";
parts.add(mode + "箱规" + plain(detail.get("boxLength")) + "×" + plain(detail.get("boxWidth")) + "×" + plain(detail.get("boxHeight")) + "cm");
}
add(parts, span("体积", detail.get("volumeMin"), detail.get("volumeMax"), "m³"));
if (detail.get("cubicMax") != null)
{
parts.add("长×宽×高≤" + plain(detail.get("cubicMax")) + "cm³");
}
if (detail.get("exceedStepCm") != null)
{
parts.add("每超出" + plain(detail.get("exceedStepCm")) + "cm");
}
if (detail.get("exceedRatio") != null)
{
parts.add("运费加收" + plain(detail.get("exceedRatio")) + "%");
}
add(parts, span("重量", detail.get("weightMin"), detail.get("weightMax"), "kg"));
add(parts, choice(detail.get("weightBasis"), Map.of("ACTUAL", "实重", "CHARGE", "计费重")));
if (detail.get("thresholdKg") != null)
{
parts.add("超过" + plain(detail.get("thresholdKg")) + "kg后续收");
}
if (detail.get("stepKg") != null)
{
parts.add("每" + plain(detail.get("stepKg")) + "kg");
}
if (detail.get("minCharge") != null)
{
parts.add("最低" + plain(detail.get("minCharge")));
}
add(parts, text(detail.get("zoneName")));
add(parts, text(detail.get("postcodes")));
add(parts, text(detail.get("countries")));
add(parts, choice(detail.get("chargeMode"), Map.of("SAME", "同正向运费", "AIR", "空运退回", "ROAD", "陆运退回", "FIXED", "固定金额")));
add(parts, choice(detail.get("rateMode"), Map.of("FIXED", "固定金额", "RATIO", "按比例")));
if (detail.get("ratio") != null)
{
parts.add(plain(detail.get("ratio")) + "%");
}
String period = joinPeriod(text(detail.get("periodStart")), text(detail.get("periodEnd")));
add(parts, period);
if ("ALWAYS".equals(calcRule) || "RETURN".equals(calcRule) || "SIZE".equals(calcRule))
{
add(parts, text(detail.get("remark")));
}
String feeName = text(detail.get("feeName"));
if (feeName != null)
{
parts.add(0, feeName);
}
return parts.isEmpty() ? null : String.join(";", parts);
}
private static String span(String name, Object min, Object max, String unit)
{
if (min == null && max == null)
{
return null;
}
if (min != null && max != null)
{
return name + " " + plain(min) + "<x≤" + plain(max) + unit;
}
if (min != null)
{
return name + ">" + plain(min) + unit;
}
return name + "≤" + plain(max) + unit;
}
private static String joinPeriod(String start, String end)
{
if (start == null && end == null)
{
return null;
}
return (start == null ? "不限" : start) + "至" + (end == null ? "不限" : end);
}
private static String choice(Object value, Map<String, String> labels)
{
String text = text(value);
return text == null ? null : labels.get(text);
}
private static void checkChoice(Map<String, Object> detail, String key, Set<String> allowed, String label)
{
String value = text(detail.get(key));
if (value == null)
{
detail.remove(key);
return;
}
if (!allowed.contains(value))
{
throw new ServiceException(label + "不在可选范围内");
}
detail.put(key, value);
}
private static void put(Map<String, Object> detail, String key, Object value)
{
if (value == null)
{
return;
}
if (value instanceof String text)
{
if (text.isBlank())
{
return;
}
if (text.length() > 2000)
{
throw new ServiceException("条件内容不能超过2000字");
}
detail.put(key, text.trim());
return;
}
detail.put(key, value);
}
private static BigDecimal decimal(Object value, String label)
{
if (value == null || (value instanceof String text && text.isBlank()))
{
return null;
}
try
{
return new BigDecimal(String.valueOf(value).trim());
}
catch (NumberFormatException ex)
{
throw new ServiceException(label + "要填写数字");
}
}
private static String numberLabel(String key)
{
return switch (key)
{
case "longestMin", "longestMax" -> "最长边";
case "secondMin", "secondMax" -> "次长边";
case "sumMin", "sumMax" -> "三边之和";
case "girthMin", "girthMax" -> "围长";
case "boxLength" -> "箱规长";
case "boxWidth" -> "箱规宽";
case "boxHeight" -> "箱规高";
case "volumeMin", "volumeMax" -> "体积";
case "cubicMax" -> "长宽高乘积";
case "exceedStepCm" -> "超出步长";
case "exceedRatio", "ratio" -> "比例";
case "thresholdKg", "weightMin", "weightMax", "stepKg" -> "重量";
case "minCharge" -> "最低消费";
default -> "数值";
};
}
private static String text(Object value)
{
if (value == null)
{
return null;
}
String text = String.valueOf(value).trim();
return text.isEmpty() ? null : text;
}
private static String plain(Object value)
{
if (value instanceof BigDecimal number)
{
return number.stripTrailingZeros().toPlainString();
}
return text(value);
}
private static void add(List<String> parts, String value)
{
if (value != null && !value.isBlank())
{
parts.add(value);
}
}
private static void require(boolean ok, String message)
{
if (!ok)
{
throw new ServiceException(message);
}
}
private static PaySurchargeRule copy(PaySurchargeRule rule)
{
PaySurchargeRule row = new PaySurchargeRule();
row.setCalcRule(rule.getCalcRule());
row.setEnabled(rule.getEnabled());
row.setCalcParam(rule.getCalcParam());
row.setRuleDetail(rule.getRuleDetail());
row.setDetail(rule.getDetail());
row.setPostcodeParam(rule.getPostcodeParam());
row.setZoneName(rule.getZoneName());
row.setWeightMin(rule.getWeightMin());
row.setWeightMax(rule.getWeightMax());
return row;
}
private static String trim(String value, int max)
{
if (value == null)
{
return null;
}
String text = value.trim();
if (text.isEmpty())
{
return null;
}
if (text.length() > max)
{
throw new ServiceException("条件内容不能超过" + max + "字");
}
return text;
}
private static List<PaySurchargeRuleLog> diffLogs(List<PaySurchargeRule> before, List<PaySurchargeRule> after,
Long productId, Long termId, Integer versionNo, String operator)
{
Map<String, Map<String, String>> oldRows = keyed(before);
Map<String, Map<String, String>> newRows = keyed(after);
List<PaySurchargeRuleLog> logs = new ArrayList<>();
for (Map.Entry<String, Map<String, String>> entry : newRows.entrySet())
{
Map<String, String> previous = oldRows.remove(entry.getKey());
if (previous == null)
{
logs.add(log(productId, termId, versionNo, "1", entry.getKey(), null, entry.getValue(), operator));
continue;
}
Map<String, String> oldChanged = new LinkedHashMap<>();
Map<String, String> newChanged = new LinkedHashMap<>();
Set<String> labels = new java.util.LinkedHashSet<>();
labels.addAll(previous.keySet());
labels.addAll(entry.getValue().keySet());
for (String label : labels)
{
String oldValue = previous.get(label);
String newValue = entry.getValue().get(label);
if (java.util.Objects.equals(oldValue, newValue))
{
continue;
}
if (oldValue != null)
{
oldChanged.put(label, oldValue);
}
if (newValue != null)
{
newChanged.put(label, newValue);
}
}
if (!oldChanged.isEmpty() || !newChanged.isEmpty())
{
logs.add(log(productId, termId, versionNo, "2", entry.getKey(), oldChanged, newChanged, operator));
}
}
for (Map.Entry<String, Map<String, String>> entry : oldRows.entrySet())
{
logs.add(log(productId, termId, versionNo, "3", entry.getKey(), entry.getValue(), null, operator));
}
return logs;
}
private static Map<String, Map<String, String>> keyed(List<PaySurchargeRule> rules)
{
Map<String, Map<String, String>> rows = new LinkedHashMap<>();
Map<String, Integer> index = new LinkedHashMap<>();
if (rules == null)
{
return rows;
}
for (PaySurchargeRule rule : rules)
{
if (rule == null || rule.getCalcRule() == null)
{
continue;
}
Map<String, String> attrs = filled(rule);
if (attrs.isEmpty())
{
continue;
}
String feeName = attrs.get("费用项");
String key;
if ("ALWAYS".equals(rule.getCalcRule()) && feeName != null)
{
key = "ALWAYS|" + feeName;
}
else if ("POSTCODE".equals(rule.getCalcRule()) || "ZONE".equals(rule.getCalcRule()))
{
int next = index.getOrDefault(rule.getCalcRule(), 0);
index.put(rule.getCalcRule(), next + 1);
String zone = attrs.get("分区");
key = rule.getCalcRule() + "|" + (zone == null ? String.valueOf(next) : zone + "#" + next);
}
else
{
int next = index.getOrDefault(rule.getCalcRule(), 0);
index.put(rule.getCalcRule(), next + 1);
key = rule.getCalcRule() + "#" + next;
}
rows.put(key, attrs);
}
return rows;
}
private static Map<String, String> filled(PaySurchargeRule rule)
{
Map<String, Object> detail = rule.getDetail() == null ? Map.of() : rule.getDetail();
Map<String, String> attrs = new LinkedHashMap<>();
putAttr(attrs, "计费条件", RULE_LABELS.getOrDefault(rule.getCalcRule(), rule.getCalcRule()));
putAttr(attrs, "费用项", text(detail.get("feeName")));
putAttr(attrs, "计费方式", choice(detail.get("rateMode"), Map.of("FIXED", "固定金额", "RATIO", "按比例")));
putAttr(attrs, "比例", detail.get("ratio") == null ? null : plain(detail.get("ratio")) + "%");
putAttr(attrs, "计费基数", choice(detail.get("chargeBase"), Map.of("HANDLE", "处理费", "DELIVERY", "派送费", "FREIGHT_FEE", "运费加附加费")));
putAttr(attrs, "生效开始", text(detail.get("periodStart")));
putAttr(attrs, "生效结束", text(detail.get("periodEnd")));
putAttr(attrs, "说明", text(detail.get("remark")));
putAttr(attrs, "命中方式", choice(detail.get("matchMode"), Map.of("ANY", "任一命中", "ALL", "全部命中")));
putAttr(attrs, "邮编匹配", choice(detail.get("postcodeMode"), Map.of("PREFIX", "邮编开头", "EXACT", "完整邮编")));
putAttr(attrs, "最长边下限", unit(detail.get("longestMin"), "cm"));
putAttr(attrs, "最长边上限", unit(detail.get("longestMax"), "cm"));
putAttr(attrs, "次长边下限", unit(detail.get("secondMin"), "cm"));
putAttr(attrs, "次长边上限", unit(detail.get("secondMax"), "cm"));
putAttr(attrs, "三边之和下限", unit(detail.get("sumMin"), "cm"));
putAttr(attrs, "三边之和上限", unit(detail.get("sumMax"), "cm"));
putAttr(attrs, "围长下限", unit(detail.get("girthMin"), "cm"));
putAttr(attrs, "围长上限", unit(detail.get("girthMax"), "cm"));
putAttr(attrs, "箱规比较", choice(detail.get("boxMode"), Map.of("OVER", "超过", "UNDER", "小于")));
if (detail.get("boxLength") != null)
{
putAttr(attrs, "箱规", plain(detail.get("boxLength")) + "×" + plain(detail.get("boxWidth")) + "×" + plain(detail.get("boxHeight")) + "cm");
}
putAttr(attrs, "体积下限", unit(detail.get("volumeMin"), "m³"));
putAttr(attrs, "体积上限", unit(detail.get("volumeMax"), "m³"));
putAttr(attrs, "体积上限立方", unit(detail.get("cubicMax"), "cm³"));
putAttr(attrs, "超出步长", unit(detail.get("exceedStepCm"), "cm"));
putAttr(attrs, "加收比例", detail.get("exceedRatio") == null ? null : plain(detail.get("exceedRatio")) + "%");
putAttr(attrs, "重量下限", unit(detail.get("weightMin"), "kg"));
putAttr(attrs, "重量上限", unit(detail.get("weightMax"), "kg"));
putAttr(attrs, "重量口径", choice(detail.get("weightBasis"), Map.of("ACTUAL", "实重", "CHARGE", "计费重")));
putAttr(attrs, "超过重量", unit(detail.get("thresholdKg"), "kg"));
putAttr(attrs, "每超出", unit(detail.get("stepKg"), "kg"));
putAttr(attrs, "最低消费", plain(detail.get("minCharge")));
putAttr(attrs, "分区", text(detail.get("zoneName")));
putAttr(attrs, "邮编", text(detail.get("postcodes")));
putAttr(attrs, "国家", text(detail.get("country") != null ? detail.get("country") : detail.get("countries")));
putAttr(attrs, "退回方式", choice(detail.get("chargeMode"), Map.of("SAME", "同正向运费", "AIR", "空运退回", "ROAD", "陆运退回", "FIXED", "固定金额")));
return attrs;
}
private static void putAttr(Map<String, String> attrs, String label, String value)
{
if (value == null || value.isBlank())
{
return;
}
attrs.put(label, value);
}
private static String unit(Object value, String unit)
{
String text = plain(value);
return text == null ? null : text + unit;
}
private static PaySurchargeRuleLog log(Long productId, Long termId, Integer versionNo, String operation,
String ruleKey, Map<String, String> before, Map<String, String> after, String operator)
{
Map<String, Object> content = new LinkedHashMap<>();
if (before != null && !before.isEmpty())
{
content.put("before", before);
}
if (after != null && !after.isEmpty())
{
content.put("after", after);
}
PaySurchargeRuleLog row = new PaySurchargeRuleLog();
row.setProductId(productId);
row.setTermId(termId);
row.setVersionNo(versionNo);
row.setOperationType(operation);
row.setRuleKey(ruleKey.length() > 200 ? ruleKey.substring(0, 200) : ruleKey);
row.setChangeContent(JSON.toJSONString(content));
row.setCreateBy(operator);
return row;
}
}
@@ -471,8 +471,24 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
throw new ServiceException(MessageUtils.message("price.bill.notFound"));
}
PrcOrderBill bill = list.get(0);
// 应付暂不在范围内:组装计费结果时不查 prc_pay_bill_fee
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()), null);
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
}
@Override
public TmsPriceQuoteResult getPayOrderBill(Long billId)
{
if (billId == null)
{
throw new ServiceException(MessageUtils.message("price.bill.billIdRequired"));
}
PrcOrderBill bill = orderBillMapper.selectPrcOrderBillById(billId);
if (bill == null)
{
throw new ServiceException(MessageUtils.message("price.bill.notFound"));
}
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
}
@@ -700,7 +716,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
throw new ServiceException(MessageUtils.message("price.bill.notFound"));
}
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()), null);
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
}
@Override
@@ -1885,7 +1902,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
orderBillMapper.updateCreditArrearsStatus(bill.getBillId(), normal, operator);
bill.setCreditArrearsStatus(normal);
saveManualArrearsUpdateEsLog(bill, true, null);
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()), null);
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
}
private void saveManualArrearsUpdateEsLog(PrcOrderBill bill, boolean success, String errorMessage)
@@ -2720,6 +2738,7 @@ bill.setWeight(weight);
line.setCurrency(fee.getCurrency());
line.setRoundMode(fee.getRoundMode());
line.setRemark(fee.getRemark());
line.setFeeSource(fee.getFeeSource());
lines.add(line);
}
return lines;
@@ -3073,7 +3092,8 @@ bill.setWeight(weight);
{
throw new ServiceException(MessageUtils.message("price.bill.notFound"));
}
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()), null);
return toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
}
/** 存在上游 Oracle 行 => 同步/计费路径会同时覆盖 weight 与 charge_weight。 */
@@ -24,6 +24,7 @@ import com.bms.price.airbill.domain.SrvBillAirFeeLog;
import com.bms.price.domain.PrcPayBill;
import com.bms.price.domain.PrcPayBillFee;
import com.bms.price.mapper.SrvBillAirAllocMapper;
import com.bms.price.pay.PayFeeMoney;
import com.bms.price.mapper.SrvBillAirFeeMapper;
import com.bms.price.mapper.SrvBillAirMapper;
import com.bms.price.service.IPrcPayBillFeeService;
@@ -63,6 +64,9 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
@Autowired
private PayBillFeeLogService payBillFeeLogService;
@Autowired
private PayFeeMoney payFeeMoney;
@Override
public List<SrvBillAirAllocFee> preview(List<String> billCodes)
{
@@ -106,7 +110,8 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
{
List<SrvBillAirAllocOrder> rows = orders.get(fee.getBillCode());
fee.setOrderCount(rows.size());
List<BigDecimal> shares = split(fee.getPrice(), rows, true);
BigDecimal cnyPrice = payFeeMoney.toCny(fee.getPrice(), fee.getCurrency(), fee.getCreateTime());
List<BigDecimal> shares = split(cnyPrice, rows, true);
for (int i = 0; i < rows.size(); i++)
{
batch.add(toOrderFee(fee, rows.get(i), shares.get(i), payBillIds));
@@ -245,11 +250,14 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
row.setFeeName(fee.getFeeName());
row.setScId(fee.getId() == null ? 0L : fee.getId());
row.setFeeLevel(fee.getFeeLevel());
String userId = PayFeeMoney.userId();
row.setAmount(amount);
row.setCurrency(fee.getCurrency().trim());
row.setCurrency(PayFeeMoney.CNY);
row.setRoundMode("HALF_UP");
row.setRemark(remark(fee));
row.setFeeSource(FEE_SOURCE);
row.setCreateBy(userId);
row.setUpdateBy(userId);
row.setSourceId(fee.getId() == null ? null : String.valueOf(fee.getId()));
row.setIsDeleted("0");
return row;
@@ -289,7 +297,7 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
}
/**
* 把费用价格拆到每一票订单,结果保留两位,合计等于费用价格。
* 把已经折成人民币的费用价格拆到每一票订单,结果保留三位,合计等于费用价格。
* 按订单数量:每一票先向下取整,差额补在最后一票。
* 按重量:按订单重量占这些订单总重量的比例分摊。前面的订单向下取整,差额补在最后一票有重量的订单上。
* 订单重量优先取计费重,没有计费重时取实际重量,再没有取收货重量。
@@ -301,12 +309,12 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
*/
private static List<BigDecimal> split(BigDecimal price, List<SrvBillAirAllocOrder> orders, boolean byWeight)
{
BigDecimal total = price.setScale(2, RoundingMode.HALF_UP);
BigDecimal total = price.setScale(PayFeeMoney.LINE_SCALE, RoundingMode.HALF_UP);
int count = orders.size();
List<BigDecimal> shares = new ArrayList<>(count);
if (!byWeight)
{
BigDecimal each = total.divide(BigDecimal.valueOf(count), 2, RoundingMode.DOWN);
BigDecimal each = total.divide(BigDecimal.valueOf(count), PayFeeMoney.LINE_SCALE, RoundingMode.DOWN);
BigDecimal used = ZERO;
for (int i = 0; i < count - 1; i++)
{
@@ -334,7 +342,7 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
shares.add(null);
continue;
}
BigDecimal share = total.multiply(weight(orders.get(i))).divide(sum, 2, RoundingMode.DOWN);
BigDecimal share = total.multiply(weight(orders.get(i))).divide(sum, PayFeeMoney.LINE_SCALE, RoundingMode.DOWN);
shares.add(share);
used = used.add(share);
}
@@ -13,7 +13,7 @@
p.product_floor as channelName,
p.charge_weight as chargeWeight,
ifnull(b.pay_total, p.pay_total) as payTotal,
p.currency as currency,
ifnull(nullif(trim(b.currency), ''), 'CNY') as currency,
b.pay_calc_status as payCalcStatus,
b.pay_calc_msg as payCalcMsg,
b.update_by as updateBy,
@@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bms.price.mapper.PaySurchargeRuleLogMapper">
<select id="selectByTerm" resultType="com.bms.price.domain.PaySurchargeRuleLog">
select log_id as logId, product_id as productId, term_id as termId, version_no as versionNo,
operation_type as operationType, rule_key as ruleKey, change_content as changeContent,
create_by as createBy, create_time as createTime
from pay_surcharge_rule_log
where product_id = #{productId}
and term_id = #{termId}
order by log_id desc
</select>
<select id="selectByProductIds" resultType="com.bms.price.domain.PaySurchargeRuleLog">
select log_id as logId, product_id as productId, term_id as termId, version_no as versionNo,
operation_type as operationType, rule_key as ruleKey, change_content as changeContent,
create_by as createBy, create_time as createTime
from pay_surcharge_rule_log
where product_id in
<foreach collection="productIds" item="id" open="(" separator="," close=")">#{id}</foreach>
order by log_id desc
</select>
<insert id="insertBatch">
insert into pay_surcharge_rule_log (
product_id, term_id, version_no, operation_type, rule_key, change_content, create_by, create_time
) values
<foreach collection="list" item="row" separator=",">
(#{row.productId}, #{row.termId}, #{row.versionNo}, #{row.operationType}, #{row.ruleKey},
#{row.changeContent}, #{row.createBy}, sysdate())
</foreach>
</insert>
</mapper>
@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bms.price.mapper.PaySurchargeRuleMapper">
<select id="selectByProduct" resultType="com.bms.price.domain.PaySurchargeRule">
select rule_id as ruleId, product_id as productId, term_id as termId, version_no as versionNo,
calc_rule as calcRule, enabled, calc_param as calcParam, rule_detail as ruleDetail, postcode_param as postcodeParam,
zone_name as zoneName, weight_min as weightMin, weight_max as weightMax, sort_no as sortNo
from pay_surcharge_rule
where product_id = #{productId}
and term_id = #{termId}
order by calc_rule, sort_no, rule_id
</select>
<select id="selectByProductId" resultType="com.bms.price.domain.PaySurchargeRule">
select rule_id as ruleId, product_id as productId, term_id as termId, version_no as versionNo,
calc_rule as calcRule, enabled, calc_param as calcParam, rule_detail as ruleDetail, postcode_param as postcodeParam,
zone_name as zoneName, weight_min as weightMin, weight_max as weightMax, sort_no as sortNo
from pay_surcharge_rule
where product_id = #{productId}
order by calc_rule, sort_no, rule_id
</select>
<delete id="deleteByTerm">
delete from pay_surcharge_rule
where product_id = #{productId}
and term_id = #{termId}
</delete>
<delete id="deleteByProductIds">
delete from pay_surcharge_rule
where product_id in
<foreach collection="productIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</delete>
<insert id="insertBatch">
insert into pay_surcharge_rule (
product_id, term_id, version_no, calc_rule, enabled, calc_param, rule_detail, postcode_param,
zone_name, weight_min, weight_max, sort_no, create_by, create_time, update_by, update_time
) values
<foreach collection="list" item="row" separator=",">
(#{row.productId}, #{row.termId}, ifnull(#{row.versionNo}, 1), #{row.calcRule}, ifnull(#{row.enabled}, '1'),
#{row.calcParam}, #{row.ruleDetail}, #{row.postcodeParam}, #{row.zoneName}, #{row.weightMin}, #{row.weightMax}, ifnull(#{row.sortNo}, 0),
#{row.createBy}, sysdate(), #{row.updateBy}, sysdate())
</foreach>
</insert>
</mapper>
@@ -953,7 +953,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<foreach collection="billIds" item="billId" open="(" separator="," close=")">#{billId}</foreach>
group by bill_id
) s on s.bill_id = o.bill_id
set o.pay_total = ifnull(s.total, 0),
set o.pay_total = round(ifnull(s.total, 0), 2),
o.update_time = sysdate()
where o.bill_id in
<foreach collection="billIds" item="billId" open="(" separator="," close=")">#{billId}</foreach>
@@ -46,11 +46,30 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
</sql>
<sql id="feeUserName">
(
select case
when nullif(trim(u.nick_name), '') is not null then u.nick_name
else u.user_name
end
from sys_user u
where u.del_flag = '0'
and (
(${column} regexp '^[0-9]+$' and u.user_id = cast(${column} as unsigned))
or (ifnull(${column}, '') not regexp '^[0-9]+$' and u.user_name = ${column})
)
limit 1
)
</sql>
<select id="selectByBillId" parameterType="Long" resultMap="PrcPayBillFeeResult">
select f.fee_id, f.bill_id, f.pay_bill_id, f.fee_type, <include refid="feeItemName"/> as fee_name,
f.sc_id, f.fee_level, f.amount, f.currency, f.round_mode, f.remark,
f.fee_source, f.source_id, f.is_deleted, f.statement_line_id,
f.create_by, f.create_time, f.update_by, f.update_time
ifnull(<include refid="feeUserName"><property name="column" value="f.create_by"/></include>, f.create_by) as create_by,
f.create_time,
ifnull(<include refid="feeUserName"><property name="column" value="f.update_by"/></include>, f.update_by) as update_by,
f.update_time
from prc_pay_bill_fee f
<include refid="feeItemJoin"/>
where f.bill_id = #{billId}
@@ -62,7 +81,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
select f.fee_id, f.bill_id, f.pay_bill_id, f.fee_type, <include refid="feeItemName"/> as fee_name,
f.sc_id, f.fee_level, f.amount, f.currency, f.round_mode, f.remark,
f.fee_source, f.source_id, f.is_deleted, f.statement_line_id,
f.create_by, f.create_time, f.update_by, f.update_time
ifnull(<include refid="feeUserName"><property name="column" value="f.create_by"/></include>, f.create_by) as create_by,
f.create_time,
ifnull(<include refid="feeUserName"><property name="column" value="f.update_by"/></include>, f.update_by) as update_by,
f.update_time
from prc_pay_bill_fee f
<include refid="feeItemJoin"/>
where f.fee_id = #{feeId}
@@ -92,22 +114,22 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertPrcPayBillFee" parameterType="PrcPayBillFee">
insert into prc_pay_bill_fee (
fee_id, bill_id, pay_bill_id, fee_type, fee_name, sc_id, fee_level, amount, currency, round_mode, remark,
fee_source, source_id, is_deleted, create_time
fee_source, source_id, is_deleted, create_by, create_time, update_by, update_time
) values (
#{feeId}, #{billId}, #{payBillId}, #{feeType}, #{feeName}, #{scId}, #{feeLevel}, #{amount}, #{currency}, #{roundMode}, #{remark},
ifnull(#{feeSource}, 'CALC'), #{sourceId}, ifnull(#{isDeleted}, '0'), sysdate()
ifnull(#{feeSource}, 'CALC'), #{sourceId}, ifnull(#{isDeleted}, '0'), #{createBy}, sysdate(), #{updateBy}, sysdate()
)
</insert>
<insert id="insertBatch" parameterType="java.util.List">
insert into prc_pay_bill_fee (
fee_id, bill_id, pay_bill_id, fee_type, fee_name, sc_id, fee_level, amount, currency, round_mode, remark,
fee_source, source_id, is_deleted, create_time
fee_source, source_id, is_deleted, create_by, create_time, update_by, update_time
) values
<foreach collection="list" item="item" separator=",">
(#{item.feeId}, #{item.billId}, #{item.payBillId}, #{item.feeType}, #{item.feeName}, #{item.scId}, #{item.feeLevel},
#{item.amount}, #{item.currency}, #{item.roundMode}, #{item.remark}, ifnull(#{item.feeSource}, 'CALC'),
#{item.sourceId}, ifnull(#{item.isDeleted}, '0'), sysdate())
#{item.sourceId}, ifnull(#{item.isDeleted}, '0'), #{item.createBy}, sysdate(), #{item.updateBy}, sysdate())
</foreach>
</insert>
@@ -123,7 +123,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<foreach collection="billIds" item="billId" open="(" separator="," close=")">#{billId}</foreach>
group by bill_id
) s on s.bill_id = b.bill_id
set b.pay_total = ifnull(s.total, 0),
set b.pay_total = round(ifnull(s.total, 0), 2),
b.currency = case
when not exists (
select 1 from prc_pay_bill_fee fx
where fx.bill_id = b.bill_id
and ifnull(fx.is_deleted, '0') = '0'
and upper(ifnull(fx.currency, 'CNY')) not in ('CNY', 'RMB')
) then 'CNY'
else b.currency
end,
b.update_time = sysdate()
where b.bill_id in
<foreach collection="billIds" item="billId" open="(" separator="," close=")">#{billId}</foreach>
@@ -5,7 +5,7 @@
<select id="selectPendingFees" resultType="com.bms.price.airbill.domain.SrvBillAirAllocFee">
select f.id, f.bill_code as billCode, a.guid as ladingId, f.fee_level as feeLevel,
f.bill_fee_status as billFeeStatus, f.fee_type as feeType, sc.sc_name as feeName, f.price, f.currency,
f.alloc_dim as allocDim
f.create_time as createTime, f.alloc_dim as allocDim
from srv_bill_air_fee f
left join srv_bill_air a on a.bill_code = f.bill_code
left join prc_surcharge sc on sc.sc_id = f.sc_id and ifnull(sc.is_del, '0') = '0'