diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java index 0644c6e3..d17ed1dd 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java @@ -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 四段返回。 * diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java index a04765c6..5bd2a189 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java @@ -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')") diff --git a/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayTemplateWorkbookTest.java b/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayTemplateWorkbookTest.java new file mode 100644 index 00000000..7fee2bbd --- /dev/null +++ b/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayTemplateWorkbookTest.java @@ -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(); + } + } +} diff --git a/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayWorkbookParserTest.java b/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayWorkbookParserTest.java index f52ae52c..f80affd1 100644 --- a/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayWorkbookParserTest.java +++ b/bms-back/bms-admin/src/test/java/com/bms/price/pay/PayWorkbookParserTest.java @@ -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()) diff --git a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java index 31f00533..44cf65be 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java @@ -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; diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayProduct.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayProduct.java index 5ba18fdc..fb9cb1a1 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayProduct.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayProduct.java @@ -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; diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleLog.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleLog.java deleted file mode 100644 index da3e75be..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleLog.java +++ /dev/null @@ -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; - } -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleSave.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleSave.java deleted file mode 100644 index 1affd297..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PaySurchargeRuleSave.java +++ /dev/null @@ -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 products = new ArrayList<>(); - - private List rules = new ArrayList<>(); - - @Data - public static class PaySurchargeRuleBind - { - private Long productId; - - private Long termId; - - private Integer versionNo; - - private String productName; - } -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/TmsPriceQuoteFeeLine.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/TmsPriceQuoteFeeLine.java index 2ce06d38..7a171e6a 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/TmsPriceQuoteFeeLine.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/TmsPriceQuoteFeeLine.java @@ -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=人工 */ diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleLogMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleLogMapper.java deleted file mode 100644 index d88ca5e5..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleLogMapper.java +++ /dev/null @@ -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 selectByTerm(@Param("productId") Long productId, @Param("termId") Long termId); - - List selectByProductIds(@Param("productIds") List productIds); - - int insertBatch(@Param("list") List list); -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleMapper.java deleted file mode 100644 index daf235a2..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PaySurchargeRuleMapper.java +++ /dev/null @@ -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 selectByProduct(@Param("productId") Long productId, @Param("termId") Long termId); - - List selectByProductId(@Param("productId") Long productId); - - int deleteByTerm(@Param("productId") Long productId, @Param("termId") Long termId); - - int deleteByProductIds(@Param("productIds") List productIds); - - int insertBatch(@Param("list") List rules); -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayChargeMode.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayChargeMode.java new file mode 100644 index 00000000..c50f1f5b --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayChargeMode.java @@ -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(); + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayFeeMoney.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayFeeMoney.java new file mode 100644 index 00000000..0093e46a --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayFeeMoney.java @@ -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; + } + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java index d5e7ab74..431f09da 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java @@ -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 linked = linkedGroups(product); String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked); applyCurrentSurcharge(channel.getId(), product); - List billingRules = product.getBillingRules(); - boolean postcodeOn = ruleOn(billingRules, PaySurchargeRules.POSTCODE); - boolean zoneOn = ruleOn(billingRules, PaySurchargeRules.ZONE); - List remoteHits = prefixRules(billingRules, PaySurchargeRules.POSTCODE) - ? null : remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName()); + List 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 rules = paySurchargeRuleService.listForCalc(priced); - priced.setBillingRules(rules == null ? new ArrayList<>() : rules); - } - - /** - * 这条计费条件是否启用。没有配置行时视为关闭。 - * - * @param rules 当前产品的计费条件 - * @param calcRule 条件编码,如 POSTCODE、ZONE - * @return 有启用行时为 true - */ - private static boolean ruleOn(List 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 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; } /** diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayTemplateWorkbook.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayTemplateWorkbook.java new file mode 100644 index 00000000..ac0e3d9e --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayTemplateWorkbook.java @@ -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 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 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; + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayWorkbookParser.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayWorkbookParser.java index 6b098ba0..0097a018 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayWorkbookParser.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayWorkbookParser.java @@ -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; } /** diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/IPayProductService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayProductService.java index 43d19028..6717f8fe 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/IPayProductService.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayProductService.java @@ -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 listTerms(Long productId); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/IPaySurchargeRuleService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/IPaySurchargeRuleService.java deleted file mode 100644 index f3c82c24..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/IPaySurchargeRuleService.java +++ /dev/null @@ -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 list(Long productId, Long termId); - - /** 计算时读取的条件。先取产品上的一份,没有再取当前生效版本上的。 */ - List listForCalc(PayProduct product); - - /** 覆盖所选产品的配置。不按价格版本各存一份。 */ - void save(PaySurchargeRuleSave command); - - /** 这个产品上的附加费配置操作记录。 */ - List logs(Long productId, Long termId); -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/IPrcOrderBillService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/IPrcOrderBillService.java index 5bd40f39..7808921a 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/IPrcOrderBillService.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/IPrcOrderBillService.java @@ -61,6 +61,9 @@ public interface IPrcOrderBillService TmsPriceQuoteResult getBill(Long billId); + /** 应付列表订单详情。不走计费数据权限,同时带出应收和应付费用。 */ + TmsPriceQuoteResult getPayOrderBill(Long billId); + /** 订单列表弹窗使用的计费失败原因(带数据权限)。 */ OrderBillFailReasonVo getBillingFailReason(Long billId); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java index 0d4dc424..50b66c5e 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java @@ -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 linked = linkedGroups(product); String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked); applyCurrentSurcharge(channel.getId(), product); - List billingRules = product.getBillingRules(); - boolean postcodeOn = ruleOn(billingRules, PaySurchargeRules.POSTCODE); - boolean zoneOn = ruleOn(billingRules, PaySurchargeRules.ZONE); - List remoteHits = null; - if (!hasPrefixRules(billingRules, PaySurchargeRules.POSTCODE)) - { - remoteHits = remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName()); - } + List 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 rules = paySurchargeRuleService.listForCalc(priced); - priced.setBillingRules(rules == null ? new ArrayList<>() : rules); - } - - /** 附加费规则里已经写了邮编前缀时,偏远不再去应付邮编配置里查。 */ - private static boolean hasPrefixRules(List 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 rules, String calcRule) - { - for (PaySurchargeRule rule : rules) - { - if (rule != null && calcRule.equals(rule.getCalcRule()) && !"0".equals(rule.getEnabled())) - { - return true; - } - } - return false; } private List 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 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) { diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java index da17ae3d..d2cc56c1 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java @@ -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); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayProductServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayProductServiceImpl.java index 92a33d0f..1aea910e 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayProductServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayProductServiceImpl.java @@ -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 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); } diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PaySurchargeRuleServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PaySurchargeRuleServiceImpl.java deleted file mode 100644 index 078c9d3a..00000000 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PaySurchargeRuleServiceImpl.java +++ /dev/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 RULES = Set.of("ALWAYS", "POSTCODE", "ZONE", "EXTRA_KG", "WEIGHT", "SIZE", "RETURN"); - - private static final Set 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 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 list(Long productId, Long termId) - { - if (productId == null) - { - return List.of(); - } - return hydrateAll(rulesOf(stableId(productId))); - } - - @Override - public List 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 rules = normalize(command.getRules()); - String operator = SecurityUtils.getUsername(); - Map 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 family = productMapper.selectFamilyIds(stableId); - if (family == null || family.isEmpty()) - { - family = List.of(stableId); - } - List before = hydrateAll(rulesOf(stableId)); - List logs = diffLogs(before, rules, stableId, 0L, null, operator); - ruleMapper.deleteByProductIds(family); - if (!logs.isEmpty()) - { - logMapper.insertBatch(logs); - } - if (rules.isEmpty()) - { - continue; - } - List 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 normalize(List raw) - { - List 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 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 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 logs(Long productId, Long termId) - { - if (productId == null) - { - return List.of(); - } - List family = productMapper.selectFamilyIds(stableId(productId)); - if (family == null || family.isEmpty()) - { - return List.of(); - } - return logMapper.selectByProductIds(family); - } - - /** 产品上的一份。还没迁到产品上时,用当前生效版本里原来那份。 */ - private List rulesOf(Long stableId) - { - List 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 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 hydrateAll(List rows) - { - if (rows == null || rows.isEmpty()) - { - return List.of(); - } - rows.forEach(PaySurchargeRuleServiceImpl::hydrate); - return rows; - } - - private static void hydrate(PaySurchargeRule row) - { - Map detail = parse(row.getRuleDetail()); - if (detail.isEmpty()) - { - detail = legacy(row); - } - row.setDetail(detail.isEmpty() ? null : detail); - } - - private static Map parse(String json) - { - if (json == null || json.isBlank()) - { - return new LinkedHashMap<>(); - } - Map parsed = JSON.parseObject(json, new TypeReference>() { }); - return parsed == null ? new LinkedHashMap<>() : parsed; - } - - /** 还没写明细的旧行,用原来的摘要列带回弹框。 */ - private static Map legacy(PaySurchargeRule row) - { - Map 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 cleanDetail(String calcRule, Map raw) - { - Map 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 detail) - { - return present(detail, "longestMin", "longestMax", "secondMin", "secondMax", "sumMin", "sumMax", - "girthMin", "girthMax", "boxLength", "volumeMin", "volumeMax", "cubicMax", "exceedStepCm"); - } - - private static boolean boxComplete(Map 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 detail, String... keys) - { - for (String key : keys) - { - if (detail.get(key) != null) - { - return true; - } - } - return false; - } - - private static BigDecimal weightMin(String calcRule, Map 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 detail) - { - if ("POSTCODE".equals(calcRule) || "ZONE".equals(calcRule)) - { - List 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 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 labels) - { - String text = text(value); - return text == null ? null : labels.get(text); - } - - private static void checkChoice(Map detail, String key, Set 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 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 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 diffLogs(List before, List after, - Long productId, Long termId, Integer versionNo, String operator) - { - Map> oldRows = keyed(before); - Map> newRows = keyed(after); - List logs = new ArrayList<>(); - for (Map.Entry> entry : newRows.entrySet()) - { - Map previous = oldRows.remove(entry.getKey()); - if (previous == null) - { - logs.add(log(productId, termId, versionNo, "1", entry.getKey(), null, entry.getValue(), operator)); - continue; - } - Map oldChanged = new LinkedHashMap<>(); - Map newChanged = new LinkedHashMap<>(); - Set 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> entry : oldRows.entrySet()) - { - logs.add(log(productId, termId, versionNo, "3", entry.getKey(), entry.getValue(), null, operator)); - } - return logs; - } - - private static Map> keyed(List rules) - { - Map> rows = new LinkedHashMap<>(); - Map index = new LinkedHashMap<>(); - if (rules == null) - { - return rows; - } - for (PaySurchargeRule rule : rules) - { - if (rule == null || rule.getCalcRule() == null) - { - continue; - } - Map 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 filled(PaySurchargeRule rule) - { - Map detail = rule.getDetail() == null ? Map.of() : rule.getDetail(); - Map 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 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 before, Map after, String operator) - { - Map 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; - } -} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java index 0d755e8e..393728f6 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java @@ -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。 */ diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java index 4ae2c953..40627d9c 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java @@ -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 preview(List billCodes) { @@ -106,7 +110,8 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService { List rows = orders.get(fee.getBillCode()); fee.setOrderCount(rows.size()); - List shares = split(fee.getPrice(), rows, true); + BigDecimal cnyPrice = payFeeMoney.toCny(fee.getPrice(), fee.getCurrency(), fee.getCreateTime()); + List 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 split(BigDecimal price, List 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 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); } diff --git a/bms-back/bms-system/src/main/resources/mapper/price/PayOrderListMapper.xml b/bms-back/bms-system/src/main/resources/mapper/price/PayOrderListMapper.xml index 56388106..53c6a5ea 100644 --- a/bms-back/bms-system/src/main/resources/mapper/price/PayOrderListMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/price/PayOrderListMapper.xml @@ -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, diff --git a/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleLogMapper.xml b/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleLogMapper.xml deleted file mode 100644 index 4b7a387a..00000000 --- a/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleLogMapper.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - insert into pay_surcharge_rule_log ( - product_id, term_id, version_no, operation_type, rule_key, change_content, create_by, create_time - ) values - - (#{row.productId}, #{row.termId}, #{row.versionNo}, #{row.operationType}, #{row.ruleKey}, - #{row.changeContent}, #{row.createBy}, sysdate()) - - - - diff --git a/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleMapper.xml b/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleMapper.xml deleted file mode 100644 index 9cabc99c..00000000 --- a/bms-back/bms-system/src/main/resources/mapper/price/PaySurchargeRuleMapper.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - delete from pay_surcharge_rule - where product_id = #{productId} - and term_id = #{termId} - - - - delete from pay_surcharge_rule - where product_id in - #{id} - - - - 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 - - (#{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()) - - - diff --git a/bms-back/bms-system/src/main/resources/mapper/price/PrcOrderBillMapper.xml b/bms-back/bms-system/src/main/resources/mapper/price/PrcOrderBillMapper.xml index 9a16173e..2d168b22 100644 --- a/bms-back/bms-system/src/main/resources/mapper/price/PrcOrderBillMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/price/PrcOrderBillMapper.xml @@ -953,7 +953,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{billId} 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 #{billId} diff --git a/bms-back/bms-system/src/main/resources/mapper/price/PrcPayBillFeeMapper.xml b/bms-back/bms-system/src/main/resources/mapper/price/PrcPayBillFeeMapper.xml index 96e3bd7c..0e81af17 100644 --- a/bms-back/bms-system/src/main/resources/mapper/price/PrcPayBillFeeMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/price/PrcPayBillFeeMapper.xml @@ -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 + + ( + 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 + ) + + 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' diff --git a/bms-back/sql/price/pay_charge_mode.sql b/bms-back/sql/price/pay_charge_mode.sql new file mode 100644 index 00000000..deefccc4 --- /dev/null +++ b/bms-back/sql/price/pay_charge_mode.sql @@ -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 ('续重计费', '续重价'); diff --git a/bms-back/sql/price/pay_charge_mode_menu.sql b/bms-back/sql/price/pay_charge_mode_menu.sql new file mode 100644 index 00000000..7f71fb10 --- /dev/null +++ b/bms-back/sql/price/pay_charge_mode_menu.sql @@ -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); diff --git a/bms-back/sql/price/pay_fee_cny_scale.sql b/bms-back/sql/price/pay_fee_cny_scale.sql new file mode 100644 index 00000000..64ae0bdc --- /dev/null +++ b/bms-back/sql/price/pay_fee_cny_scale.sql @@ -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 '变更后金额'; diff --git a/bms-back/sql/price/pay_surcharge_rule_drop.sql b/bms-back/sql/price/pay_surcharge_rule_drop.sql new file mode 100644 index 00000000..dc2ceac3 --- /dev/null +++ b/bms-back/sql/price/pay_surcharge_rule_drop.sql @@ -0,0 +1,5 @@ +-- 去掉应付附加费配置操作记录表 +DROP TABLE IF EXISTS `bms`.`pay_surcharge_rule_log`; + +-- 去掉应付附加费配置表 +DROP TABLE IF EXISTS `bms`.`pay_surcharge_rule`; diff --git a/bms-front/src/api/price/pay.js b/bms-front/src/api/price/pay.js index 8b7cf41d..7eb9ef32 100644 --- a/bms-front/src/api/price/pay.js +++ b/bms-front/src/api/price/pay.js @@ -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 - }) -} diff --git a/bms-front/src/api/price/payOrder.js b/bms-front/src/api/price/payOrder.js index 32b0e04e..383282c9 100644 --- a/bms-front/src/api/price/payOrder.js +++ b/bms-front/src/api/price/payOrder.js @@ -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', diff --git a/bms-front/src/views/price/basic/pay/components/PayConfigDetail.vue b/bms-front/src/views/price/basic/pay/components/PayConfigDetail.vue index 3fe175c7..5cebdb0c 100644 --- a/bms-front/src/views/price/basic/pay/components/PayConfigDetail.vue +++ b/bms-front/src/views/price/basic/pay/components/PayConfigDetail.vue @@ -6,7 +6,7 @@ {{ pane.item.supplierName || '-' }} {{ pane.item.effectiveDate || '-' }} {{ pane.item.countryScope || '-' }} - {{ pane.item.chargeType || '-' }} + {{ chargeTypeText(pane.item.chargeType) }} {{ pane.item.extraPerKg || '-' }} {{ pane.item.serviceType || '-' }} {{ pane.item.classification || '-' }} @@ -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, diff --git a/bms-front/src/views/price/basic/pay/components/PayCreateDialog.vue b/bms-front/src/views/price/basic/pay/components/PayCreateDialog.vue new file mode 100644 index 00000000..f316b5fb --- /dev/null +++ b/bms-front/src/views/price/basic/pay/components/PayCreateDialog.vue @@ -0,0 +1,290 @@ + + + + + diff --git a/bms-front/src/views/price/basic/pay/components/PayImportDialog.vue b/bms-front/src/views/price/basic/pay/components/PayImportDialog.vue index 701c2960..d36deff7 100644 --- a/bms-front/src/views/price/basic/pay/components/PayImportDialog.vue +++ b/bms-front/src/views/price/basic/pay/components/PayImportDialog.vue @@ -1,7 +1,19 @@ + + - -
比对所选版本 @@ -120,31 +123,12 @@ - - - - - - - - - - - - - - - - - - @@ -221,16 +205,18 @@