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

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
@@ -19,6 +19,7 @@ import com.bms.price.domain.PayOrderQuery;
import com.bms.price.domain.PayOrderRecalcCommand;
import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.service.IPayOrderListService;
import com.bms.price.service.IPrcOrderBillService;
/** 提单管理下的应付列表。 */
@RestController
@@ -28,6 +29,9 @@ public class PayOrderController extends BaseController
@Autowired
private IPayOrderListService payOrderListService;
@Autowired
private IPrcOrderBillService orderBillService;
@PreAuthorize("@ss.hasPermi('price:payOrder:list')")
@GetMapping("/list")
public TableDataInfo list(PayOrderQuery query)
@@ -82,6 +86,19 @@ public class PayOrderController extends BaseController
return success(payOrderListService.cancelRecalc(taskId));
}
/**
* 应付列表里的订单详情。带出应收费用和应付费用,不按计费列表的销售员权限过滤。
*
* @param billId 计费订单 ID
* @return 订单、应收明细和应付明细
*/
@PreAuthorize("@ss.hasPermi('price:payOrder:query')")
@GetMapping("/{billId}")
public AjaxResult detail(@PathVariable Long billId)
{
return success(orderBillService.getPayOrderBill(billId));
}
/**
* 查看一票订单的应付费用,按 A、B、C、D 四段返回。
*
@@ -30,10 +30,10 @@ import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PayProductTerm;
import com.bms.price.domain.PaySaveCommand;
import com.bms.price.pay.PayDetailExporter;
import com.bms.price.domain.PaySurchargeRuleSave;
import com.bms.price.pay.PayChargeMode;
import com.bms.price.pay.PayTemplateWorkbook;
import com.bms.price.service.IPayOrderCostService;
import com.bms.price.service.IPayProductService;
import com.bms.price.service.IPaySurchargeRuleService;
import jakarta.servlet.http.HttpServletResponse;
/**
@@ -49,9 +49,6 @@ public class PayProductController extends BaseController
@Autowired
private IPayOrderCostService payOrderCostService;
@Autowired
private IPaySurchargeRuleService paySurchargeRuleService;
@PreAuthorize("@ss.hasPermi('price:pay:list')")
@GetMapping("/list")
public TableDataInfo list(PayProduct query)
@@ -107,29 +104,36 @@ public class PayProductController extends BaseController
payProductService.writeSource(productId, response.getOutputStream());
}
/** 产品上的附加费计费条件。不按价格版本拆开。 */
@PreAuthorize("@ss.hasAnyPermi('price:pay:query,price:pay:edit')")
@GetMapping("/surchargeRule")
public AjaxResult surchargeRule(@RequestParam Long productId, @RequestParam(required = false) Long termId)
/** 下载所选计费模式的标准模板 */
@PreAuthorize("@ss.hasAnyPermi('price:pay:import,price:pay:add')")
@PostMapping("/template")
public void template(HttpServletResponse response, @RequestParam String chargeType) throws Exception
{
return success(paySurchargeRuleService.list(productId, termId));
String mode = PayChargeMode.code(chargeType);
String filename = (mode.isEmpty() ? "价卡" : PayChargeMode.label(mode)) + "模板.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
FileUtils.setAttachmentResponseHeader(response, filename);
PayTemplateWorkbook.write(mode, response.getOutputStream());
}
/** 这个产品上的附加费配置操作记录。 */
@PreAuthorize("@ss.hasAnyPermi('price:pay:query,price:pay:edit')")
@GetMapping("/surchargeRule/log")
public AjaxResult surchargeRuleLog(@RequestParam Long productId, @RequestParam(required = false) Long termId)
/** 按标准模板预览,不写数据库 */
@PreAuthorize("@ss.hasPermi('price:pay:import')")
@Log(title = "应付配置", businessType = BusinessType.IMPORT)
@PostMapping(value = "/template/preview", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public AjaxResult previewTemplate(MultipartFile file, @RequestParam String chargeType) throws Exception
{
return success(paySurchargeRuleService.logs(productId, termId));
assertWorkbook(file);
return success(payProductService.previewTemplate(file.getBytes(), file.getOriginalFilename(), chargeType));
}
@PreAuthorize("@ss.hasPermi('price:pay:edit')")
@Log(title = "应付附加费计费条件", businessType = BusinessType.UPDATE)
@PostMapping("/surchargeRule")
public AjaxResult saveSurchargeRule(@RequestBody PaySurchargeRuleSave command)
/** 按所选计费模式手工新增一条价卡 */
@PreAuthorize("@ss.hasPermi('price:pay:add')")
@Log(title = "应付配置", businessType = BusinessType.INSERT)
@PostMapping("/manual")
public AjaxResult manual(@RequestBody PayProduct product)
{
paySurchargeRuleService.save(command);
return success();
return success(payProductService.saveManual(product));
}
@PreAuthorize("@ss.hasPermi('price:pay:query')")
@@ -0,0 +1,76 @@
package com.bms.price.pay;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import com.bms.price.domain.PayPreview;
import com.bms.price.domain.PayProduct;
import com.bms.price.pay.PayCostCalculator;
import com.bms.price.domain.PayOrderCostResult;
/** 三种标准模板都能导回,并且按各自公式算出运费。 */
class PayTemplateWorkbookTest
{
@Test
void flatTemplateChargesTheBandPrice() throws Exception
{
byte[] file = workbook(PayChargeMode.FLAT);
PayPreview preview = PayTemplateWorkbook.parse(replaceSample(file,
"法国Colissimo", "威狮", "EUR", "法国", "FR", "", "0", "1", "3.03"), "一口价.xlsx", PayChargeMode.FLAT);
PayProduct product = preview.getProducts().get(0);
assertEquals(PayChargeMode.FLAT, product.getChargeType());
PayOrderCostResult result = PayCostCalculator.calculate(product, new BigDecimal("0.6"), null, null, null, null, null, null);
assertEquals(new BigDecimal("3.03"), result.getPayTotal());
}
@Test
void perKgTemplateMultipliesWeight() throws Exception
{
byte[] file = workbook(PayChargeMode.PER_KG);
PayPreview preview = PayTemplateWorkbook.parse(replaceSample(file,
"DHL泛欧", "威狮", "EUR", "奥地利", "AT", "", "0", "31.5", "0.29"), "常规计费.xlsx", PayChargeMode.PER_KG);
PayProduct product = preview.getProducts().get(0);
PayOrderCostResult result = PayCostCalculator.calculate(product, new BigDecimal("2.4"), null, null, null, null, null, null);
assertEquals(new BigDecimal("0.70"), result.getPayTotal());
}
@Test
void extraTemplateAddsWeightBeyondTheFirstKilo() throws Exception
{
byte[] file = workbook(PayChargeMode.EXTRA);
PayPreview preview = PayTemplateWorkbook.parse(replaceSample(file,
"CTT", "威狮", "EUR", "西班牙", "ES", "马德里", "1", "2.05", "0.29"), "续重价.xlsx", PayChargeMode.EXTRA);
PayProduct product = preview.getProducts().get(0);
assertTrue(product.getSurcharges().stream().anyMatch(fee -> "EXTRA_KG".equals(fee.getCalcRule())));
PayOrderCostResult result = PayCostCalculator.calculate(product, new BigDecimal("2.4"), null, null, null, null, null, null);
assertEquals(new BigDecimal("2.46"), result.getPayTotal());
}
private static byte[] workbook(String mode) throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
PayTemplateWorkbook.write(mode, out);
return out.toByteArray();
}
/** 用真实数据换掉模板里的示例行,避免示例被跳过。 */
private static byte[] replaceSample(byte[] source, String... values) throws Exception
{
try (org.apache.poi.xssf.usermodel.XSSFWorkbook book = new org.apache.poi.xssf.usermodel.XSSFWorkbook(new java.io.ByteArrayInputStream(source)))
{
org.apache.poi.ss.usermodel.Row row = book.getSheetAt(0).getRow(1);
for (int i = 0; i < values.length; i++)
{
row.getCell(i).setCellValue(values[i]);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
book.write(out);
return out.toByteArray();
}
}
}
@@ -489,7 +489,7 @@ class PayWorkbookParserTest
"西班牙CTT带电专线(主要地区)", List.of("西班牙CTT带电专线(主要地区)"));
PayProduct ctt = preview.getProducts().get(0);
assertEquals("OK", ctt.getParseStatus());
assertEquals("单票价", ctt.getChargeType());
assertEquals("FLAT", ctt.getChargeType());
assertTrue(ctt.getExtraPerKg() == null || ctt.getExtraPerKg().isBlank());
assertEquals(150, ctt.getWeightBands().size());
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "1".equals(band.getWeightLabel())
@@ -534,7 +534,7 @@ class PayWorkbookParserTest
PayProduct ctt = preview.getProducts().get(0);
assertEquals("OK", ctt.getParseStatus());
assertEquals("EUR", ctt.getCurrency());
assertEquals("续重计费", ctt.getChargeType());
assertEquals("EXTRA", ctt.getChargeType());
assertTrue(covers(ctt.getExtraPerKg(), "1.86"));
assertTrue(covers(ctt.getExtraPerKg(), "5.79"));
assertEquals(24, ctt.getWeightBands().size());
@@ -607,7 +607,7 @@ class PayWorkbookParserTest
PayProduct ctt = preview.getProducts().get(0);
assertEquals("OK", ctt.getParseStatus());
assertEquals("西班牙", ctt.getCountryScope());
assertEquals("续重计费", ctt.getChargeType());
assertEquals("EXTRA", ctt.getChargeType());
assertTrue(covers(ctt.getExtraPerKg(), "0.82"));
assertEquals(60, ctt.getWeightBands().size());
assertTrue(ctt.getWeightBands().stream().anyMatch(band -> "西班牙".equals(band.getCountryName()) && "ES".equals(band.getCountryCode())
@@ -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'
+41
View File
@@ -0,0 +1,41 @@
-- 订单收费类型改为常规计费、一口价、续重价
UPDATE `bms`.`sys_dict_data`
SET `dict_label` = '常规计费', `dict_value` = 'PER_KG', `dict_sort` = 1, `remark` = '单价乘以公斤重'
WHERE `dict_type` = 'order_charge_type' AND `dict_value` IN ('常规计重价', '常规计费');
-- 单票价改为一口价
UPDATE `bms`.`sys_dict_data`
SET `dict_label` = '一口价', `dict_value` = 'FLAT', `dict_sort` = 2, `remark` = '重量段内按票收取固定金额'
WHERE `dict_type` = 'order_charge_type' AND `dict_value` IN ('单票价', '一口价');
-- 续重计费改为续重价
UPDATE `bms`.`sys_dict_data`
SET `dict_label` = '续重价', `dict_value` = 'EXTRA', `dict_sort` = 3, `remark` = '首重一口价,超出部分按每公斤续重'
WHERE `dict_type` = 'order_charge_type' AND `dict_value` IN ('续重计费', '续重价');
-- 字典里还没有常规计费时补上
INSERT INTO `bms`.`sys_dict_data` (`dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `remark`)
SELECT 1, '常规计费', 'PER_KG', 'order_charge_type', '', 'default', 'N', '0', 'admin', sysdate(), '单价乘以公斤重'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_dict_data` WHERE `dict_type` = 'order_charge_type' AND `dict_value` = 'PER_KG');
-- 字典里还没有一口价时补上
INSERT INTO `bms`.`sys_dict_data` (`dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `remark`)
SELECT 2, '一口价', 'FLAT', 'order_charge_type', '', 'default', 'N', '0', 'admin', sysdate(), '重量段内按票收取固定金额'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_dict_data` WHERE `dict_type` = 'order_charge_type' AND `dict_value` = 'FLAT');
-- 字典里还没有续重价时补上
INSERT INTO `bms`.`sys_dict_data` (`dict_sort`, `dict_label`, `dict_value`, `dict_type`, `css_class`, `list_class`, `is_default`, `status`, `create_by`, `create_time`, `remark`)
SELECT 3, '续重价', 'EXTRA', 'order_charge_type', '', 'default', 'N', '0', 'admin', sysdate(), '首重一口价,超出部分按每公斤续重'
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_dict_data` WHERE `dict_type` = 'order_charge_type' AND `dict_value` = 'EXTRA');
-- 应付价卡上的历史计费类型改成字典键
UPDATE `bms`.`pay_product` SET `charge_type` = 'PER_KG' WHERE `product_type` = 'AP' AND `charge_type` IN ('常规计重价', '常规计费');
-- 应付价卡上的单票价改成一口价
UPDATE `bms`.`pay_product` SET `charge_type` = 'FLAT' WHERE `product_type` = 'AP' AND `charge_type` IN ('单票价', '一口价');
-- 应付价卡上的续重计费改成续重价
UPDATE `bms`.`pay_product` SET `charge_type` = 'EXTRA' WHERE `product_type` = 'AP' AND `charge_type` IN ('续重计费', '续重价');
@@ -0,0 +1,18 @@
-- 应付配置增加新增价卡按钮
INSERT INTO `bms`.`sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`)
SELECT 2677, '新增价卡', 2508, 7, '', '', 1, 0, 'F', '0', '0', 'price:pay:add', '#', 'admin', sysdate()
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_menu` WHERE `menu_id` = 2677 OR `perms` = 'price:pay:add');
-- 管理员拥有新增价卡按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT 1, 2677
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` WHERE `role_id` = 1 AND `menu_id` = 2677);
-- 能看应付配置的角色同时拥有新增价卡按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT DISTINCT rm.`role_id`, 2677
FROM `bms`.`sys_role_menu` rm
WHERE rm.`menu_id` = 2508
AND NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` x WHERE x.`role_id` = rm.`role_id` AND x.`menu_id` = 2677);
+8
View File
@@ -0,0 +1,8 @@
-- `prc_pay_bill_fee` 费用金额改为三位小数,折人民币后按明细保存
ALTER TABLE `bms`.`prc_pay_bill_fee` MODIFY COLUMN `amount` decimal(18, 3) NOT NULL DEFAULT 0.000 COMMENT '金额(本位币CNY,保留三位)';
-- `prc_pay_bill_fee_log` 变更前金额改为三位小数
ALTER TABLE `bms`.`prc_pay_bill_fee_log` MODIFY COLUMN `before_amount` decimal(18, 3) NULL DEFAULT NULL COMMENT '变更前金额';
-- `prc_pay_bill_fee_log` 变更后金额改为三位小数
ALTER TABLE `bms`.`prc_pay_bill_fee_log` MODIFY COLUMN `after_amount` decimal(18, 3) NULL DEFAULT NULL COMMENT '变更后金额';
@@ -0,0 +1,5 @@
-- 去掉应付附加费配置操作记录表
DROP TABLE IF EXISTS `bms`.`pay_surcharge_rule_log`;
-- 去掉应付附加费配置表
DROP TABLE IF EXISTS `bms`.`pay_surcharge_rule`;
+23 -26
View File
@@ -46,6 +46,29 @@ export function payParseProgress(progressId) {
})
}
/** 按标准模板预览,不写数据库 */
export function previewPayTemplate(file, chargeType) {
const data = new FormData()
data.append('file', file)
data.append('chargeType', chargeType)
return request({
url: '/price/pay/template/preview',
method: 'post',
data,
headers: { 'Content-Type': 'multipart/form-data', repeatSubmit: false },
timeout: 120000
})
}
/** 按所选计费模式手工新增一条价卡 */
export function savePayManual(data) {
return request({
url: '/price/pay/manual',
method: 'post',
data
})
}
/** 修改已保存的公共模板 */
export function updatePay(data) {
return request({
@@ -172,29 +195,3 @@ export function delPay(productIds) {
})
}
/** 产品上的附加费计费条件,不按价格版本拆开 */
export function listPaySurchargeRule(productId) {
return request({
url: '/price/pay/surchargeRule',
method: 'get',
params: { productId }
})
}
/** 这一版产品上的附加费配置操作记录 */
export function listPaySurchargeRuleLog(productId, termId) {
return request({
url: '/price/pay/surchargeRule/log',
method: 'get',
params: { productId, termId }
})
}
/** 覆盖绑定产品当前版本的计费条件。同一版本只保留这一份。 */
export function savePaySurchargeRule(data) {
return request({
url: '/price/pay/surchargeRule',
method: 'post',
data
})
}
+7
View File
@@ -8,6 +8,13 @@ export function listPayOrder(query) {
})
}
export function getPayOrder(billId) {
return request({
url: '/price/payOrder/' + billId,
method: 'get'
})
}
export function listPayOrderFees(billId) {
return request({
url: '/price/payOrder/' + billId + '/fees',
@@ -6,7 +6,7 @@
<el-descriptions-item label="价卡归属">{{ pane.item.supplierName || '-' }}</el-descriptions-item>
<el-descriptions-item label="生效日期">{{ pane.item.effectiveDate || '-' }}</el-descriptions-item>
<el-descriptions-item label="国家/口岸">{{ pane.item.countryScope || '-' }}</el-descriptions-item>
<el-descriptions-item label="费用类型">{{ pane.item.chargeType || '-' }}</el-descriptions-item>
<el-descriptions-item label="费用类型">{{ chargeTypeText(pane.item.chargeType) }}</el-descriptions-item>
<el-descriptions-item label="每公斤加价">{{ pane.item.extraPerKg || '-' }}</el-descriptions-item>
<el-descriptions-item label="服务类型">{{ pane.item.serviceType || '-' }}</el-descriptions-item>
<el-descriptions-item label="分类">{{ pane.item.classification || '-' }}</el-descriptions-item>
@@ -269,8 +269,20 @@
import { h, onMounted, watch } from 'vue'
import { ElInput } from 'element-plus'
import { listSurchargeOptions } from '@/api/price/surcharge'
import { useDict } from '@/utils/dict'
import PaySurchargePickerDialog from './PaySurchargePickerDialog.vue'
const { order_charge_type } = useDict('order_charge_type')
function chargeTypeText(value) {
const hit = (order_charge_type.value || []).find(item => item.value === value)
if (hit) return hit.label
if (value === 'PER_KG') return '常规计费'
if (value === 'FLAT') return '一口价'
if (value === 'EXTRA') return '续重价'
return value || '-'
}
const props = defineProps({
product: {
type: Object,
@@ -0,0 +1,290 @@
<template>
<el-dialog v-model="visible" title="新增应付价卡" width="1080px" append-to-body destroy-on-close @closed="reset">
<el-form label-width="88px">
<el-row :gutter="12">
<el-col :span="8">
<el-form-item label="计费模式" required>
<el-select v-model="form.chargeType" style="width: 100%" @change="onMode">
<el-option v-for="item in modes" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="产品名称" required>
<el-input v-model="form.productName" maxlength="80" placeholder="渠道或产品名称" />
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="价卡归属">
<el-input v-model="form.supplierName" maxlength="40" placeholder="供应商" />
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="币种">
<el-select v-model="form.currency" filterable placeholder="请选择币种" style="width: 100%">
<el-option v-for="item in currencyOptions" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="16">
<el-form-item label="国家/口岸">
<el-select
v-model="scopeCodes"
multiple
filterable
collapse-tags
collapse-tags-tooltip
placeholder="不选则按价格行里的国家汇总"
style="width: 100%"
>
<el-option v-for="item in regions" :key="item.countryCode2" :label="regionLabel(item)" :value="item.countryCode2" />
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div class="bar">
<span>{{ hint }}</span>
<el-button type="primary" link @click="addRow">添加一行</el-button>
</div>
<el-table :data="rows" border size="small" max-height="360">
<el-table-column label="国家" min-width="200">
<template #default="{ row }">
<el-select
v-model="row.countryCode"
filterable
clearable
size="small"
placeholder="选择国家"
style="width: 100%"
@change="code => onCountry(row, code)"
>
<el-option v-for="item in regions" :key="item.countryCode2" :label="regionLabel(item)" :value="item.countryCode2" />
</el-select>
</template>
</el-table-column>
<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 v-if="form.chargeType !== 'EXTRA'" label="重量下限KG" width="120">
<template #default="{ row }"><el-input v-model="row.weightMin" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType !== 'EXTRA'" label="重量上限KG" width="120">
<template #default="{ row }"><el-input v-model="row.weightMax" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType === 'PER_KG'" label="单价" width="110">
<template #default="{ row }"><el-input v-model="row.price" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType === 'FLAT'" label="价格" width="110">
<template #default="{ row }"><el-input v-model="row.price" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType === 'EXTRA'" label="首重KG" width="110">
<template #default="{ row }"><el-input v-model="row.weightMax" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType === 'EXTRA'" label="首重价格" width="110">
<template #default="{ row }"><el-input v-model="row.price" size="small" /></template>
</el-table-column>
<el-table-column v-if="form.chargeType === 'EXTRA'" label="续重单价" width="110">
<template #default="{ row }"><el-input v-model="row.extraPrice" size="small" /></template>
</el-table-column>
<el-table-column label="操作" width="160" align="center">
<template #default="{ $index }">
<el-button v-if="$index > 0" link type="primary" @click="copyPrev($index)">复制上一行</el-button>
<el-button link type="danger" @click="rows.splice($index, 1)">删除</el-button>
</template>
</el-table-column>
</el-table>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submit">保存</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { savePayManual } from '@/api/price/pay'
import { listRegionOptions } from '@/api/data/region'
import { useDict } from '@/utils/dict'
const emit = defineEmits(['saved'])
const { proxy } = getCurrentInstance()
const { order_charge_type, bms_currency } = useDict('order_charge_type', 'bms_currency')
const fallbackModes = [
{ label: '常规计费', value: 'PER_KG' },
{ label: '一口价', value: 'FLAT' },
{ label: '续重价', value: 'EXTRA' }
]
const visible = ref(false)
const saving = ref(false)
const regions = ref([])
const scopeCodes = ref([])
const form = reactive({ chargeType: 'FLAT', productName: '', supplierName: '', currency: 'EUR' })
const rows = ref([])
const currencyOptions = computed(() => {
const dict = (bms_currency.value || []).map(item => ({
label: item.label || item.value,
value: item.value
}))
return dict.length ? dict : [{ label: 'EUR', value: 'EUR' }]
})
const modes = computed(() => {
const dict = (order_charge_type.value || []).filter(item => ['PER_KG', 'FLAT', 'EXTRA'].includes(item.value))
return dict.length ? dict : fallbackModes
})
const hint = computed(() => {
if (form.chargeType === 'PER_KG') return '常规计费:运费 = 单价 × 计费重(公斤)。重量落在哪一档,就用那一档的单价。'
if (form.chargeType === 'EXTRA') return '续重价:不超过首重收首重价格;超出部分 = 超出公斤 × 续重单价。'
return '一口价:计费重落在重量段内,收这一档的固定金额。'
})
function open() {
reset()
loadRegions()
visible.value = true
}
function loadRegions() {
if (regions.value.length) return
listRegionOptions().then(res => {
regions.value = res.data || []
})
}
function regionLabel(item) {
const name = item.countryNameCn || item.countryNameEn || ''
const code = item.countryCode2 || ''
return name ? `${item.flagEmoji || ''} ${name} (${code})`.trim() : code
}
function regionName(code) {
const hit = regions.value.find(item => item.countryCode2 === code)
return hit ? (hit.countryNameCn || hit.countryNameEn || code) : code
}
function onCountry(row, code) {
row.countryCode = code || ''
row.countryName = code ? regionName(code) : ''
}
function reset() {
form.chargeType = 'FLAT'
form.productName = ''
form.supplierName = ''
form.currency = 'EUR'
scopeCodes.value = []
rows.value = [blankRow()]
saving.value = false
}
function onMode() {
rows.value = [blankRow()]
}
function blankRow() {
return { countryName: '', countryCode: '', zoneName: '', weightMin: '0', weightMax: '', price: '', extraPrice: '' }
}
function addRow() {
rows.value.push(blankRow())
}
function copyPrev(index) {
const prev = rows.value[index - 1]
if (!prev) return
rows.value[index] = { ...prev }
}
function num(value, title) {
const text = String(value ?? '').trim()
if (!text) {
proxy.$modal.msgError('请填写' + title)
return null
}
const parsed = Number(text)
if (Number.isNaN(parsed)) {
proxy.$modal.msgError(title + '必须是数字')
return null
}
return parsed
}
async function submit() {
if (!form.productName.trim()) {
proxy.$modal.msgError('请填写产品名称')
return
}
if (!rows.value.length) {
proxy.$modal.msgError('请至少添加一行价格')
return
}
const bands = []
const surcharges = []
for (const row of rows.value) {
const price = num(row.price, form.chargeType === 'PER_KG' ? '单价' : form.chargeType === 'EXTRA' ? '首重价格' : '价格')
if (price == null) return
if (form.chargeType === 'EXTRA') {
const firstKg = num(row.weightMax, '首重KG')
const extra = num(row.extraPrice, '续重单价')
if (firstKg == null || extra == null) return
bands.push({
countryName: row.countryName,
countryCode: row.countryCode,
zoneName: row.zoneName,
weightMin: 0,
weightMax: firstKg,
price
})
surcharges.push({
zoneName: row.zoneName,
amount: extra,
calcParam: String(firstKg)
})
continue
}
const min = num(row.weightMin, '重量下限')
const max = num(row.weightMax, '重量上限')
if (min == null || max == null) return
bands.push({
countryName: row.countryName,
countryCode: row.countryCode,
zoneName: row.zoneName,
weightMin: min,
weightMax: max,
price
})
}
saving.value = true
try {
const countryScope = scopeCodes.value.map(regionName).filter(Boolean).join('、')
await savePayManual({
...form,
productName: form.productName.trim(),
countryScope,
weightBands: bands,
surcharges
})
proxy.$modal.msgSuccess('价卡已保存')
visible.value = false
emit('saved')
} finally {
saving.value = false
}
}
defineExpose({ open })
</script>
<style scoped>
.bar {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: var(--el-text-color-secondary);
}
</style>
@@ -1,7 +1,19 @@
<template>
<el-dialog v-model="visible" title="导入应付价卡" width="1080px" append-to-body destroy-on-close @closed="reset">
<el-form label-width="88px" class="import-form">
<el-form-item label="产品">
<el-form-item label="导入方式">
<el-radio-group v-model="importMode">
<el-radio value="template">标准模板</el-radio>
<el-radio value="source">承运商原表</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item v-if="importMode === 'template'" label="计费模式">
<el-select v-model="chargeType" placeholder="选择后下载对应模板" style="width: 280px">
<el-option v-for="item in modes" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
<el-button link type="primary" :disabled="!chargeType" @click="downloadTemplate">下载模板</el-button>
</el-form-item>
<el-form-item v-else label="产品">
<el-select v-model="dictValue" clearable filterable placeholder="不选则按工作表名称匹配全部字典产品" style="width: 420px">
<el-option v-for="item in payment_product_type" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
@@ -19,7 +31,7 @@
<el-icon class="upload-icon"><UploadFilled /></el-icon>
<div class="el-upload__text">将 xlsx 价卡拖到此处,或<em>点击选择</em></div>
<template #tip>
<div class="upload-tip">选一个产品就只读对应工作表。不选时,一个文件里有多张表,只读取名称能对上字典的工作表。</div>
<div class="upload-tip">{{ importMode === 'template' ? '请先选择计费模式并下载模板,按模板填写后再上传。示例行不会导入。' : '选一个产品就只读对应工作表。不选时,一个文件里有多张表,只读取名称能对上字典的工作表。' }}</div>
</template>
</el-upload>
@@ -104,18 +116,29 @@
<script setup>
import { ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { previewPay, payParseProgress, savePay } from '@/api/price/pay'
import { previewPay, previewPayTemplate, payParseProgress, savePay } from '@/api/price/pay'
import { useDict } from '@/utils/dict'
import PayConfigDetail from './PayConfigDetail.vue'
const emit = defineEmits(['saved'])
const { proxy } = getCurrentInstance()
const { payment_product_type } = useDict('payment_product_type')
const { payment_product_type, order_charge_type } = useDict('payment_product_type', 'order_charge_type')
const fallbackModes = [
{ label: '常规计费', value: 'PER_KG' },
{ label: '一口价', value: 'FLAT' },
{ label: '续重价', value: 'EXTRA' }
]
const modes = computed(() => {
const dict = (order_charge_type.value || []).filter(item => ['PER_KG', 'FLAT', 'EXTRA'].includes(item.value))
return dict.length ? dict : fallbackModes
})
const visible = ref(false)
const recognizing = ref(false)
const saving = ref(false)
const overwrite = ref(false)
const importMode = ref('template')
const chargeType = ref('FLAT')
const dictValue = ref('')
const preview = ref(null)
const selected = ref([])
@@ -133,6 +156,11 @@ const skippedText = computed(() => (preview.value?.skippedSheets || []).filter(B
let parseSeq = 0
let progressTimer = null
function downloadTemplate() {
const hit = modes.value.find(item => item.value === chargeType.value)
proxy.download('/price/pay/template', { chargeType: chargeType.value }, `${hit?.label || '价卡'}模板.xlsx`)
}
function open() {
reset()
visible.value = true
@@ -143,6 +171,8 @@ function reset() {
preview.value = null
selected.value = []
overwrite.value = false
importMode.value = 'template'
chargeType.value = 'FLAT'
dictValue.value = ''
activeKey.value = ''
recognizing.value = false
@@ -161,6 +191,10 @@ async function onFile(uploadFile) {
proxy.$modal.msgError('请上传xlsx价卡')
return
}
if (importMode.value === 'template' && !chargeType.value) {
proxy.$modal.msgError('请先选择计费模式')
return
}
const seq = ++parseSeq
const progressId = createProgressId()
recognizing.value = true
@@ -169,7 +203,9 @@ async function onFile(uploadFile) {
parseStatus.value = undefined
startProgress(seq, progressId)
try {
const res = await previewPay(raw, dictValue.value, progressId, event => {
const requestPreview = importMode.value === 'template'
? previewPayTemplate(raw, chargeType.value)
: previewPay(raw, dictValue.value, progressId, event => {
if (seq !== parseSeq || !event?.total) return
const uploaded = Math.min(8, Math.round(event.loaded * 8 / event.total))
if (uploaded > parsePercent.value) {
@@ -177,6 +213,7 @@ async function onFile(uploadFile) {
parseMessage.value = '正在上传价卡…'
}
})
const res = await requestPreview
if (seq !== parseSeq) return
parsePercent.value = 100
parseMessage.value = '解析完成'
@@ -1,741 +0,0 @@
<template>
<el-dialog v-model="visible" title="附加费配置" width="1080px" append-to-body destroy-on-close @closed="reset">
<div class="rule-body">
<div class="rule-block">
<div class="rule-title">绑定产品</div>
<div class="rule-products">
<el-tag v-for="item in products" :key="item.key" closable class="rule-tag" @close="removeProduct(item)">
{{ item.productName }}
</el-tag>
<span v-if="!products.length" class="rule-empty">还没有产品。勾选列表后打开,或在下面查询后加入。</span>
</div>
<div class="rule-search">
<el-input v-model="keyword" clearable placeholder="按产品名称查询" @keyup.enter="searchProducts" />
<el-button type="primary" plain :loading="searching" @click="searchProducts">查询</el-button>
</div>
<el-table v-if="found.length" :data="found" border size="small" max-height="180" empty-text="没有产品">
<el-table-column prop="productName" label="产品名称" min-width="180" show-overflow-tooltip />
<el-table-column prop="versionNo" label="版本" width="70" align="center" />
<el-table-column label="有效期" min-width="180" show-overflow-tooltip>
<template #default="{ row }">{{ termText(row) }}</template>
</el-table-column>
<el-table-column label="操作" width="80" align="center">
<template #default="{ row }">
<el-button link type="primary" @click="addProduct(row)">加入</el-button>
</template>
</el-table-column>
</el-table>
<p class="rule-hint">配置跟产品走,不跟价格版本。计算时用这个产品当前生效版本上的附加费。</p>
</div>
<div class="rule-block">
<div class="rule-title">计费条件</div>
<div class="rule-switches">
<div v-for="rule in ruleDefs" :key="rule.value" class="rule-switch">
<span>{{ rule.label }}</span>
<el-switch v-model="enabled[rule.value]" @change="value => toggleRule(rule.value, value)" />
</div>
</div>
</div>
<div v-for="rule in openedRules" :key="rule.value" class="rule-block">
<div class="rule-bar">
<span class="rule-title">{{ rule.label }}</span>
<el-button type="primary" link @click="addRow(rule.value)">新增一条</el-button>
</div>
<p class="rule-hint">{{ rule.hint }}</p>
<div v-for="(row, index) in groups[rule.value]" :key="index" class="rule-card">
<div class="rule-card-bar">
<span>第 {{ index + 1 }} 条</span>
<el-button link type="danger" @click="groups[rule.value].splice(index, 1)">删除</el-button>
</div>
<div v-if="rule.value === 'SIZE'" class="rule-grid">
<div class="field">
<span class="label">命中方式</span>
<div class="control">
<el-select v-model="row.matchMode" size="small">
<el-option label="任一命中" value="ANY" />
<el-option label="全部命中" value="ALL" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">重量前提 kg</span>
<div class="control">
<el-input v-model="row.weightMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.weightMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">最长边 cm</span>
<div class="control">
<el-input v-model="row.longestMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.longestMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">次长边 cm</span>
<div class="control">
<el-input v-model="row.secondMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.secondMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">三边之和 cm</span>
<div class="control">
<el-input v-model="row.sumMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.sumMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">围长 cm</span>
<div class="control">
<el-input v-model="row.girthMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.girthMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">箱规 cm</span>
<div class="control">
<el-select v-model="row.boxMode" size="small" class="mode">
<el-option label="任一边超过" value="OVER" />
<el-option label="小于最小尺寸" value="UNDER" />
</el-select>
<el-input v-model="row.boxLength" class="num" size="small" placeholder="长" />
<el-input v-model="row.boxWidth" class="num" size="small" placeholder="宽" />
<el-input v-model="row.boxHeight" class="num" size="small" placeholder="高" />
</div>
</div>
<div class="field">
<span class="label">体积 m³</span>
<div class="control">
<el-input v-model="row.volumeMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.volumeMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">长×宽×高上限 cm³</span>
<div class="control">
<el-input v-model="row.cubicMax" size="small" placeholder="例如 432000" />
</div>
</div>
<div class="field">
<span class="label">每超出 cm</span>
<div class="control">
<el-input v-model="row.exceedStepCm" size="small" placeholder="例如 10" />
</div>
</div>
<div class="field">
<span class="label">运费加收比例 %</span>
<div class="control">
<el-input v-model="row.exceedRatio" size="small" placeholder="例如 35" />
</div>
</div>
<div class="field">
<span class="label">说明</span>
<div class="control">
<el-input v-model="row.remark" size="small" placeholder="这一档的补充说明" />
</div>
</div>
</div>
<div v-else-if="rule.value === 'WEIGHT'" class="rule-grid">
<div class="field">
<span class="label">重量 kg</span>
<div class="control">
<el-input v-model="row.weightMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.weightMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">重量口径</span>
<div class="control">
<el-select v-model="row.weightBasis" size="small">
<el-option label="实重" value="ACTUAL" />
<el-option label="计费重" value="CHARGE" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">每超出 kg</span>
<div class="control">
<el-input v-model="row.stepKg" size="small" placeholder="超过上限后按每公斤" />
</div>
</div>
<div class="field">
<span class="label">最低消费</span>
<div class="control">
<el-input v-model="row.minCharge" size="small" placeholder="没有就空着" />
</div>
</div>
<div class="field">
<span class="label">运费加收比例 %</span>
<div class="control">
<el-input v-model="row.exceedRatio" size="small" placeholder="按运费比例加收时填写" />
</div>
</div>
<div class="field">
<span class="label">说明</span>
<div class="control">
<el-input v-model="row.remark" size="small" />
</div>
</div>
</div>
<div v-else-if="rule.value === 'EXTRA_KG'" class="rule-grid">
<div class="field">
<span class="label">超过 kg</span>
<div class="control">
<el-input v-model="row.thresholdKg" size="small" placeholder="超过这个重量后开始续收" />
</div>
</div>
<div class="field">
<span class="label">每超出 kg</span>
<div class="control">
<el-input v-model="row.stepKg" size="small" placeholder="例如 1" />
</div>
</div>
<div class="field">
<span class="label">重量口径</span>
<div class="control">
<el-select v-model="row.weightBasis" size="small">
<el-option label="实重" value="ACTUAL" />
<el-option label="计费重" value="CHARGE" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">最低消费</span>
<div class="control">
<el-input v-model="row.minCharge" size="small" placeholder="例如 17.5" />
</div>
</div>
<div class="field">
<span class="label">邮编</span>
<div class="control">
<el-input v-model="row.postcodes" size="small" type="textarea" :rows="2" placeholder="续收还要限定邮编时填写,支持 KA27-28 这种区间" />
</div>
</div>
</div>
<div v-else-if="rule.value === 'POSTCODE' || rule.value === 'ZONE'" class="rule-grid">
<div class="field">
<span class="label">分区</span>
<div class="control">
<el-select v-model="row.zoneName" filterable size="small" placeholder="选择附加费里的高、中、低区">
<el-option v-for="zone in zoneOptions" :key="zone" :label="zone" :value="zone" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">邮编前缀</span>
<div class="control">
<el-input v-model="row.postcodes" size="small" type="textarea" :rows="2" placeholder="多个用逗号或换行。前缀、完整邮编、1000-1099、KA27-28 都可以" />
</div>
</div>
<div class="field">
<span class="label">国家</span>
<div class="control">
<el-input v-model="row.country" size="small" placeholder="不填则不限,例如 DE 或 德国" />
</div>
</div>
</div>
<div v-else-if="rule.value === 'ALWAYS'" class="rule-grid">
<div class="field">
<span class="label">费用项</span>
<div class="control">
<el-select v-model="row.feeName" filterable size="small" placeholder="选择这一条要每票收取的费用" @change="(name) => pickFee(row, name)">
<el-option v-for="item in feeOptions" :key="item.feeName" :label="item.feeName" :value="item.feeName" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">计费方式</span>
<div class="control">
<el-select v-model="row.rateMode" size="small">
<el-option label="固定金额" value="FIXED" />
<el-option label="按比例" value="RATIO" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">比例 %</span>
<div class="control">
<el-input v-model="row.ratio" size="small" placeholder="燃油、战争附加费这类" />
</div>
</div>
<div class="field">
<span class="label">计费基数</span>
<div class="control">
<el-select v-model="row.chargeBase" size="small" clearable placeholder="按比例时选择">
<el-option label="处理费" value="HANDLE" />
<el-option label="派送费" value="DELIVERY" />
<el-option label="运费加附加费" value="FREIGHT_FEE" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">生效日期</span>
<div class="control">
<el-date-picker v-model="row.periodStart" type="date" value-format="YYYY-MM-DD" placeholder="开始日期" size="small" clearable />
<span class="sep">至</span>
<el-date-picker v-model="row.periodEnd" type="date" value-format="YYYY-MM-DD" placeholder="结束日期" size="small" clearable />
</div>
</div>
<div class="field">
<span class="label">说明</span>
<div class="control">
<el-input v-model="row.remark" size="small" placeholder="例如每年 11、12 月固定收取" />
</div>
</div>
</div>
<div v-else class="rule-grid">
<div class="field">
<span class="label">退回方式</span>
<div class="control">
<el-select v-model="row.chargeMode" size="small">
<el-option label="同正向运费" value="SAME" />
<el-option label="空运退回" value="AIR" />
<el-option label="陆运退回" value="ROAD" />
<el-option label="固定金额" value="FIXED" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">重量 kg</span>
<div class="control">
<el-input v-model="row.weightMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.weightMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">尺寸命中</span>
<div class="control">
<el-select v-model="row.matchMode" size="small" clearable placeholder="退件还看尺寸时选择">
<el-option label="任一命中" value="ANY" />
<el-option label="全部命中" value="ALL" />
</el-select>
</div>
</div>
<div class="field">
<span class="label">最长边 cm</span>
<div class="control">
<el-input v-model="row.longestMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.longestMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">围长 cm</span>
<div class="control">
<el-input v-model="row.girthMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.girthMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">三边之和 cm</span>
<div class="control">
<el-input v-model="row.sumMin" size="small" placeholder="下限" />
<span class="sep">至</span>
<el-input v-model="row.sumMax" size="small" placeholder="上限" />
</div>
</div>
<div class="field">
<span class="label">说明</span>
<div class="control">
<el-input v-model="row.remark" size="small" placeholder="例如拒收、地址错误退回" />
</div>
</div>
</div>
</div>
</div>
</div>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="save">保存</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { getPay, listPay, listPaySurchargeRule, savePaySurchargeRule } from '@/api/price/pay'
const { proxy } = getCurrentInstance()
const ruleDefs = [
{
value: 'SIZE',
label: '超尺寸',
hint: '按报价里的每一档填写。只写最长边>120 就只填下限;100<最长边≤200 则下限、上限都填。围长是长+2×(宽+高)。任一命中对应「或 / 任一边超过」,全部命中对应「且 / 同时满足」。运费另加 35%、70% 填加收比例,每超出 10cm 填超出步长。'
},
{
value: 'WEIGHT',
label: '超重',
hint: '30<W≤70 填下限 30、上限 70;只写超过 30KG 就只填下限。超过 300kg 后每公斤续收的,填每超出。报价写明按实际重量、不按体积重时,口径选实重。'
},
{
value: 'EXTRA_KG',
label: '超重续收',
hint: '超过某个重量后只收超出部分。偏远按公斤且有最低消费的,把邮编和最低消费写在这一条。'
},
{
value: 'POSTCODE',
label: '命中邮编',
hint: '按附加费里的高、中、低区填写邮编前缀。订单邮编命中这一区,才加这一区的附加费。前缀、完整邮编和区间都认。国家不填则不限目的国。'
},
{
value: 'ZONE',
label: '命中分区',
hint: '写法和命中邮编一样,表示这些邮编属于哪个地区。命中后按该地区的附加费收取。运费用的地区仍按应付邮编配置。'
},
{
value: 'ALWAYS',
label: '每票都收',
hint: '每一条都要选费用项,没被选中的费用不会按每票收取。燃油、去碳按比例填写比例和基数,旺季再填生效日期。'
},
{
value: 'RETURN',
label: '退件',
hint: '同正向运费、空运或陆运分开配。超尺寸或超重才退件的,把重量和最长边、围长写在同一条。'
}
]
const visible = ref(false)
const saving = ref(false)
const searching = ref(false)
const keyword = ref('')
const found = ref([])
const products = ref([])
const feeOptions = ref([])
const feeCounts = ref({})
const zoneOptions = ref([])
const enabled = reactive({})
const groups = reactive({})
function blank(rule) {
if (rule === 'SIZE') {
return { matchMode: 'ANY', boxMode: 'OVER', weightMin: '', weightMax: '', longestMin: '', longestMax: '', secondMin: '', secondMax: '', sumMin: '', sumMax: '', girthMin: '', girthMax: '', boxLength: '', boxWidth: '', boxHeight: '', volumeMin: '', volumeMax: '', cubicMax: '', exceedStepCm: '', exceedRatio: '', remark: '' }
}
if (rule === 'WEIGHT') {
return { weightMin: '', weightMax: '', weightBasis: 'ACTUAL', stepKg: '', minCharge: '', exceedRatio: '', remark: '' }
}
if (rule === 'EXTRA_KG') {
return { thresholdKg: '', stepKg: '1', weightBasis: 'ACTUAL', minCharge: '', postcodes: '' }
}
if (rule === 'POSTCODE' || rule === 'ZONE') {
return { zoneName: '', postcodes: '', country: '' }
}
if (rule === 'ALWAYS') {
return { feeName: '', scId: '', rateMode: 'FIXED', ratio: '', chargeBase: '', periodStart: '', periodEnd: '', remark: '' }
}
return { chargeMode: 'SAME', weightMin: '', weightMax: '', matchMode: '', longestMin: '', longestMax: '', girthMin: '', girthMax: '', sumMin: '', sumMax: '', remark: '' }
}
function blankGroups() {
for (const rule of ruleDefs) {
enabled[rule.value] = false
groups[rule.value] = []
}
}
function reset() {
keyword.value = ''
found.value = []
products.value = []
feeOptions.value = []
feeCounts.value = {}
zoneOptions.value = []
blankGroups()
saving.value = false
searching.value = false
}
function open(rows) {
reset()
visible.value = true
const skipped = []
for (const row of rows || []) addProduct(row, skipped)
if (skipped.length) proxy.$modal.msgWarning('有产品还没有生效版本,未带入:' + skipped.join('、'))
const first = products.value[0]
if (first) loadRules(first.productId)
}
function versionOf(row) {
return {
key: String(row.productId),
productId: row.productId,
feeProductId: row.versionProductId || row.productId,
productName: row.productName || '未命名产品'
}
}
function addProduct(row, skipped) {
const item = versionOf(row)
if (!item.productId) {
if (skipped) skipped.push(item.productName)
else proxy.$modal.msgWarning(item.productName + '不能绑定')
return
}
if (products.value.some(product => product.key === item.key)) return
products.value.push(item)
loadFees()
}
function removeProduct(item) {
products.value = products.value.filter(product => product.key !== item.key)
loadFees()
}
let feeToken = 0
function loadFees() {
const token = ++feeToken
const bound = products.value.slice()
if (!bound.length) {
feeOptions.value = []
feeCounts.value = {}
zoneOptions.value = keepZones([])
return Promise.resolve()
}
return Promise.all(bound.map(item => getPay(item.feeProductId || item.productId).catch(() => null))).then(results => {
if (token !== feeToken) return
const map = new Map()
const counts = {}
const zones = new Set()
results.forEach(res => {
const local = {}
const rows = res?.data?.surcharges || []
rows.forEach(fee => {
const name = String(fee.feeName || '').trim()
const zone = String(fee.zoneName || '').trim()
if (zone) zones.add(zone)
if (!name) return
local[name] = (local[name] || 0) + 1
if (!map.has(name)) map.set(name, { feeName: name, scId: fee.scId || '' })
})
Object.keys(local).forEach(name => {
counts[name] = Math.max(counts[name] || 0, local[name])
})
})
zoneOptions.value = keepZones([...zones])
feeCounts.value = counts
for (const row of groups.ALWAYS || []) {
const name = String(row.feeName || '').trim()
if (name && !map.has(name)) map.set(name, { feeName: name, scId: row.scId || '' })
}
feeOptions.value = [...map.values()]
})
}
function keepZones(zones) {
const set = new Set(zones)
for (const rule of ['POSTCODE', 'ZONE']) {
for (const row of groups[rule] || []) {
const zone = String(row.zoneName || '').trim()
if (zone) set.add(zone)
}
}
return [...set]
}
function pickFee(row, name) {
const found = feeOptions.value.find(item => item.feeName === name)
row.scId = found?.scId || ''
}
function termText(row) {
const start = row.termStart || row.effectiveStart || ''
const end = row.termEnd || row.effectiveEnd || ''
if (!start && !end) return '-'
return (String(start).slice(0, 10) || '不限') + ' 至 ' + (String(end).slice(0, 10) || '不限')
}
function searchProducts() {
searching.value = true
listPay({ productName: keyword.value.trim(), templateOnly: true, currentOnly: true, pageNum: 1, pageSize: 20 }).then(res => {
found.value = res.rows || []
}).finally(() => {
searching.value = false
})
}
function toggleRule(rule, value) {
const def = ruleDefs.find(item => item.value === rule)
if (def?.switchOnly) return
if (value && !groups[rule].length) groups[rule].push(blank(rule))
}
function addRow(rule) {
groups[rule].push(blank(rule))
}
function applyRules(list) {
blankGroups()
for (const item of list || []) {
const rule = item.calcRule
if (!groups[rule]) continue
enabled[rule] = item.enabled !== '0'
if (ruleDefs.find(def => def.value === rule)?.switchOnly) continue
if (item.enabled === '0') continue
const row = blank(rule)
const detail = item.detail || {}
Object.keys(row).forEach(key => {
if (detail[key] === undefined || detail[key] === null) return
row[key] = key === 'periodStart' || key === 'periodEnd' ? asDate(detail[key]) : String(detail[key])
})
groups[rule].push(row)
}
for (const rule of ruleDefs) {
if (rule.switchOnly) continue
if (enabled[rule.value] && !groups[rule.value].length) groups[rule.value].push(blank(rule.value))
}
const map = new Map(feeOptions.value.map(item => [item.feeName, item]))
for (const row of groups.ALWAYS || []) {
const name = String(row.feeName || '').trim()
if (name && !map.has(name)) map.set(name, { feeName: name, scId: row.scId || '' })
}
feeOptions.value = [...map.values()]
zoneOptions.value = keepZones(zoneOptions.value)
}
function asDate(value) {
const text = String(value).trim()
if (/^\d{4}-\d{2}-\d{2}/.test(text)) return text.slice(0, 10)
const monthDay = text.match(/^(\d{1,2})-(\d{1,2})$/)
if (!monthDay) return ''
const year = new Date().getFullYear()
return `${year}-${monthDay[1].padStart(2, '0')}-${monthDay[2].padStart(2, '0')}`
}
function loadRules(productId) {
listPaySurchargeRule(productId).then(res => applyRules(res.data || []))
}
const openedRules = computed(() => ruleDefs.filter(rule => enabled[rule.value] && !rule.switchOnly))
function detailOf(rule, row) {
const detail = {}
const template = blank(rule)
Object.keys(template).forEach(key => {
const value = row[key]
if (value === '' || value === null || value === undefined) return
detail[key] = value
})
return detail
}
function payloadRules() {
const rules = []
for (const rule of ruleDefs) {
if (!enabled[rule.value]) continue
if (rule.switchOnly) {
rules.push({ calcRule: rule.value, enabled: '1', detail: {} })
continue
}
const rows = groups[rule.value].length ? groups[rule.value] : [blank(rule.value)]
rows.forEach(row => {
rules.push({ calcRule: rule.value, enabled: '1', detail: detailOf(rule.value, row) })
})
}
return rules
}
function save() {
if (!products.value.length) {
proxy.$modal.msgError('请选择要绑定的产品')
return
}
for (const rule of ['POSTCODE', 'ZONE']) {
if (!enabled[rule]) continue
const label = rule === 'POSTCODE' ? '命中邮编' : '命中分区'
for (const row of groups[rule]) {
if (!String(row.zoneName || '').trim() || !String(row.postcodes || '').trim()) {
proxy.$modal.msgError(label + '要选择分区,并填写邮编前缀')
return
}
}
}
if (enabled.ALWAYS) {
for (const row of groups.ALWAYS) {
if (!String(row.feeName || '').trim()) {
proxy.$modal.msgError('每票都收要选择费用项')
return
}
}
}
saving.value = true
loadFees().then(() => {
const duplicated = sameTypeFees()
if (duplicated.length) {
proxy.$modal.alert('存在两笔同类型的附加费:' + duplicated.join('、'))
return
}
return savePaySurchargeRule({
products: products.value.map(item => ({
productId: item.productId,
productName: item.productName
})),
rules: payloadRules()
}).then(() => {
proxy.$modal.msgSuccess('已保存,计算时按当前生效版本上的附加费执行')
visible.value = false
})
}).finally(() => {
saving.value = false
})
}
function sameTypeFees() {
if (!enabled.ALWAYS) return []
const seen = new Set()
const duplicated = []
for (const row of groups.ALWAYS) {
const name = String(row.feeName || '').trim()
if (!name) continue
if (seen.has(name) || Number(feeCounts.value[name] || 0) >= 2) duplicated.push(name)
seen.add(name)
}
return [...new Set(duplicated)]
}
defineExpose({ open })
</script>
<style scoped>
.rule-body { max-height: 68vh; overflow: auto; padding-right: 4px; }
.rule-block { margin-bottom: 16px; }
.rule-title { font-weight: 600; }
.rule-products { display: flex; flex-wrap: wrap; gap: 8px; min-height: 32px; margin: 8px 0; }
.rule-tag { margin: 0; }
.rule-empty { color: var(--el-text-color-secondary); font-size: 13px; }
.rule-search { display: flex; gap: 8px; margin-bottom: 8px; }
.rule-hint { margin: 6px 0 8px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.5; }
.rule-switches { display: flex; flex-wrap: wrap; gap: 12px 20px; margin-top: 8px; }
.rule-switch { display: flex; align-items: center; gap: 8px; }
.rule-bar, .rule-card-bar { display: flex; align-items: center; justify-content: space-between; }
.rule-card { border: 1px solid var(--el-border-color); border-radius: 6px; padding: 12px 20px 12px 28px; margin-bottom: 10px; overflow: visible; }
.rule-grid { display: grid; grid-template-columns: 1fr 1fr; column-gap: 48px; row-gap: 12px; align-items: center; }
.field { display: grid; grid-template-columns: 104px minmax(0, 1fr); column-gap: 8px; align-items: center; min-width: 0; }
.field .label { width: 104px; min-width: 0; justify-self: end; text-align: right; white-space: nowrap; overflow: visible; font-size: 13px; line-height: 24px; color: var(--el-text-color-regular); }
.control { display: flex; align-items: center; gap: 6px; min-width: 0; }
.control :deep(.el-input),
.control :deep(.el-select),
.control :deep(.el-textarea),
.control :deep(.el-date-editor) { flex: 1 1 0; width: 0 !important; min-width: 0; max-width: none; }
.control :deep(.mode) { flex: 1.7 1 0; }
.control :deep(.num) { flex: 0.75 1 0; }
.field .sep { flex: none; color: var(--el-text-color-secondary); line-height: 24px; }
</style>
+23 -70
View File
@@ -14,6 +14,9 @@
<el-col :span="1.5">
<el-button type="primary" plain icon="Link" :disabled="selection.length !== 1" @click="openBind(selection)" v-hasPermi="['price:pay:bind']">绑定渠道</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="primary" plain icon="Plus" @click="createRef.open()" v-hasPermi="['price:pay:add']">新增价卡</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="primary" plain icon="Upload" @click="importRef.open()" v-hasPermi="['price:pay:import']">导入价卡</el-button>
</el-col>
@@ -26,9 +29,10 @@
<el-col :span="1.5">
<el-button type="warning" plain icon="Download" @click="handleExportDetail" v-hasPermi="['price:pay:export']">导出明细</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="primary" plain icon="Setting" @click="openRule(selection)" v-hasPermi="['price:pay:edit']">附加费配置</el-button>
</el-col>
</template>
<template #col-chargeType="{ row }">
<span>{{ chargeTypeText(row.chargeType) }}</span>
</template>
<template #col-sourceFile="{ row }">
@@ -67,6 +71,7 @@
</basic-table>
<pay-import-dialog ref="importRef" @saved="tableRef.refresh()" />
<pay-create-dialog ref="createRef" @saved="tableRef.refresh()" />
<el-dialog v-model="bindVisible" title="绑定渠道" width="640px" append-to-body @closed="resetBind">
<el-form label-width="70px">
<el-form-item label="产品">
@@ -93,8 +98,6 @@
<el-button type="primary" :loading="bindSaving" @click="submitBind">确认</el-button>
</template>
</el-dialog>
<pay-surcharge-rule-dialog ref="ruleRef" />
<el-drawer v-model="historyVisible" :title="historyTitle" size="980px" append-to-body destroy-on-close>
<div class="history-bar">
<el-button type="primary" plain :disabled="historyPicked.length !== 2" @click="openCompare">比对所选版本</el-button>
@@ -120,31 +123,12 @@
<el-table-column label="操作" width="220" align="center">
<template #default="{ row }">
<el-button link type="primary" @click="downloadSource(row)" v-hasPermi="['price:pay:query']">下载</el-button>
<el-button link type="primary" @click="openRuleLog(row)" v-hasPermi="['price:pay:query']">附加费记录</el-button>
<el-button link type="primary" @click="openDetail(row)" v-hasPermi="['price:pay:query']">查看</el-button>
</template>
</el-table-column>
</el-table>
</el-drawer>
<el-dialog v-model="ruleLogVisible" :title="ruleLogTitle" width="860px" append-to-body>
<el-table v-loading="ruleLogLoading" :data="ruleLogRows" border size="small" empty-text="这一版还没有附加费配置记录">
<el-table-column label="操作" width="70" align="center">
<template #default="{ row }">{{ ruleLogAction(row.operationType) }}</template>
</el-table-column>
<el-table-column label="更改前" min-width="220" show-overflow-tooltip>
<template #default="{ row }">{{ ruleLogSide(row, 'before') }}</template>
</el-table-column>
<el-table-column label="更改后" min-width="220" show-overflow-tooltip>
<template #default="{ row }">{{ ruleLogSide(row, 'after') }}</template>
</el-table-column>
<el-table-column prop="createBy" label="操作人" width="100" align="center" />
<el-table-column label="操作时间" width="160" align="center">
<template #default="{ row }">{{ row.createTime || '-' }}</template>
</el-table-column>
</el-table>
</el-dialog>
<el-dialog v-model="termVisible" title="修改有效期" width="460px" append-to-body>
<el-form label-width="90px">
<el-form-item label="生效开始" required>
@@ -221,16 +205,18 @@
</template>
<script setup name="PricePay">
import { listPay, getPay, delPay, updatePay, listPayTerm, updatePayTerm, changePayTermStatus, comparePay, listPaySurchargeRuleLog, batchBindChannelPay } from '@/api/price/pay'
import { listPay, getPay, delPay, updatePay, listPayTerm, updatePayTerm, changePayTermStatus, comparePay, batchBindChannelPay } from '@/api/price/pay'
import { listChannelOptions } from '@/api/masterdata/serviceChannel'
import { useDict } from '@/utils/dict'
import PayImportDialog from './components/PayImportDialog.vue'
import PayCreateDialog from './components/PayCreateDialog.vue'
import PayConfigDetail from './components/PayConfigDetail.vue'
import PaySurchargeRuleDialog from './components/PaySurchargeRuleDialog.vue'
const { proxy } = getCurrentInstance()
const { order_charge_type } = useDict('order_charge_type')
const tableRef = ref()
const importRef = ref()
const ruleRef = ref()
const createRef = ref()
const detailVisible = ref(false)
const detailLoading = ref(false)
const savingRowKey = ref('')
@@ -241,10 +227,6 @@ const historyRows = ref([])
const historyTitle = ref('价格版本')
const historyProductId = ref(null)
const historyPicked = ref([])
const ruleLogVisible = ref(false)
const ruleLogLoading = ref(false)
const ruleLogRows = ref([])
const ruleLogTitle = ref('附加费配置记录')
const compareVisible = ref(false)
const compareLoading = ref(false)
const compareTitle = ref('版本比对')
@@ -275,7 +257,7 @@ const statusOptions = [
]
const columns = [
{ label: '服务商渠道名称', prop: 'productName', align: 'center', minWidth: 180, showOverflowTooltip: true, fixed: 'left' },
{ label: '应付价卡名称', prop: 'productName', align: 'center', minWidth: 180, showOverflowTooltip: true, fixed: 'left' },
{ label: '价卡归属', prop: 'supplierName', align: 'center', width: 100 },
{ label: '国家/口岸', prop: 'countryScope', align: 'center', minWidth: 120, showOverflowTooltip: true },
{ label: '费用类型', prop: 'chargeType', align: 'center', width: 110 },
@@ -295,7 +277,7 @@ const columns = [
]
const searchColumns = [
{ label: '服务商渠道名称', prop: 'productName', component: 'input', placeholder: '产品名称', width: '180px' },
{ label: '应付价卡名称', prop: 'productName', component: 'input', placeholder: '产品名称', width: '180px' },
{ label: '价卡归属', prop: 'supplierName', component: 'input', placeholder: '威狮、易德、GWE', width: '160px' },
{ label: '来源文件', prop: 'sourceFile', component: 'input', placeholder: '文件名', width: '180px' },
{ label: '报价工作表', prop: 'sheetName', component: 'input', placeholder: '工作表', width: '160px' },
@@ -361,8 +343,13 @@ function handleDelete(ids) {
}).catch(() => {})
}
function openRule(selection) {
ruleRef.value?.open(selection || [])
function chargeTypeText(value) {
const hit = (order_charge_type.value || []).find(item => item.value === value)
if (hit) return hit.label
if (value === 'PER_KG') return '常规计费'
if (value === 'FLAT') return '一口价'
if (value === 'EXTRA') return '续重价'
return value || '-'
}
function channelLabel(item) {
@@ -397,7 +384,7 @@ function resetBind() {
function submitBind() {
if (!bindForm.productId) {
proxy.$modal.msgWarning('请选择一个产品')
proxy.$modal.msgWarning('请选择一个应付价卡')
return
}
if (!bindForm.channelIds.length) {
@@ -476,40 +463,6 @@ function termText(row) {
return `${start || '不限'} 至 ${end || '不限'}`
}
function openRuleLog(row) {
ruleLogTitle.value = `${row.productName || '产品'} 第 ${row.versionNo || '-'} 版的附加费配置记录`
ruleLogRows.value = []
ruleLogVisible.value = true
ruleLogLoading.value = true
listPaySurchargeRuleLog(row.productId, row.termId).then(res => {
ruleLogRows.value = res.data || []
}).finally(() => {
ruleLogLoading.value = false
})
}
function ruleLogAction(type) {
if (type === '1') return '新增'
if (type === '2') return '修改'
if (type === '3') return '删除'
return '-'
}
function ruleLogSide(row, side) {
let content = row.changeContent
if (typeof content === 'string') {
try {
content = JSON.parse(content)
} catch (error) {
return side === 'after' ? content : '-'
}
}
const values = content?.[side]
if (!values || typeof values !== 'object') return '-'
const text = Object.entries(values).map(([label, value]) => `${label}:${value}`).join(';')
return text || '-'
}
function openHistory(row) {
historyProductId.value = row.productId
historyTitle.value = `${row.productName || '产品'}的价格版本`
@@ -158,7 +158,7 @@
</el-table-column>
<el-table-column label="金额" min-width="120" align="right">
<template #default="{ row }">
<span class="fee-amount">{{ formatMoney(row.amount) }}</span>
<span class="fee-amount">{{ formatFeeAmount(row.amount) }}</span>
</template>
</el-table-column>
<el-table-column label="币种" width="90" align="center">
@@ -342,6 +342,13 @@ function formatMoney(val) {
return num.toFixed(2)
}
function formatFeeAmount(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
if (Number.isNaN(num)) return val
return num.toFixed(3)
}
function formatWeight(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
@@ -44,7 +44,9 @@
<el-table-column prop="countryName" label="目的国" width="110" show-overflow-tooltip />
<el-table-column prop="channelName" label="渠道" min-width="140" show-overflow-tooltip />
<el-table-column prop="chargeWeight" label="计费重" width="90" align="right" />
<el-table-column prop="payTotal" label="应付总额" width="110" align="right" />
<el-table-column prop="payTotal" label="应付总额" width="110" align="right">
<template #default="{ row }">{{ money2(row.payTotal) }}</template>
</el-table-column>
<el-table-column prop="currency" label="币种" width="80" align="center" />
<el-table-column label="计费状态" width="100" align="center">
<template #default="{ row }">
@@ -92,8 +94,8 @@
</el-table-column>
<el-table-column label="金额" min-width="1" header-align="center" align="right" show-overflow-tooltip>
<template #default="{ row }">
<el-input-number v-if="row.editing" v-model="row.amount" :precision="2" :controls="false" />
<span v-else>{{ row.amount }}</span>
<el-input-number v-if="row.editing" v-model="row.amount" :precision="3" :controls="false" />
<span v-else>{{ money3(row.amount) }}</span>
</template>
</el-table-column>
<el-table-column label="币种" min-width="1" header-align="center" align="center" show-overflow-tooltip>
@@ -113,7 +115,9 @@
<el-table-column label="来源" min-width="1" header-align="center" align="center" show-overflow-tooltip>
<template #default="{ row }">{{ sourceText(row.feeSource) }}</template>
</el-table-column>
<el-table-column prop="createBy" label="创建人" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column label="创建人" min-width="1" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ row.createBy || '-' }}</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column prop="updateBy" label="更新人" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column prop="updateTime" label="更新时间" min-width="1" header-align="center" show-overflow-tooltip />
@@ -241,8 +245,7 @@
</template>
<script setup name="PayOrderList">
import { getBill } from '@/api/price/billing'
import { addPayOrderFee, cancelPayOrderRecalc, getPayOrderRecalcTask, listPayOrder, listPayOrderFeeLogs, listPayOrderFees, pollPayOrderRecalc, removePayOrderFee, submitPayOrderRecalc } from '@/api/price/payOrder'
import { addPayOrderFee, cancelPayOrderRecalc, getPayOrder, getPayOrderRecalcTask, listPayOrder, listPayOrderFeeLogs, listPayOrderFees, pollPayOrderRecalc, removePayOrderFee, submitPayOrderRecalc } from '@/api/price/payOrder'
import { ElMessage, ElMessageBox } from 'element-plus'
import BillDetail from '../components/BillDetail.vue'
@@ -319,6 +322,18 @@ const sources = {
MANUAL: '手工'
}
function money2(value) {
if (value === null || value === undefined || value === '') return '-'
const num = Number(value)
return Number.isNaN(num) ? value : num.toFixed(2)
}
function money3(value) {
if (value === null || value === undefined || value === '') return '-'
const num = Number(value)
return Number.isNaN(num) ? value : num.toFixed(3)
}
function sourceText(value) {
return sources[value] || value || '-'
}
@@ -381,7 +396,7 @@ function openDetail(row) {
detail.value = null
detailOpen.value = true
detailLoading.value = true
getBill(row.billId).then(res => {
getPayOrder(row.billId).then(res => {
detail.value = res.data || null
}).finally(() => {
detailLoading.value = false