31 Commits

Author SHA1 Message Date
caojia b6718f9361 调整命名2 2026-11-11 09:54:09 +08:00
wuweihua a58de9bb7e 修改计费逻辑仅 billing_fail_status = 0 才写 prc_income_bill 2026-11-11 09:49:59 +08:00
wuweihua a211f06663 修改定时任务时间 2026-11-11 09:29:47 +08:00
caojia 41cefd5fd5 调整命名 2026-11-11 00:18:12 +08:00
wuweihua fca999c384 修改比较逻辑 2026-11-10 18:10:10 +08:00
caojia 2e5ab2bfc1 ✅ 跳过依赖本机价卡文件的测试 2026-11-10 18:04:19 +08:00
caojia 3e5ef25153 ✨ 完善应收账单毛利分析与提成展示 2026-11-10 17:37:17 +08:00
caojia 9004a1b921 🔥 删除毛利汇总说明文字 2026-11-10 17:37:17 +08:00
wuweihua cf6b90008d 修改规则 2026-11-10 17:30:11 +08:00
liuminghui fbc138f041 提单费用均摊处理 2026-11-10 17:24:52 +08:00
wuweihua 3c49175cea 增加规则配置 2026-11-10 17:15:38 +08:00
wuweihua f26e03efb1 Merge branch 'test' of https://git.lionquexpress.com/wuweihua/BMS into test 2026-11-10 16:21:16 +08:00
wuweihua 1a0483c7fe 增加一个渠道绑定 2026-11-10 16:21:07 +08:00
liuminghui da9efc422e 提单费用调整 2026-11-10 15:21:03 +08:00
wuweihua e6a9fcf0a2 修改类型 2026-11-10 14:38:38 +08:00
wuweihua de5784cbac 修改打单计费逻辑 2026-11-09 23:38:07 +08:00
wuweihua 16afa0d590 增加一个打单功能套餐 2026-11-09 23:00:48 +08:00
wuweihua 2632e5aa78 渠道管理增加应收关联 2026-11-09 17:27:21 +08:00
liuminghui ace1eb06c0 去除计费列表的多余按钮 2026-11-09 16:15:55 +08:00
liuminghui f31bb4c54d Merge remote-tracking branch 'origin/test' into test 2026-11-09 16:00:23 +08:00
liuminghui b8b943ef51 偏远地区邮编判断调整 2026-11-09 15:58:27 +08:00
caojia f2d27f3502 🔥 移除应收毛利分析冗余展示和筛选 2026-11-09 15:58:14 +08:00
liuminghui 9220696519 Merge branch 'test' into feauture-20261104
# Conflicts:
#	bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcOrderBillMapper.java
2026-11-09 15:37:55 +08:00
wuweihua 8633019788 增加计费日志显示 2026-11-09 14:12:21 +08:00
wuweihua 4148c447fc 修改删除逻辑 2026-11-09 13:39:14 +08:00
caojia 61099b2514 调整模板 2026-11-09 11:24:27 +08:00
caojia 9e3f8314f1 🐛 修正账单预览导出重量精度 2026-11-09 11:24:26 +08:00
caojia 7abb7fdb06 🐛 修正账单预览重量精度显示 2026-11-09 11:24:26 +08:00
caojia cd25055159 ✨ 新增应收账单毛利分析与提成管理 2026-11-09 11:24:26 +08:00
wuweihua 489f99dc7b 合并套餐 2026-11-09 11:09:51 +08:00
wuweihua af3fb0aa2f 修改去空格 2026-11-06 19:27:31 +08:00
218 changed files with 12206 additions and 1164 deletions
@@ -13,13 +13,13 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bms.ar.domain.ArBill;
import com.bms.ar.domain.ArBalanceWriteoff;
import com.bms.ar.domain.vo.ArBillListExportRow;
import com.bms.ar.domain.vo.ArBillQuery;
import com.bms.ar.domain.vo.ArBillSummary;
import com.bms.ar.service.IArBalanceWriteoffService;
import com.bms.ar.service.IArBillService;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.domain.ArBalanceWriteoff;
import com.bms.receivable.domain.vo.ArBillListExportRow;
import com.bms.receivable.domain.vo.ArBillQuery;
import com.bms.receivable.domain.vo.ArBillSummary;
import com.bms.receivable.service.IArBalanceWriteoffService;
import com.bms.receivable.service.IArBillService;
import com.bms.common.annotation.Log;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
@@ -0,0 +1,362 @@
package com.bms.web.controller.price;
import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.bms.common.annotation.Log;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
import com.bms.common.core.page.TableDataInfo;
import com.bms.common.enums.BusinessType;
import com.bms.common.exception.ServiceException;
import com.bms.price.domain.PaySaveCommand;
import com.bms.price.domain.PrcCustomerPriceSet;
import com.bms.price.domain.PrcCustomerPriceSetBatch;
import com.bms.price.domain.PrcPriceSet;
import com.bms.price.service.IPayProductService;
import com.bms.price.service.IPrcPriceSetService;
/**
* 打单套餐:套餐壳 + 应收价卡(pay_*)。
*/
@RestController
@RequestMapping("/price/label")
public class LabelPackageController extends BaseController
{
@Autowired
private IPrcPriceSetService priceSetService;
@Autowired
private IPayProductService payProductService;
@PreAuthorize("@ss.hasPermi('price:label:list')")
@GetMapping("/list")
public TableDataInfo list(PrcPriceSet set)
{
set.setSetCategory(PrcPriceSet.CATEGORY_LABEL);
startPage();
List<PrcPriceSet> list = priceSetService.selectPrcPriceSetList(set);
return getDataTable(list);
}
@PreAuthorize("@ss.hasPermi('price:label:query')")
@GetMapping("/{priceSetId:[0-9]+}")
public AjaxResult getInfo(@PathVariable Long priceSetId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return success(priceSetService.selectPrcPriceSetById(priceSetId));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐基本信息", businessType = BusinessType.UPDATE)
@PutMapping("/basic")
public AjaxResult editBasic(@RequestBody PrcPriceSet set)
{
priceSetService.assertSetCategory(set.getPriceSetId(), PrcPriceSet.CATEGORY_LABEL);
set.setUpdateBy(getUsername());
return toAjax(priceSetService.updateBasicInfo(set));
}
@PreAuthorize("@ss.hasPermi('price:label:audit')")
@Log(title = "打单套餐停用", businessType = BusinessType.UPDATE)
@PutMapping("/{priceSetId}/disable")
public AjaxResult disable(@PathVariable Long priceSetId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return toAjax(priceSetService.disable(priceSetId, getUsername()));
}
@PreAuthorize("@ss.hasPermi('price:label:audit')")
@Log(title = "打单套餐启用", businessType = BusinessType.UPDATE)
@PutMapping("/{priceSetId}/enable")
public AjaxResult enable(@PathVariable Long priceSetId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return toAjax(priceSetService.enable(priceSetId, getUsername()));
}
@PreAuthorize("@ss.hasPermi('price:label:remove')")
@Log(title = "打单套餐删除", businessType = BusinessType.DELETE)
@DeleteMapping("/{priceSetIds}")
public AjaxResult remove(@PathVariable Long[] priceSetIds)
{
if (priceSetIds != null)
{
for (Long id : priceSetIds)
{
priceSetService.assertSetCategory(id, PrcPriceSet.CATEGORY_LABEL);
}
}
return toAjax(priceSetService.deletePrcPriceSetByIds(priceSetIds));
}
@PreAuthorize("@ss.hasPermi('price:label:import')")
@PostMapping("/preview")
public AjaxResult preview(@RequestParam("file") MultipartFile file,
@RequestParam(value = "dictValue", required = false) String dictValue,
@RequestParam(value = "progressId", required = false) String progressId,
@RequestParam(value = "priceSetId", required = false) Long priceSetId) throws Exception
{
if (file == null || file.isEmpty())
{
throw new ServiceException("请上传价卡文件");
}
String name = file.getOriginalFilename();
if (name == null || !name.toLowerCase(Locale.ROOT).endsWith(".xlsx"))
{
throw new ServiceException("请上传xlsx价卡");
}
if (priceSetId != null)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
}
// 打单独立预览:已存在按本套餐判断,不与应付公共模板互挡
return success(payProductService.previewLabel(file.getBytes(), name, dictValue, progressId, priceSetId));
}
@PreAuthorize("@ss.hasPermi('price:label:import')")
@GetMapping("/preview/progress")
public AjaxResult parseProgress(@RequestParam("progressId") String progressId)
{
return success(payProductService.parseProgress(progressId));
}
@PreAuthorize("@ss.hasPermi('price:label:import')")
@Log(title = "打单套餐导入", businessType = BusinessType.IMPORT)
@PostMapping("/importSave")
public AjaxResult importSave(@RequestBody PaySaveCommand command)
{
if (command == null)
{
throw new ServiceException("保存参数不能为空");
}
String message = payProductService.saveLabel(command);
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("message", message);
payload.put("priceSetId", command.getPriceSetId());
return success(payload);
}
@PreAuthorize("@ss.hasPermi('price:label:list')")
@GetMapping("/{priceSetId}/versions")
public AjaxResult versions(@PathVariable Long priceSetId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return success(payProductService.selectLabelVersions(priceSetId));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐启动版本", businessType = BusinessType.UPDATE)
@PutMapping("/{priceSetId}/versions/{versionNo}/activate")
public AjaxResult activateVersion(@PathVariable Long priceSetId, @PathVariable Integer versionNo,
@RequestBody Map<String, Object> body)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
Date effectiveTime = parseEffectiveTime(body == null ? null : body.get("effectiveTime"));
String message = payProductService.activateLabelVersion(priceSetId, versionNo, effectiveTime);
Map<String, Object> payload = new HashMap<String, Object>();
payload.put("message", message);
return success(payload);
}
@PreAuthorize("@ss.hasPermi('price:label:remove')")
@Log(title = "打单套餐删除版本", businessType = BusinessType.DELETE)
@DeleteMapping("/{priceSetId}/versions/{versionNo}")
public AjaxResult deleteVersion(@PathVariable Long priceSetId, @PathVariable Integer versionNo)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return toAjax(payProductService.deleteLabelVersion(priceSetId, versionNo));
}
@PreAuthorize("@ss.hasPermi('price:label:list')")
@GetMapping("/{priceSetId}/products")
public AjaxResult products(@PathVariable Long priceSetId,
@RequestParam(value = "versionNo", required = false) Integer versionNo)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
if (versionNo != null)
{
return success(payProductService.selectLabelProductsByVersion(priceSetId, versionNo));
}
return success(payProductService.selectLabelProducts(priceSetId));
}
@PreAuthorize("@ss.hasPermi('price:label:query')")
@GetMapping("/product/{productId}")
public AjaxResult productDetail(@PathVariable Long productId,
@RequestParam(value = "termId", required = false) Long termId)
{
if (termId != null)
{
return success(payProductService.selectPayProductDetailByTerm(termId));
}
return success(payProductService.selectPayProductDetail(productId));
}
@PreAuthorize("@ss.hasPermi('price:label:remove')")
@Log(title = "打单套餐移除产品", businessType = BusinessType.DELETE)
@DeleteMapping("/{priceSetId}/products/{productIds}")
public AjaxResult removeProducts(@PathVariable Long priceSetId, @PathVariable Long[] productIds)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return toAjax(payProductService.removeLabelProducts(priceSetId, productIds));
}
@PreAuthorize("@ss.hasPermi('price:label:query')")
@GetMapping("/{priceSetId}/channels")
public AjaxResult listChannels(@PathVariable Long priceSetId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return success(payProductService.listLabelChannels(priceSetId));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐绑定渠道", businessType = BusinessType.UPDATE)
@PutMapping("/{priceSetId}/channels")
public AjaxResult bindChannels(@PathVariable Long priceSetId, @RequestBody Map<String, Object> body)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
List<String> channelIds = new ArrayList<String>();
Object rawIds = body == null ? null : body.get("channelIds");
if (rawIds instanceof List<?>)
{
for (Object item : (List<?>) rawIds)
{
if (item != null && !String.valueOf(item).trim().isEmpty())
{
channelIds.add(String.valueOf(item).trim());
}
}
}
Long productId = null;
Object rawProductId = body == null ? null : body.get("productId");
if (rawProductId instanceof Number)
{
productId = ((Number) rawProductId).longValue();
}
else if (rawProductId != null && !String.valueOf(rawProductId).trim().isEmpty()
&& !"null".equalsIgnoreCase(String.valueOf(rawProductId).trim()))
{
productId = Long.valueOf(String.valueOf(rawProductId).trim());
}
return success(payProductService.bindLabelChannels(priceSetId, channelIds, productId));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐解绑渠道", businessType = BusinessType.DELETE)
@DeleteMapping("/{priceSetId}/channels/{channelId}")
public AjaxResult unbindChannel(@PathVariable Long priceSetId, @PathVariable String channelId)
{
priceSetService.assertSetCategory(priceSetId, PrcPriceSet.CATEGORY_LABEL);
return toAjax(payProductService.unbindLabelChannel(priceSetId, channelId));
}
@PreAuthorize("@ss.hasPermi('price:label:list')")
@GetMapping("/customer/list")
public TableDataInfo customerList(PrcCustomerPriceSet customer)
{
if (customer != null && customer.getPriceSetId() != null)
{
priceSetService.assertSetCategory(customer.getPriceSetId(), PrcPriceSet.CATEGORY_LABEL);
}
startPage();
List<PrcCustomerPriceSet> list = priceSetService.selectCustomerList(customer);
return getDataTable(list);
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐客户绑定", businessType = BusinessType.INSERT)
@PostMapping("/customer")
public AjaxResult addCustomer(@RequestBody PrcCustomerPriceSet customer)
{
if (customer == null || customer.getPriceSetId() == null)
{
throw new ServiceException("请选择打单套餐");
}
priceSetService.assertSetCategory(customer.getPriceSetId(), PrcPriceSet.CATEGORY_LABEL);
customer.setCreateBy(getUsername());
return toAjax(priceSetService.insertCustomer(customer));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐客户批量绑定", businessType = BusinessType.INSERT)
@PostMapping("/customer/batch")
public AjaxResult batchAddCustomer(@RequestBody PrcCustomerPriceSetBatch batch)
{
if (batch == null || batch.getPriceSetId() == null)
{
throw new ServiceException("请选择打单套餐");
}
priceSetService.assertSetCategory(batch.getPriceSetId(), PrcPriceSet.CATEGORY_LABEL);
batch.setCreateBy(getUsername());
batch.setUpdateBy(getUsername());
return success(priceSetService.batchInsertCustomers(batch));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐客户绑定", businessType = BusinessType.UPDATE)
@PutMapping("/customer")
public AjaxResult editCustomer(@RequestBody PrcCustomerPriceSet customer)
{
if (customer == null)
{
throw new ServiceException("客户绑定参数不能为空");
}
if (customer.getPriceSetId() != null)
{
priceSetService.assertSetCategory(customer.getPriceSetId(), PrcPriceSet.CATEGORY_LABEL);
}
customer.setUpdateBy(getUsername());
return toAjax(priceSetService.updateCustomer(customer));
}
@PreAuthorize("@ss.hasPermi('price:label:edit')")
@Log(title = "打单套餐客户绑定", businessType = BusinessType.DELETE)
@DeleteMapping("/customer/{customerPricesetIds}")
public AjaxResult removeCustomer(@PathVariable Long[] customerPricesetIds)
{
return toAjax(priceSetService.deleteCustomerByIds(customerPricesetIds));
}
private Date parseEffectiveTime(Object raw)
{
if (raw == null)
{
return null;
}
if (raw instanceof Date)
{
return (Date) raw;
}
String text = String.valueOf(raw).trim();
if (text.isEmpty() || "null".equalsIgnoreCase(text))
{
return null;
}
// 兼容 yyyy-MM-dd / yyyy-MM-dd HH:mm / yyyy-MM-dd HH:mm:ss
if (text.length() >= 16)
{
return com.bms.common.utils.DateUtils.parseDate(text);
}
if (text.length() >= 10)
{
return com.bms.common.utils.DateUtils.parseDate(text.substring(0, 10));
}
return com.bms.common.utils.DateUtils.parseDate(text);
}
}
@@ -27,6 +27,12 @@ public class PayBillController extends BaseController
@Autowired
private IPayBillService payBillService;
/**
* 分页查询应付账单。
*
* @param query 账单号、供应商、状态、币种,空着的条件不过滤
* @return 账单列表,不含费用明细
*/
@PreAuthorize("@ss.hasPermi('price:payBill:list')")
@GetMapping("/list")
public TableDataInfo list(PayBill query)
@@ -36,6 +42,12 @@ public class PayBillController extends BaseController
return getDataTable(list);
}
/**
* 查询一张应付账单的明细和操作日志。
*
* @param billId 应付账单ID
* @return 账单头、费用行和日志
*/
@PreAuthorize("@ss.hasPermi('price:payBill:query')")
@GetMapping("/{billId}")
public AjaxResult detail(@PathVariable Long billId)
@@ -43,6 +55,12 @@ public class PayBillController extends BaseController
return success(payBillService.selectPayBillDetail(billId));
}
/**
* 预览本次能生成账单的订单。只查询,不重算费用,也不写账单。
*
* @param command 查询方式,以及订单号、计费日或提单号
* @return 可生成订单、未找到的单号、已经入账的订单
*/
@PreAuthorize("@ss.hasPermi('price:payBill:query')")
@PostMapping("/preview")
public AjaxResult preview(@RequestBody PayBillCommand command)
@@ -50,6 +68,12 @@ public class PayBillController extends BaseController
return success(payBillService.preview(command));
}
/**
* 生成应付账单。先重算每票订单的尾程应付,再把当时的费用抄进草稿账单。
*
* @param command 供应商,以及按订单号、计费日或提单号划定的范围
* @return 刚生成的草稿账单
*/
@PreAuthorize("@ss.hasPermi('price:payBill:add')")
@PostMapping
public AjaxResult generate(@RequestBody PayBillCommand command)
@@ -57,6 +81,11 @@ public class PayBillController extends BaseController
return success(payBillService.generate(command));
}
/**
* 确认草稿账单。确认后才可以登记付款。
*
* @param billId 应付账单ID
*/
@PreAuthorize("@ss.hasPermi('price:payBill:confirm')")
@PutMapping("/confirm/{billId}")
public AjaxResult confirm(@PathVariable Long billId)
@@ -65,6 +94,11 @@ public class PayBillController extends BaseController
return success();
}
/**
* 把已确认的账单登记为已付款。已付款的账单不能直接作废。
*
* @param billId 应付账单ID
*/
@PreAuthorize("@ss.hasPermi('price:payBill:confirm')")
@PutMapping("/paid/{billId}")
public AjaxResult paid(@PathVariable Long billId)
@@ -73,6 +107,11 @@ public class PayBillController extends BaseController
return success();
}
/**
* 作废应付账单。账单和费用行保留,只改状态并记下作废原因。
*
* @param command 账单ID和作废原因
*/
@PreAuthorize("@ss.hasPermi('price:payBill:void')")
@PutMapping("/void")
public AjaxResult voidBill(@RequestBody PayBillCommand command)
@@ -1,6 +1,8 @@
package com.bms.web.controller.price;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -114,17 +116,18 @@ public class PayProductController extends BaseController
return success(payProductService.selectTemplateOptions(payType));
}
/** 渠道当前价格副本 */
/** 渠道当前价格副本;payType 默认应付 AP */
@PreAuthorize("@ss.hasAnyPermi('price:pay:query,data:serviceChannel:query,data:serviceChannel:edit')")
@GetMapping("/channel/{channelId}")
public AjaxResult channelPrice(@PathVariable String channelId)
public AjaxResult channelPrice(@PathVariable String channelId,
@RequestParam(value = "payType", required = false) String payType)
{
return success(payProductService.selectChannelPrice(channelId));
return success(payProductService.selectChannelPrice(channelId, payType));
}
/** 渠道只绑定产品编号,以后按有效期取价 */
/** 渠道只绑定产品编号,以后按有效期取价;支持应收 AR 与应付 AP */
@PreAuthorize("@ss.hasAnyPermi('price:pay:edit,data:serviceChannel:edit')")
@Log(title = "渠道应付产品", businessType = BusinessType.UPDATE)
@Log(title = "渠道产品绑定", businessType = BusinessType.UPDATE)
@PutMapping("/channel/{channelId}/bind")
public AjaxResult bindChannel(@PathVariable String channelId, @RequestBody ChannelProductMap link)
{
@@ -134,8 +137,31 @@ public class PayProductController extends BaseController
payProductService.unbindChannel(channelId, payType);
return success();
}
payProductService.bindChannel(channelId, link.getProductId(), link.getPriceSetId(), payType);
return success(payProductService.selectChannelPrice(channelId));
payProductService.bindChannel(channelId, link.getProductId(), payType);
return success(payProductService.selectChannelPrice(channelId, payType));
}
/** 批量绑定渠道应收/应付产品 */
@PreAuthorize("@ss.hasAnyPermi('price:pay:edit,data:serviceChannel:edit')")
@Log(title = "渠道批量绑定产品", businessType = BusinessType.UPDATE)
@PutMapping("/channel/batchBind")
public AjaxResult batchBindChannel(@RequestBody Map<String, Object> body)
{
List<String> channelIds = new ArrayList<String>();
Object rawIds = body == null ? null : body.get("channelIds");
if (rawIds instanceof List<?>)
{
for (Object item : (List<?>) rawIds)
{
if (item != null && !String.valueOf(item).trim().isEmpty())
{
channelIds.add(String.valueOf(item).trim());
}
}
}
Long apProductId = toLong(body == null ? null : body.get("apProductId"));
Long arProductId = toLong(body == null ? null : body.get("arProductId"));
return success(payProductService.batchBindChannel(channelIds, apProductId, arProductId));
}
/** 对照两个价格版本 */
@@ -246,4 +272,22 @@ public class PayProductController extends BaseController
throw new ServiceException("价卡文件不能超过30MB");
}
}
private Long toLong(Object raw)
{
if (raw == null)
{
return null;
}
if (raw instanceof Number)
{
return ((Number) raw).longValue();
}
String text = String.valueOf(raw).trim();
if (text.isEmpty() || "null".equalsIgnoreCase(text))
{
return null;
}
return Long.valueOf(text);
}
}
@@ -16,10 +16,12 @@ import com.bms.common.core.domain.AjaxResult;
import com.bms.common.core.page.TableDataInfo;
import com.bms.common.enums.BusinessType;
import com.bms.common.utils.StringUtils;
import com.bms.price.airbill.domain.SrvBillAirAllocCommand;
import com.bms.price.airbill.domain.SrvBillAirFeeLog;
import com.bms.price.airbill.domain.SrvBillAirFeeSave;
import com.bms.price.domain.vo.SrvBillAirQuery;
import com.bms.price.domain.vo.SrvBillAirVo;
import com.bms.price.service.ISrvBillAirAllocService;
import com.bms.price.service.ISrvBillAirFeeService;
import com.bms.price.service.ISrvBillAirService;
@@ -36,6 +38,9 @@ public class SrvBillAirController extends BaseController
@Autowired
private ISrvBillAirFeeService srvBillAirFeeService;
@Autowired
private ISrvBillAirAllocService srvBillAirAllocService;
/**
* 提单列表
*/
@@ -94,4 +99,57 @@ public class SrvBillAirController extends BaseController
{
return success(srvBillAirFeeService.save(command));
}
/** 已分摊的费用改为已确定 */
@PreAuthorize("@ss.hasPermi('price:airBill:feeConfirm')")
@Log(title = "提单费用确定", businessType = BusinessType.UPDATE)
@PostMapping("/fee/confirm")
public AjaxResult confirmFee(@RequestParam("billCode") String billCode, @RequestParam("feeId") Long feeId)
{
return success(srvBillAirFeeService.confirm(billCode, feeId));
}
/** 作废已分摊或已确定的费用,并逻辑删除已分摊到订单的明细 */
@PreAuthorize("@ss.hasPermi('price:airBill:feeVoid')")
@Log(title = "提单费用作废", businessType = BusinessType.DELETE)
@PostMapping("/fee/void")
public AjaxResult voidFee(@RequestParam("billCode") String billCode, @RequestParam("feeId") Long feeId)
{
return success(srvBillAirFeeService.voidFee(billCode, feeId));
}
/** 勾选提单后,查出需要分摊到订单的费用 */
@PreAuthorize("@ss.hasPermi('price:airBill:fee')")
@GetMapping("/fee/alloc/preview")
public AjaxResult allocPreview(@RequestParam("billCodes") String billCodes)
{
return success(srvBillAirAllocService.preview(splitCodes(billCodes)));
}
/** 按重量或订单数把费用分摊到订单,并把费用状态改为已分摊 */
@PreAuthorize("@ss.hasPermi('price:airBill:fee')")
@Log(title = "提单费用分摊", businessType = BusinessType.UPDATE)
@PostMapping("/fee/alloc")
public AjaxResult allocate(@RequestBody SrvBillAirAllocCommand command)
{
List<String> billCodes = command == null ? null : command.getBillCodes();
return success(srvBillAirAllocService.allocate(billCodes));
}
private static List<String> splitCodes(String billCodes)
{
List<String> codes = new ArrayList<>();
if (StringUtils.isEmpty(billCodes))
{
return codes;
}
for (String part : billCodes.split("[,,\\s]+"))
{
if (StringUtils.isNotEmpty(part))
{
codes.add(part.trim());
}
}
return codes;
}
}
@@ -72,7 +72,9 @@ public class SurchargeController extends BaseController
*/
@PreAuthorize("@ss.hasPermi('price:surcharge:list') or @ss.hasPermi('price:surcharge:query')"
+ " or @ss.hasPermi('price:set:query') or @ss.hasPermi('price:set:add') or @ss.hasPermi('price:set:edit')"
+ " or @ss.hasPermi('price:billing:bill')")
+ " or @ss.hasPermi('price:billing:bill')"
+ " or @ss.hasPermi('price:pay:query') or @ss.hasPermi('price:pay:edit') or @ss.hasPermi('price:pay:import')"
+ " or @ss.hasPermi('price:airBill:fee')")
@GetMapping("/options")
public AjaxResult listOptions(PrcSurcharge surcharge)
{
@@ -1,4 +1,4 @@
package com.bms.web.controller.ar;
package com.bms.web.controller.receivable;
import java.util.List;
@@ -7,8 +7,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.bms.ar.domain.ArBankAccount;
import com.bms.ar.service.IArBillService;
import com.bms.receivable.domain.ArBankAccount;
import com.bms.receivable.service.IArBillService;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
@@ -1,4 +1,4 @@
package com.bms.web.controller.ar;
package com.bms.web.controller.receivable;
import java.util.ArrayList;
import java.util.List;
@@ -23,21 +23,20 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.bms.ar.domain.ArBill;
import com.bms.ar.domain.ArBankAccount;
import com.bms.ar.domain.ArBillDetailFee;
import com.bms.ar.domain.ArBillExport;
import com.bms.ar.domain.ArBillGenerateTask;
import com.bms.ar.domain.ArBillLog;
import com.bms.ar.domain.vo.ArBillActionRequest;
import com.bms.ar.domain.vo.ArBillGenerateQuery;
import com.bms.ar.domain.vo.ArBillGeneratePreviewExportRow;
import com.bms.ar.domain.vo.ArBillGenerateRequest;
import com.bms.ar.domain.vo.ArBillListExportRow;
import com.bms.ar.domain.vo.ArBillQuery;
import com.bms.ar.enums.ArBillDateType;
import com.bms.ar.service.IArBillService;
import com.bms.ar.security.ArBillScopeResolver;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.domain.ArBankAccount;
import com.bms.receivable.domain.ArBillDetailFee;
import com.bms.receivable.domain.ArBillGenerateTask;
import com.bms.receivable.domain.ArBillLog;
import com.bms.receivable.domain.vo.ArBillActionRequest;
import com.bms.receivable.domain.vo.ArBillGenerateQuery;
import com.bms.receivable.domain.vo.ArBillGeneratePreviewExportRow;
import com.bms.receivable.domain.vo.ArBillGenerateRequest;
import com.bms.receivable.domain.vo.ArBillListExportRow;
import com.bms.receivable.domain.vo.ArBillQuery;
import com.bms.receivable.enums.ArBillDateType;
import com.bms.receivable.service.IArBillService;
import com.bms.receivable.security.ArBillScopeResolver;
import com.bms.common.annotation.Log;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
@@ -1,4 +1,4 @@
package com.bms.web.controller.ar;
package com.bms.web.controller.receivable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@@ -12,9 +12,8 @@ import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bms.ar.domain.ArBalanceWriteoff;
import com.bms.ar.domain.ArBill;
import com.bms.ar.service.IArBalanceWriteoffService;
import com.bms.receivable.domain.ArBalanceWriteoff;
import com.bms.receivable.service.IArBalanceWriteoffService;
import com.bms.common.annotation.Log;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
@@ -0,0 +1,135 @@
package com.bms.web.controller.report;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bms.receivable.profit.ArCommissionRate;
import com.bms.receivable.profit.ArCommissionService;
import com.bms.receivable.profit.ArProfitQuery;
import com.bms.receivable.profit.ArProfitService;
import com.bms.receivable.profit.ArWriteoffRate;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import jakarta.servlet.http.HttpServletResponse;
import com.bms.receivable.profit.ArProfitRow;
import com.bms.receivable.profit.ArCommissionResult;
import com.bms.common.utils.poi.ExcelUtil;
import com.bms.price.enums.ProfitAreaRule;
import com.bms.common.annotation.Log;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
import com.bms.common.core.page.TableDataInfo;
import com.bms.common.enums.BusinessType;
@RestController
@RequestMapping("/report/ar-profit")
public class ArProfitController extends BaseController
{
private final ArProfitService report;
private final ArCommissionService commissions;
public ArProfitController(ArProfitService report, ArCommissionService commissions)
{
this.report = report;
this.commissions = commissions;
}
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/summary")
public AjaxResult summary(ArProfitQuery query) { return success(report.selectSummary(query)); }
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/sales-options")
public AjaxResult salesOptions(@RequestParam(required = false) String keyword) { return success(report.selectSalesOptions(keyword)); }
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/area-rules")
public AjaxResult areaRules() { return success(ProfitAreaRule.areaRules()); }
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/orders/{detailId}/fees")
public AjaxResult fees(@PathVariable Long detailId) { return success(report.selectFees(detailId)); }
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/bills/{billId}/details")
public TableDataInfo billDetails(@PathVariable Long billId)
{
startPage();
return getDataTable(report.selectBillDetails(billId));
}
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/bills")
public TableDataInfo bills(ArProfitQuery query)
{
startPage();
return getDataTable(report.selectBills(query));
}
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@GetMapping("/rates")
public AjaxResult rates() { return success(commissions.selectRates()); }
@Log(title = "账单毛利提成比例", businessType = BusinessType.INSERT)
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@PostMapping("/rates")
public AjaxResult addRate(@RequestBody ArCommissionRate rate)
{
commissions.addRate(rate);
return success();
}
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@GetMapping("/writeoffs/missing-rates")
public TableDataInfo missingRates()
{
startPage();
return getDataTable(commissions.missingRates());
}
@Log(title = "历史核销提成比例确认", businessType = BusinessType.UPDATE)
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@PostMapping("/writeoffs/confirm-rate")
public AjaxResult confirmRate(@RequestBody ArWriteoffRate input)
{
commissions.confirmMissingRate(input);
return success();
}
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/commissions")
public TableDataInfo commissions(@RequestParam(required = false) Long billId,
@RequestParam(defaultValue = "false") boolean includeReversed)
{
startPage();
return getDataTable(commissions.results(billId, includeReversed));
}
@PreAuthorize("@ss.hasPermi('report:arProfit:list')")
@GetMapping("/commissions/summary")
public AjaxResult commissionSummary(@RequestParam(required = false) Long billId) { return success(commissions.summary(billId)); }
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@GetMapping("/commissions/{billId}/writeoffs")
public AjaxResult commissionWriteoffs(@PathVariable Long billId) { return success(commissions.writeoffRates(billId)); }
@Log(title = "应收账单提成明细", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('report:arProfit:commission')")
@PostMapping("/commissions/export")
public void exportCommissions(HttpServletResponse response, @RequestParam(required = false) Long billId)
{
new ExcelUtil<>(ArCommissionResult.class).exportExcel(response, commissions.exportResults(billId), "应收账单提成明细");
}
@Log(title = "应收账单毛利分析", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('report:arProfit:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, ArProfitQuery query)
{
ExcelUtil<ArProfitRow> excel = new ExcelUtil<>(ArProfitRow.class);
excel.exportExcel(response, report.selectBills(query), "应收账单毛利分析");
}
}
@@ -42,14 +42,14 @@ bms:
order-source-sync-threads: 16
# Order-list local rebill workers (2~24). Pair with Druid maxActive >= threads + 8.
local-rebill-threads: 16
# Night auto-rebill: hours 0-8, pull 500 (all statuses) -> bill -> next 500 until empty / 09:00.
# Empty page => no billing.
# Auto-rebill: every hour all day, pull 500 (all statuses) -> bill -> next 500 until empty.
# Empty page => no billing. Window [start-hour, end-hour).
night-retry:
enabled: true
start-hour: 0
end-hour: 9
end-hour: 24
batch-size: 500
cron: "0 0/1 0-8 * * ?"
cron: "0 0 * * * ?"
oracle:
# SLAVE datasource Oracle main-order table (schema.table allowed)
order-table: WEISHI_USER.TAB_ORDER
@@ -1,12 +1,15 @@
package com.bms.price.pay;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.bms.price.domain.PayOrderCostResult;
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.PayWeightBand;
@@ -113,6 +116,133 @@ class PayCostCalculatorTest
assertTrue(hasFee(result, "基础运费", "1.57"));
}
@Test
void remoteZoneUsesMainlandFreightAndItsOwnSurcharge()
{
PayProduct product = new PayProduct();
product.setProductName("Evri 48H");
product.setCurrency("GBP");
product.setWeightBands(new ArrayList<>(List.of(
band("0", "1", "1.51", "UK Mainland"),
band("1", "2", "1.72", "UK Mainland"))));
PaySurcharge light = fee(1L, "偏远附加费", "5.95", "GBP", "ZONE", null);
light.setZoneName("Highlands& Islands");
light.setWeightMin(BigDecimal.ZERO);
light.setWeightMax(BigDecimal.ONE);
PaySurcharge heavy = fee(2L, "偏远附加费", "6.20", "GBP", "ZONE", null);
heavy.setZoneName("Highlands& Islands");
heavy.setWeightMin(BigDecimal.ONE);
heavy.setWeightMax(new BigDecimal("2"));
product.setSurcharges(List.of(light, heavy));
PayOrderCostResult remote = PayCostCalculator.calculate(product, new BigDecimal("0.5"),
null, null, null, "IV1 1AA", "Highlands& Islands", null, 1);
assertTrue(hasFee(remote, "基础运费", "1.51"));
assertTrue(hasFee(remote, "偏远附加费", "5.95"));
assertEquals(1, remote.getFees().stream().filter(fee -> "偏远附加费".equals(fee.getFeeName())).count());
PayOrderCostResult mainland = PayCostCalculator.calculate(product, new BigDecimal("0.5"),
null, null, null, "LL22 8PJ", "UK Mainland", null, 1);
assertTrue(hasFee(mainland, "基础运费", "1.51"));
assertTrue(mainland.getFees().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName())));
}
@Test
void spanishPrefixChargesFirstWeightThenExtraKg()
{
PayProduct product = new PayProduct();
product.setProductName("CTT 48H");
product.setCurrency("EUR");
product.setWeightBands(new ArrayList<>(List.of(band("0", "5", "2.05", "马德里"))));
PaySurcharge first = fee(1L, "偏远附加费", "7.1", "EUR", "POSTCODE", "07");
first.setZoneName("Balearic Islands");
first.setPostcodeParam("07");
first.setWeightMin(BigDecimal.ZERO);
first.setWeightMax(BigDecimal.ONE);
PaySurcharge extra = fee(2L, "偏远附加费", "4", "EUR", "EXTRA_KG", "1");
extra.setZoneName("Balearic Islands");
extra.setPostcodeParam("07");
extra.setPriceUnit("EUR/KG");
product.setSurcharges(List.of(first, extra));
PayOrderCostResult light = PayCostCalculator.calculate(product, new BigDecimal("0.8"),
null, null, null, "07008", "马德里", null, 1);
assertTrue(hasFee(light, "基础运费", "2.05"));
assertTrue(hasFee(light, "偏远附加费", "7.1"));
assertEquals(1, light.getFees().stream().filter(fee -> "偏远附加费".equals(fee.getFeeName())).count());
PayOrderCostResult heavy = PayCostCalculator.calculate(product, new BigDecimal("3"),
null, null, null, "07008", "马德里", null, 1);
assertTrue(hasFee(heavy, "基础运费", "2.05"));
assertTrue(hasFee(heavy, "偏远附加费", "7.1"));
assertTrue(hasFee(heavy, "偏远附加费", "8"));
PayOrderCostResult mainland = PayCostCalculator.calculate(product, new BigDecimal("3"),
null, null, null, "28001", "马德里", null, 1);
assertTrue(mainland.getFees().stream().noneMatch(fee -> "偏远附加费".equals(fee.getFeeName())));
assertTrue(PaySurchargeRules.matchesPostcode("07,35,38,51,52,9", "35001"));
assertTrue(PaySurchargeRules.matchesPostcode("07,35,38,51,52,9", "9000"));
assertFalse(PaySurchargeRules.matchesPostcode("07,35,38,51,52,9", "28001"));
assertTrue(PaySurchargeRules.matchesPostcode("IV,HS,KA27-28", "KA27 8AA"));
assertEquals("07", PaySurchargeRules.remotePrefixes("Balearic Islands 07邮编开头"));
assertEquals("35,38", PaySurchargeRules.remotePrefixes("Canary Islands 35、38邮编开头"));
assertEquals("9", PaySurchargeRules.remotePrefixes("Portuguese Island 9邮编开头"));
assertEquals("", PaySurchargeRules.remotePrefixes("岛屿邮编地区"));
}
@Test
void productPostcodeBookChoosesTheMatchingRemoteFee()
{
List<PayRemoteBook.Hit> hits = List.of(new PayRemoteBook.Hit("偏远附加费", new BigDecimal("1.80"), "", "Highlands"));
PayOrderCostResult result = PayCostCalculator.calculate(royalMail(), new BigDecimal("4"),
null, null, null, "IV1 1AA", null, null, 1, hits);
assertTrue(hasFee(result, "偏远地区附加费", "1.80"));
assertTrue(result.getFees().stream().noneMatch(fee -> "偏远地区附加费".equals(fee.getFeeName())
&& fee.getAmount().compareTo(new BigDecimal("1.00")) == 0));
}
@Test
void linkedRemoteBookWithoutAHitDoesNotUseThePriceCardList()
{
PayOrderCostResult result = PayCostCalculator.calculate(royalMail(), new BigDecimal("4"),
null, null, null, "IV1 1AA", null, null, 1, List.of());
assertTrue(result.getFees().stream().noneMatch(fee -> fee.getFeeName().contains("偏远")));
assertTrue(hasFee(result, "基础运费", "1.62"));
}
@Test
void remoteBookChargesAManualIslandFeeAndPerKg()
{
PayProduct product = new PayProduct();
product.setProductName("德国DPD挂号-国际件");
product.setCurrency("EUR");
product.setWeightBands(new ArrayList<>(List.of(band("0", "5", "3.20", ""))));
PaySurcharge island = fee(31L, "岛屿附加费", "12", "EUR", "MANUAL", null);
PaySurcharge perKg = fee(32L, "偏远附加费", "0.35", "EUR", "MANUAL", null);
perKg.setPriceUnit("EUR/KG");
product.setSurcharges(List.of(island, perKg));
List<PayRemoteBook.Hit> hits = List.of(new PayRemoteBook.Hit("", null, "", "岛屿"));
PayOrderCostResult result = PayCostCalculator.calculate(product, new BigDecimal("2"),
null, null, null, "1234", null, null, 1, hits);
assertTrue(hasFee(result, "岛屿附加费", "12"));
assertTrue(hasFee(result, "偏远附加费", "0.70"));
}
@Test
void remoteHitsFollowTheProductGroupAndCountry()
{
PayPostcodeGroup germany = group(44L, "西班牙GLS", "REMOTE", "", "DE");
PayPostcodeGroup france = group(45L, "西班牙GLS", "REMOTE", "", "FR");
PayPostcodeLine berlin = line(44L, "10115");
PayPostcodeLine paris = line(45L, "75001");
List<PayRemoteBook.Hit> de = PayRemoteBook.hits(List.of(germany, france), List.of(berlin, paris), "10115", "DE", "德国");
assertEquals(1, de.size());
List<PayRemoteBook.Hit> none = PayRemoteBook.hits(List.of(germany, france), List.of(berlin, paris), "28001", "ES", "西班牙");
assertTrue(none.isEmpty());
PayPostcodeGroup delivery = group(42L, "西班牙CTT", "", "", "ES");
assertTrue(PayRemoteBook.hits(List.of(delivery), List.of(line(42L, "28001")), "28001", "ES", "西班牙") == null);
}
@Test
void severalZonesCannotBePricedFromTheOrder()
{
@@ -192,6 +322,26 @@ class PayCostCalculatorTest
return band;
}
private static PayPostcodeGroup group(Long id, String quoteSheet, String coverage, String feeName, String country)
{
PayPostcodeGroup group = new PayPostcodeGroup();
group.setGroupId(id);
group.setQuoteSheet(quoteSheet);
group.setCoverage(coverage);
group.setFeeName(feeName);
group.setCountryCode(country);
group.setConfigKind("ZONE");
return group;
}
private static PayPostcodeLine line(Long groupId, String postcode)
{
PayPostcodeLine line = new PayPostcodeLine();
line.setGroupId(groupId);
line.setPostcode(postcode);
return line;
}
private static PaySurcharge fee(Long id, String name, String amount, String currency, String rule, String param)
{
PaySurcharge fee = new PaySurcharge();
@@ -7,6 +7,7 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.bms.price.domain.PayPostcodeGroup;
@@ -18,6 +19,7 @@ class PayPostcodeImporterTest
private final PayPostcodeImporter importer = new PayPostcodeImporter();
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void stripsStarAndMergesSameFee() throws Exception
{
List<PayPostcodeGroup> groups = importer.parse(Files.readAllBytes(file("32、")), "32.xlsx");
@@ -88,6 +90,7 @@ class PayPostcodeImporterTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void reachableUnreachableAndRemoteKeepTheirOwnCountry() throws Exception
{
List<PayPostcodeGroup> may = importer.parse(Files.readAllBytes(file("20、")), "20.xlsx");
@@ -8,6 +8,7 @@ import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayPreview;
@@ -23,6 +24,7 @@ class PayWorkbookParserTest
private final PayWorkbookParser parser = new PayWorkbookParser();
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void octoberCatalogKeepsTwelveProductSheets() throws Exception
{
PayPreview preview = parse("9、");
@@ -36,6 +38,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void mayCardReadsDhlAndDpdWithoutZoneSheets() throws Exception
{
PayPreview preview = parse("8、");
@@ -88,6 +91,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void upsZonesStayLeftToRightAndColissimoFuelIsMarked() throws Exception
{
PayPreview preview = parse("32、");
@@ -148,6 +152,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void imilePostcodesResolveZoneAndGermanCoverage() throws Exception
{
PayPreview preview = parse("32、");
@@ -168,6 +173,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void gweFileOverridesOnlyPanEuroSupplier() throws Exception
{
PayPreview preview = parse("8.1");
@@ -182,6 +188,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void wholeWorkbookPreviewSerializes() throws Exception
{
PayPreview preview = parse("9、");
@@ -191,6 +198,7 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/应付供应商 下的价卡文件,未随项目提供")
void yideCatalogIncludesPostcodeProducts() throws Exception
{
PayPreview preview = parse("26、");
@@ -204,7 +212,7 @@ class PayWorkbookParserTest
@Test
void dictMatchReadsNamedSheetAndSkipsOthers() throws Exception
{
Path file = Path.of("D:/payment/Evri 48H.xlsx");
Path file = priceCard("Evri 48H.xlsx");
Assumptions.assumeTrue(Files.exists(file));
PayPreview preview = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(), "Evri 48H",
List.of("Evri 48H", "DHL Paket"));
@@ -213,6 +221,14 @@ class PayWorkbookParserTest
assertEquals("Evri 48H", evri.getDictValue());
assertEquals("Evri 48H", evri.getSheetName());
assertFalse(evri.getWeightBands().isEmpty());
assertTrue(evri.getWeightBands().stream().allMatch(band -> "派送费".equals(band.getChargeName())));
assertTrue(evri.getWeightBands().stream().noneMatch(band -> bandText(band).contains("偏远") || bandText(band).contains("Highlands")));
assertTrue(evri.getWeightBands().stream().anyMatch(band -> decimal(band, "1.51") && band.getZoneName().contains("Mainland")));
PaySurcharge highlands = evri.getSurcharges().stream()
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Highlands") && decimalFee(fee, "5.95"))
.findFirst().orElseThrow();
assertEquals("ZONE", highlands.getCalcRule());
assertTrue(highlands.getWeightMax() != null && highlands.getWeightMax().compareTo(java.math.BigDecimal.ONE) == 0);
}
@Test
@@ -280,7 +296,7 @@ class PayWorkbookParserTest
@Test
void royalMailReadsRemoteAreaTableAndSkipsRemarks() throws Exception
{
Path file = Path.of("D:/payment/英国RM.xlsx");
Path file = priceCard("英国RM.xlsx");
Assumptions.assumeTrue(Files.exists(file));
PayPreview preview = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(), "英国RM", List.of("英国RM"));
assertEquals(1, preview.getProducts().size());
@@ -318,6 +334,21 @@ class PayWorkbookParserTest
assertTrue(rm.getExtraLines().isEmpty());
}
@Test
void royalMail48hRemoteRowsMatchPostcodePrefixes() throws Exception
{
Path file = priceCard("Royal Mail 48H.xlsx");
Assumptions.assumeTrue(Files.exists(file));
PayProduct rm = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(), "Royal Mail 48H",
List.of("Royal Mail 48H")).getProducts().get(0);
List<PaySurcharge> remote = rm.getSurcharges().stream().filter(fee -> fee.getFeeName() != null && fee.getFeeName().contains("偏远")).toList();
assertFalse(remote.isEmpty(), rm.getSurcharges().stream().map(fee -> fee.getFeeName() + "/" + fee.getCalcRule() + "/" + fee.getCalcParam()).toList().toString());
assertTrue(remote.stream().allMatch(fee -> "POSTCODE".equals(fee.getCalcRule())),
remote.stream().map(fee -> fee.getFeeName() + "/" + fee.getCalcParam() + "/" + fee.getFeeDesc()).toList().toString());
assertTrue(remote.stream().anyMatch(fee -> fee.getCalcParam() != null && fee.getCalcParam().contains("IV") && !fee.getCalcParam().contains("邮编")));
assertTrue(rm.getWeightBands().stream().noneMatch(band -> bandText(band).contains("偏远")));
}
@Test
void evriOtherFeesKeepOneRowPerRegion() throws Exception
{
@@ -416,9 +447,10 @@ class PayWorkbookParserTest
}
@Test
@Disabled("依赖开发机 D:/payment 下的 CTT 48H.xlsx 价卡文件,未随项目提供")
void ctt48hFileKeepsSurchargeTablesOutOfWeightBands() throws Exception
{
Path file = Path.of("D:/payment/CTT 48H.xlsx");
Path file = priceCard("CTT 48H.xlsx");
PayPreview preview = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(), "CTT 48H",
List.of("CTT 48H"));
PayProduct ctt = preview.getProducts().get(0);
@@ -431,8 +463,17 @@ class PayWorkbookParserTest
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Balearic") && decimalFee(fee, "7.1"))
.findFirst().orElseThrow();
assertTrue(balearic.getFeeDesc().contains("首重"));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> "偏远附加费".equals(fee.getFeeName())
&& fee.getZoneName().contains("Canary") && decimalFee(fee, "4.5") && fee.getChargeText().contains("KG")));
assertEquals("POSTCODE", balearic.getCalcRule());
assertTrue(balearic.getCalcParam() != null && balearic.getCalcParam().contains("07"));
assertTrue(balearic.getWeightMax() != null && balearic.getWeightMax().compareTo(new java.math.BigDecimal("1")) == 0);
PaySurcharge canary = ctt.getSurcharges().stream()
.filter(fee -> "偏远附加费".equals(fee.getFeeName()) && fee.getZoneName().contains("Canary") && decimalFee(fee, "4.5")
&& fee.getChargeText().contains("KG"))
.findFirst().orElseThrow();
assertEquals("EXTRA_KG", canary.getCalcRule());
assertEquals("1", canary.getCalcParam());
assertTrue(canary.getPostcodeParam() != null && canary.getPostcodeParam().contains("35") && canary.getPostcodeParam().contains("38"));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费") && "MANUAL".equals(fee.getCalcRule())));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费") && decimalFee(fee, "0.09")));
assertTrue(ctt.getSurcharges().stream().anyMatch(fee -> fee.getFeeName().contains("额外线路运输费")
&& fee.getFeeDesc().contains("800公里")));
@@ -442,7 +483,7 @@ class PayWorkbookParserTest
@Test
void spainCttMainlandReadsBillableConcepts() throws Exception
{
Path file = Path.of("D:/payment/西班牙CTT带电专线(主要地区).xlsx");
Path file = priceCard("西班牙CTT带电专线(主要地区).xlsx");
Assumptions.assumeTrue(Files.exists(file));
PayPreview preview = parser.parseMatched(Files.readAllBytes(file), file.getFileName().toString(),
"西班牙CTT带电专线(主要地区)", List.of("西班牙CTT带电专线(主要地区)"));
@@ -711,6 +752,16 @@ class PayWorkbookParserTest
return fee.getAmount() != null && fee.getAmount().compareTo(new java.math.BigDecimal(amount)) == 0;
}
private static Path priceCard(String name)
{
Path current = Path.of("D:/A-payment").resolve(name);
if (Files.exists(current))
{
return current;
}
return Path.of("D:/payment").resolve(name);
}
private String bandText(PayWeightBand band)
{
return (band.getChargeName() == null ? "" : band.getChargeName()) + " "
@@ -0,0 +1,125 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import com.bms.receivable.domain.ArBalanceWriteoff;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.mapper.ArCommissionMapper;
import com.bms.receivable.profit.ArCommissionRate;
import com.bms.receivable.profit.ArCommissionResult;
import com.bms.receivable.profit.ArCommissionService;
import com.bms.receivable.profit.ArProfitScope;
import com.bms.receivable.profit.ArProfitScopeResolver;
import com.bms.common.exception.ServiceException;
class ArCommissionServiceTest
{
@Test
void commissionReadsUseServerResolvedScopeAndManagementRemainsRestricted()
{
AtomicReference<ArProfitScope> actorScope = new AtomicReference<>(new ArProfitScope(false, true, false, 7L, 10L));
AtomicReference<Object[]> selected = new AtomicReference<>();
ArProfitScopeResolver resolver = new ArProfitScopeResolver() {
@Override public ArProfitScope resolve() { return actorScope.get(); }
};
ArCommissionMapper mapper = (ArCommissionMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] { ArCommissionMapper.class }, (proxy, method, args) -> {
if ("selectResults".equals(method.getName()) || "selectCommissionSummary".equals(method.getName())) {
selected.set(args.clone());
return List.of();
}
throw new AssertionError(method.getName());
});
ArCommissionService service = new ArCommissionService(mapper, resolver, null, null);
service.results(999L, true);
assertEquals(999L, selected.get()[0]);
assertSame(actorScope.get(), selected.get()[2]);
service.summary(999L);
assertSame(actorScope.get(), selected.get()[1]);
assertThrows(ServiceException.class, service::selectRates);
assertThrows(ServiceException.class, service::missingRates);
assertThrows(ServiceException.class, () -> service.exportResults(null));
actorScope.set(new ArProfitScope(false, false, true, 8L, 10L));
service.results(null, false);
assertSame(actorScope.get(), selected.get()[2]);
assertThrows(ServiceException.class, service::selectRates);
actorScope.set(new ArProfitScope(true, false, false, 9L, 10L));
service.exportResults(null);
assertSame(actorScope.get(), selected.get()[2]);
}
@Test
void snapshotsTheRateOnceAtWriteoffAndPreservesMissingRates()
{
List<String> calls = new ArrayList<>();
AtomicReference<Object[]> inserted = new AtomicReference<>();
AtomicReference<ArCommissionRate> effective = new AtomicReference<>();
ArCommissionMapper mapper = (ArCommissionMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] { ArCommissionMapper.class }, (proxy, method, args) -> {
calls.add(method.getName());
return switch (method.getName()) {
case "lockSalesUser" -> 7L;
case "selectEffective" -> effective.get();
case "insertWriteoffRate" -> { inserted.set(args.clone()); yield 1; }
default -> throw new AssertionError(method.getName());
};
});
ArCommissionService service = new ArCommissionService(mapper, null, null, null);
ArBill bill = new ArBill();
bill.setProfitSalesUserId(7L);
ArBalanceWriteoff writeoff = new ArBalanceWriteoff();
writeoff.setWriteoffId(18L);
ArCommissionRate rate = new ArCommissionRate();
rate.setRateId(3L);
rate.setRate(new BigDecimal("10"));
effective.set(rate);
service.snapshotWriteoff(bill, writeoff);
assertEquals(List.of("lockSalesUser", "selectEffective", "insertWriteoffRate"), calls);
assertEquals(3L, inserted.get()[2]);
assertEquals(new BigDecimal("10"), inserted.get()[3]);
calls.clear();
effective.set(null);
service.snapshotWriteoff(bill, writeoff);
assertNull(inserted.get()[2]);
assertNull(inserted.get()[3]);
}
@Test
void savesOnlyCalculatedAmountsForReadyRows()
{
ArCommissionResult ready = new ArCommissionResult();
ready.setResultStatus("READY");
ready.setGrossProfit(new BigDecimal("-40"));
ready.setWeightedRate(new BigDecimal("1000"));
ready.setBillAmount(new BigDecimal("100"));
ArCommissionResult missing = new ArCommissionResult();
missing.setResultStatus("MISSING_PRICE");
List<ArCommissionResult> saved = new ArrayList<>();
ArCommissionMapper mapper = (ArCommissionMapper) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class<?>[] { ArCommissionMapper.class }, (proxy, method, args) -> {
if ("selectSettlementInputs".equals(method.getName())) return List.of(ready, missing);
if ("insertResults".equals(method.getName())) {
@SuppressWarnings("unchecked") List<ArCommissionResult> batch = (List<ArCommissionResult>) args[0];
saved.addAll(batch);
return batch.size();
}
throw new AssertionError(method.getName());
});
new ArCommissionService(mapper, null, null, null).createFinalResults(1L, "finance");
assertEquals(new BigDecimal("-4.00"), saved.get(0).getCommissionAmount());
assertNull(saved.get(1).getCommissionAmount());
}
}
@@ -0,0 +1,133 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.InputStream;
import java.util.Map;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;
import com.bms.receivable.profit.ArProfitQuery;
import com.bms.receivable.profit.ArProfitScope;
import com.bms.receivable.profit.ArCommissionResult;
class ArProfitMapperSqlTest
{
@Test
void commissionInReportSummaryUsesBillFiltersAndDataScope() throws Exception
{
Configuration configuration = new Configuration();
String resource = "mapper/receivable/ArProfitMapper.xml";
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource))
{
new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
}
var statement = configuration.getMappedStatement("com.bms.ar.mapper.ArProfitMapper.selectSummary");
ArProfitQuery query = new ArProfitQuery();
query.setCustomerId(5L);
query.setBillNo("AR123");
query.setStatus("WRITTEN_OFF");
query.setSalesUserId(8L);
query.setBeginBillDate(new java.util.Date(0));
query.setEndBillDate(new java.util.Date());
String sql = statement.getBoundSql(Map.of("query", query,
"scope", new ArProfitScope(false, true, false, 8L, 10L))).getSql();
int commissionStart = sql.indexOf("from ar_bill b join ar_profit_commission_result r");
assertTrue(commissionStart >= 0);
String commission = sql.substring(commissionStart);
assertTrue(commission.contains("r.result_status = 'READY'"));
assertTrue(commission.contains("r.currency = b.currency"));
assertTrue(commission.contains("b.status = 'WRITTEN_OFF'"));
assertTrue(commission.contains("b.profit_sales_user_id = ?"));
assertTrue(commission.contains("b.customer_id = ?"));
assertTrue(commission.contains("b.bill_no like"));
assertTrue(commission.contains("b.status = ?"));
assertTrue(commission.contains("b.bill_date >= ?"));
assertTrue(commission.contains("b.bill_date <= ?"));
assertTrue(commission.contains("group by b.currency"));
for (ArProfitScope scope : new ArProfitScope[] {
new ArProfitScope(false, false, true, 8L, 10L),
new ArProfitScope(false, false, false, 8L, 10L),
new ArProfitScope(true, false, false, 8L, 10L) })
{
String scopedSql = statement.getBoundSql(Map.of("query", new ArProfitQuery(), "scope", scope)).getSql();
String scopedCommission = scopedSql.substring(scopedSql.indexOf("from ar_bill b join ar_profit_commission_result r"));
if (scope.department()) assertTrue(scopedCommission.contains("find_in_set"));
else if (scope.all()) assertFalse(scopedCommission.contains("b.profit_sales_user_id = ?"));
else assertTrue(scopedCommission.contains("and 1 = 0"));
}
}
@Test
void parsesReportAndCommissionMappersAndScopesEachReportQuery() throws Exception
{
Configuration configuration = new Configuration();
// 提成 Mapper 先加载时也必须能解析引用的报表权限片段。
for (String resource : new String[] {"mapper/receivable/ArCommissionMapper.xml", "mapper/receivable/ArProfitMapper.xml"})
{
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource))
{
new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
}
}
for (String id : new String[] { "selectBills", "selectSummary", "selectBillDetails", "selectFees" })
{
String name = "com.bms.ar.mapper.ArProfitMapper." + id;
String self = configuration.getMappedStatement(name).getBoundSql(Map.of(
"query", new ArProfitQuery(), "scope", new ArProfitScope(false, true, false, 8L, 10L))).getSql();
String manager = configuration.getMappedStatement(name).getBoundSql(Map.of(
"query", new ArProfitQuery(), "scope", new ArProfitScope(false, false, true, 8L, 10L))).getSql();
assertTrue(self.contains("b.profit_sales_user_id = ?"));
assertFalse(self.contains("find_in_set"));
assertTrue(manager.contains("find_in_set"));
assertTrue(manager.contains("b.status in"));
}
String bills = configuration.getMappedStatement("com.bms.ar.mapper.ArProfitMapper.selectBills")
.getBoundSql(Map.of("query", new ArProfitQuery(), "scope", new ArProfitScope(true, false, false, 8L, 10L))).getSql();
assertTrue(bills.contains("from ar_bill b"));
assertTrue(bills.contains("b.bill_name"));
assertFalse(bills.contains("order_no"));
String billCommission = configuration.getMappedStatement("com.bms.ar.mapper.ArCommissionMapper.selectCommissionSummary")
.getBoundSql(Map.of("billId", 9L, "scope", new ArProfitScope(true, false, false, 8L, 10L))).getSql();
assertTrue(billCommission.contains("r.ar_bill_id = ?"));
assertTrue(billCommission.contains("then null"));
for (String id : new String[] { "selectResults", "selectCommissionSummary" })
{
var statement = configuration.getMappedStatement("com.bms.ar.mapper.ArCommissionMapper." + id);
String self = statement.getBoundSql(Map.of("billId", 9L, "includeReversed", true,
"scope", new ArProfitScope(false, true, false, 8L, 10L))).getSql();
String department = statement.getBoundSql(Map.of("includeReversed", false,
"scope", new ArProfitScope(false, false, true, 8L, 10L))).getSql();
String denied = statement.getBoundSql(Map.of("includeReversed", false,
"scope", new ArProfitScope(false, false, false, 8L, 10L))).getSql();
String all = statement.getBoundSql(Map.of("includeReversed", false,
"scope", new ArProfitScope(true, false, false, 8L, 10L))).getSql();
assertTrue(self.contains("b.profit_sales_user_id = ?"));
assertTrue(self.contains("r.ar_bill_id = ?"));
assertFalse(self.contains("find_in_set"));
assertTrue(department.contains("u.user_id = b.profit_sales_user_id"));
assertTrue(department.contains("find_in_set"));
assertTrue(denied.contains("and 1 = 0"));
assertFalse(all.contains("b.profit_sales_user_id = ?"));
assertFalse(all.contains("find_in_set"));
}
var salesSql = configuration.getMappedStatement("com.bms.ar.mapper.ArProfitMapper.selectSalesOptions")
.getBoundSql(Map.of("keyword", "sales"));
assertTrue(salesSql.getSql().contains("from sys_user u"));
assertTrue(salesSql.getSql().contains("u.nick_name like"));
assertTrue(salesSql.getSql().contains("u.user_name like"));
assertFalse(salesSql.getSql().contains("ar_bill"));
assertFalse(salesSql.getSql().contains("sys_role"));
assertTrue(salesSql.getSql().contains("limit 50"));
String settlement = configuration.getMappedStatement("com.bms.ar.mapper.ArCommissionMapper.selectSettlementInputs")
.getBoundSql(Map.of("billId", 1L)).getSql();
assertTrue(settlement.contains("w.status = 'EFFECTIVE'"));
assertTrue(settlement.contains("b.status = 'WRITTEN_OFF'"));
var insert = configuration.getMappedStatement("com.bms.ar.mapper.ArCommissionMapper.insertResults")
.getBoundSql(Map.of("items", java.util.List.of(new ArCommissionResult(), new ArCommissionResult()), "operator", "test"));
assertTrue(insert.getSql().contains("ar_profit_commission_result"));
assertTrue(insert.getParameterMappings().size() == 16);
}
}
@@ -0,0 +1,51 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.bms.receivable.profit.ArProfitScopeResolver;
import com.bms.common.core.domain.entity.SysRole;
import com.bms.common.core.domain.entity.SysUser;
import com.bms.common.core.domain.model.LoginUser;
import com.bms.common.exception.ServiceException;
class ArProfitScopeResolverTest
{
private static final String PERMISSION = "report:arProfit:list";
private LoginUser actor(String... keys)
{
SysUser user = new SysUser();
user.setUserId(99L);
user.setStatus("0");
user.setDelFlag("0");
user.setRoles(java.util.Arrays.stream(keys).map(key -> {
SysRole role = new SysRole();
role.setRoleKey(key);
role.setStatus("0");
role.setPermissions(Set.of(PERMISSION));
return role;
}).toList());
return new LoginUser(99L, 10L, user, Set.of(PERMISSION));
}
@Test
void allowedRolesHaveOnlyTheirApprovedScope()
{
ArProfitScopeResolver resolver = new ArProfitScopeResolver();
var sales = resolver.resolve(actor("ORA_6041"), PERMISSION);
assertTrue(sales.self());
assertFalse(sales.all());
var manager = resolver.resolve(actor("ORA_6040"), PERMISSION);
assertTrue(manager.department());
assertFalse(manager.all());
assertTrue(resolver.resolve(actor("ORA_6042"), PERMISSION).all());
assertTrue(resolver.resolve(actor("ORA_6043"), PERMISSION).all());
assertThrows(ServiceException.class, () -> resolver.resolve(actor("ORA_6163"), PERMISSION));
assertThrows(ServiceException.class, () -> resolver.resolve(actor("UNKNOWN"), PERMISSION));
assertThrows(ServiceException.class, () -> resolver.resolve(actor("ORA_6042"), "other:permission"));
}
}
@@ -0,0 +1,59 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigDecimal;
import java.util.List;
import com.bms.receivable.profit.CommissionCalculator;
import com.bms.receivable.profit.ArCommissionResult;
import com.bms.receivable.profit.CommissionCalculator.Writeoff;
import org.junit.jupiter.api.Test;
class CommissionCalculatorTest
{
private static BigDecimal n(String value) { return new BigDecimal(value); }
@Test
void waitsForFullSettlementAndUsesEachWriteoffRate()
{
var first = new Writeoff(n("50"), n("10"));
var partial = CommissionCalculator.calculate(n("100"), n("20"), List.of(first));
assertEquals(n("1.00"), partial.estimated());
assertNull(partial.formal());
var complete = CommissionCalculator.calculate(n("100"), n("20"),
List.of(first, new Writeoff(n("50"), n("20"))));
assertEquals(n("3.00"), complete.formal());
}
@Test
void deductsNegativeProfitAndKeepsMissingRatesUnknown()
{
assertEquals(n("-4.00"), CommissionCalculator.calculate(n("100"), n("-40"),
List.of(new Writeoff(n("100"), n("10")))).formal());
assertNull(CommissionCalculator.calculate(n("100"), n("20"),
List.of(new Writeoff(n("100"), null))).formal());
assertThrows(IllegalArgumentException.class, () -> CommissionCalculator.calculate(n("100"), n("20"),
List.of(new Writeoff(n("101"), n("10")))));
}
@Test
void allocatesRoundingRemainderAcrossOrderResults()
{
List<ArCommissionResult> orders = new java.util.ArrayList<>();
for (int i = 0; i < 3; i++)
{
ArCommissionResult order = new ArCommissionResult();
order.setResultStatus("READY");
order.setBillAmount(n("100"));
order.setGrossProfit(n("0.05"));
order.setWeightedRate(n("1000"));
orders.add(order);
}
CommissionCalculator.allocateFinalAmounts(orders);
assertEquals(n("0.01"), orders.get(0).getCommissionAmount());
assertEquals(n("0.00"), orders.get(1).getCommissionAmount());
assertEquals(n("0.01"), orders.get(2).getCommissionAmount());
}
}
@@ -168,6 +168,35 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils
return (str == null ? "" : str.trim());
}
/**
* Normalize destination postcode for zone match / persist.
* Removes all Unicode whitespace (incl. NBSP / U+2005) and ASCII spaces;
* strips Excel-style trailing ".0" on pure digits.
*/
public static String normalizePostcode(String postcode)
{
if (isEmpty(postcode))
{
return postcode;
}
StringBuilder sb = new StringBuilder(postcode.length());
for (int i = 0; i < postcode.length(); )
{
int cp = postcode.codePointAt(i);
if (!Character.isWhitespace(cp))
{
sb.appendCodePoint(cp);
}
i += Character.charCount(cp);
}
String n = sb.toString();
if (n.endsWith(".0") && n.matches("\\d+\\.0"))
{
return n.substring(0, n.length() - 2);
}
return n;
}
/**
* 替换指定字符串的指定区间内字符为"*"
*
@@ -15,8 +15,8 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.bms.common.exception.ServiceException;
import com.bms.common.utils.SecurityUtils;
import com.bms.ar.domain.ArBankAccount;
import com.bms.ar.mapper.ArBankAccountMapper;
import com.bms.receivable.domain.ArBankAccount;
import com.bms.receivable.mapper.ArBankAccountMapper;
import com.bms.customer.customerinfo.domain.BmsCustomer;
import com.bms.customer.customerinfo.domain.BmsCustomerAttachment;
import com.bms.customer.customerinfo.mapper.BmsCustomerMapper;
@@ -0,0 +1,11 @@
package com.bms.price.airbill.domain;
import java.util.List;
import lombok.Data;
/** 提单费用分摊请求。一次最多 5 个提单号。 */
@Data
public class SrvBillAirAllocCommand
{
private List<String> billCodes;
}
@@ -0,0 +1,45 @@
package com.bms.price.airbill.domain;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
/** 待分摊的一条提单费用,供费用处理弹框展示。 */
@Data
public class SrvBillAirAllocFee
{
private Long id;
private String billCode;
/** 提单主键 srv_bill_air.guid,写入订单费用的 source_id */
private String ladingId;
/** 费用阶段,字典 bms_fee_level */
private String feeLevel;
/** 费用状态,字典 bill_fee_status */
private String billFeeStatus;
private String feeName;
private BigDecimal price;
private String currency;
/** 分摊维度:1订单 2重量 */
private String allocDim;
/** 提单实际重量。只在按重量分摊时按提单号填入,不返回页面 */
@JsonIgnore
private BigDecimal actualWeight;
/** 干线打板重量。只在按重量分摊时按提单号填入,不返回页面 */
@JsonIgnore
private BigDecimal bandBoxWeight;
private Integer orderCount;
/** 不能分摊时的原因。空表示可以分摊 */
private String blockReason;
}
@@ -0,0 +1,19 @@
package com.bms.price.airbill.domain;
import java.math.BigDecimal;
import lombok.Data;
/** 提单下参与分摊的一票订单。 */
@Data
public class SrvBillAirAllocOrder
{
private String billCode;
private String orderNo;
/** 计费订单 ID,对应 prc_order_bill.bill_id */
private String billId;
/** 计费重,没有计费重时依次取实际重量、收货重量 */
private BigDecimal chargeWeight;
}
@@ -15,9 +15,24 @@ public class SrvBillAirFee
private String billCode;
/** 字典 bms_fee_type */
/** 附加费编号 prc_surcharge.sc_id */
private String feeType;
/** 附加费名称,仅展示,不入库 */
private String feeName;
/** 费用阶段,字典 bms_fee_level */
private String feeLevel;
/** 提单费用状态,字典 bill_fee_status。只随分摊、作废操作变化 */
private String billFeeStatus;
/** 是否分摊,字典 bill_fee_alloc:1是 0否 */
private String allocFlag;
/** 分摊维度(票),字典 bill_fee_alloc_dim:1订单 2重量。是否分摊为否时为空 */
private String allocDim;
private BigDecimal price;
/** 字典 bms_currency */
@@ -17,6 +17,12 @@ public class SrvBillAirFeeLog
public static final String DELETE = "3";
/** 已分摊费用确定。日志不记录字段变化。 */
public static final String CONFIRM = "4";
/** 已分摊或已确定费用作废。 */
public static final String VOID = "5";
private Long logId;
private String billCode;
@@ -25,7 +25,7 @@ public class BillingProperties
* Keep below Druid maxActive with headroom for other traffic.
*/
private int localRebillThreads = 16;
/** Night window auto-retry of prc_billing_task (all statuses) */
/** Hourly auto-retry of prc_billing_task (all statuses) */
private NightRetry nightRetry = new NightRetry();
private Oracle oracle = new Oracle();
@@ -120,8 +120,8 @@ public class BillingProperties
}
/**
* Overnight rebill window: pull prc_billing_task (all success_status) and retryTask.
* Default hours [0, 9) local time; empty result skips billing.
* Auto rebill window: pull prc_billing_task (all success_status) and retryTask.
* Default hours [0, 24) local time (all day); empty result skips billing.
*/
public static class NightRetry
{
@@ -129,8 +129,8 @@ public class BillingProperties
private boolean enabled = true;
/** Inclusive start hour (0 = 00:00) */
private int startHour = 0;
/** Exclusive end hour (9 = stop at 09:00) */
private int endHour = 9;
/** Exclusive end hour (24 = all day) */
private int endHour = 24;
/** Page size: bill this many then pull next page (default 500) */
private int batchSize = 500;
@@ -15,11 +15,20 @@ public class ChannelProductMap
/** 渠道表主键 srv_service_channel.id */
private String channelId;
/** 渠道编码,对应 srv_service_channel.channel_code */
private String channelCode;
private Long productId;
/** 应收套餐 prc_price_set.price_set_id */
/** 打单套餐 ID,对应 prc_price_set.price_set_id(应收可填) */
private Long priceSetId;
/** 渠道名称(列表回显) */
private String channelName;
/** 产品名称(列表回显) */
private String productName;
/** AR 应收,AP 应付 */
private String payType;
@@ -0,0 +1,39 @@
package com.bms.price.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 打单套餐价卡版本(按 pay_product_term.version_no 聚合,不走价格套餐 prc_price_set_version)。
*/
@Data
public class LabelPackageVersion
{
private Long priceSetId;
private Integer versionNo;
/** 展示用,如 V1 */
private String versionLabel;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date effectiveTime;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date expireTime;
/** 与 pay_product_term.status 一致:0待生效 1生效 2已失效 */
private String status;
private Integer productCount;
/** status=1 生效条数 */
private Integer activeCount;
/** status=0 待生效条数 */
private Integer pendingCount;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
}
@@ -6,22 +6,30 @@ import lombok.Data;
@Data
public class PayBillCommand
{
/** ORDER、TIME、LADING */
/** 取数方式:ORDER 订单号,TIME 计费日,LADING 提单号 */
private String sourceType;
/** 订单号原文,可用逗号、空格或换行分隔 */
private String orderText;
/** 计费日起,yyyy-MM-dd。sourceType 为 TIME 时必填 */
private String beginDate;
/** 计费日止,yyyy-MM-dd,含当天 */
private String endDate;
/** 提单号原文,可用逗号、空格或换行分隔 */
private String ladingText;
/** 供应商ID。生成账单时必填,预览不用 */
private Long supplierId;
/** 账单备注 */
private String remark;
/** 作废原因。作废时必填 */
private String voidReason;
/** 要作废的应付账单ID */
private Long billId;
}
@@ -8,11 +8,15 @@ import lombok.Data;
@Data
public class PayBillPreview
{
/** 还没进未作废账单、可以生成的订单 */
private List<PayBillOrder> orders = new ArrayList<>();
/** 按订单号查询时没有找到的单号 */
private List<String> missingNos = new ArrayList<>();
/** 已经挂在未作废账单上的订单 */
private List<PayBillOrder> occupied = new ArrayList<>();
/** 给页面的提示,例如未找到订单或超过单次票数 */
private String message;
}
@@ -12,6 +12,9 @@ public class PayExtraLine
private Long productId;
/** 价卡周期,对应 pay_product_term.term_id;与 productId 组成明细维度 */
private Long termId;
/** 邮编 或 配置 */
private String lineType;
@@ -11,7 +11,13 @@ public class PayPriceCompare
private PayProduct newer;
/** 有效期、来源文件、币种 */
private List<PayPriceDiff> versionDiffs;
private List<PayPriceDiff> weightDiffs;
private List<PayPriceDiff> surchargeDiffs;
/** 邮编等不能归进重量段和附加费的原文 */
private List<PayPriceDiff> extraDiffs;
}
@@ -6,6 +6,9 @@ import lombok.Data;
@Data
public class PayPriceDiff
{
/** 版本、重量段、附加费、其他配置 */
private String kind;
private String name;
private String zoneName;
@@ -22,6 +22,9 @@ public class PayProductTerm extends BaseEntity
private Long productId;
/** 打单套餐ID;应付公共模板为空 */
private Long priceSetId;
private Integer versionNo;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@@ -30,7 +33,7 @@ public class PayProductTerm extends BaseEntity
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date effectiveEnd;
/** 0 生效,1 失效 */
/** 0待生效 1生效 2已失效 */
private String status;
private String productName;
@@ -13,5 +13,17 @@ public class PaySaveCommand
/** 为 true 时,同文件同表同名的旧产品先删后插 */
private boolean overwrite;
/** 打单套餐ID;有值时走 LABEL 导入(稳定 product_id + term.price_set_id) */
private Long priceSetId;
/** 打单套餐名称;priceSetId 为空时新建套餐壳 */
private String priceSetName;
/** 打单套餐备注 */
private String priceSetNote;
/** 编辑待生效版本时传入,覆盖该 version_no,不新建版本号 */
private Integer versionNo;
private List<PayProduct> products = new ArrayList<>();
}
@@ -15,13 +15,19 @@ public class PaySurcharge
private Long productId;
/** 所属价卡版本,跟产品版本一起变 */
/** 价卡周期,对应 pay_product_term.term_id;与 productId 组成明细维度 */
private Long termId;
/** 所属价卡版本,跟产品版本一起变(展示兼容) */
private Integer versionNo;
private String sectionName;
private String feeName;
/** 附加费配置ID,对应 prc_surcharge.sc_id */
private Long scId;
private String zoneName;
/** 收费标准原文 */
@@ -51,11 +57,20 @@ public class PaySurcharge
/** 固定收取、产生时收取、旺季期间 */
private String chargeTiming;
/** ALWAYS、POSTCODE、WEIGHT、SIZE、RETURN、EXTRA_KG、MANUAL */
/** ALWAYS、POSTCODE、ZONE、WEIGHT、SIZE、RETURN、EXTRA_KG、MANUAL */
private String calcRule;
/** 邮编列表、重量阈值或尺寸表达式 */
/** 邮编列表、重量阈值或尺寸表达式。续重时这里是公斤阈值 */
private String calcParam;
/** 偏远邮编规则。续重行的阈值在 calcParam,邮编放这里,避免互相覆盖 */
private String postcodeParam;
/** 适用重量下限,空表示不限。首重从 0 开始 */
private BigDecimal weightMin;
/** 适用重量上限,空表示不限。分区价按这个区间只收一档 */
private BigDecimal weightMax;
private Integer sortNo;
}
@@ -13,7 +13,10 @@ public class PayWeightBand
private Long productId;
/** 所属价卡版本,跟产品版本一起变 */
/** 价卡周期,对应 pay_product_term.term_id;与 productId 组成明细维度 */
private Long termId;
/** 所属价卡版本,跟产品版本一起变(展示兼容) */
private Integer versionNo;
/** 报价区块,例如派送费、偏远附加费 */
@@ -122,7 +122,7 @@ public class PrcOrderBill extends BaseEntity
private String creditArrearsStatus;
/** NONE / REFUNDED */
private String refundStatus;
/** Billing fail: 0 ok; 1/2/3 sales miss; 23/24/25 catalog miss; soft-fail amount=0, no fee rows */
/** Billing fail: 0 ok writes income bill+fee; non-0 amount=0, no income bill/fee */
private Integer billingFailStatus;
/** 失败原因 */
private String errorMessage;
@@ -19,6 +19,9 @@ public class PrcPayBillFee implements Serializable
private String feeType;
private String feeName;
private Long scId;
/** 费用所属阶段:1 a段,2 b段,3 c段,4 d段 */
private String feeLevel;
private BigDecimal amount;
private String currency;
private String roundMode;
@@ -26,6 +29,12 @@ public class PrcPayBillFee implements Serializable
/** CALC 计算,LADING 提单分摊,MANUAL 人工 */
private String feeSource;
/** 来源数据id */
private String sourceId;
/** 是否删除:0未删除 1已删除 */
private String isDeleted;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
}
@@ -19,6 +19,8 @@ public class PrcPriceSet extends BaseEntity
public static final String CATEGORY_PACKAGE = "PACKAGE";
/** Boss exclusive quote. */
public static final String CATEGORY_EXCLUSIVE = "EXCLUSIVE";
/** Label / 打单套餐(应收价卡套餐). */
public static final String CATEGORY_LABEL = "LABEL";
private Long priceSetId;
private String priceSetCode;
@@ -26,7 +28,7 @@ public class PrcPriceSet extends BaseEntity
private String priceSetNote;
/** FIXED / DISCOUNT */
private String setType;
/** PACKAGE=ordinary set / EXCLUSIVE=boss exclusive quote */
/** PACKAGE=ordinary set / EXCLUSIVE=boss exclusive quote / LABEL=打单套餐 */
private String setCategory;
private BigDecimal defaultDiscount;
private String defaultType;
@@ -21,6 +21,11 @@ public class TmsPriceQuoteRequest implements Serializable
@NotBlank(message = "productCode is required")
private String productCode;
/**
* 打单套餐(LABEL)试算/计费用渠道ID;计费也可从订单扩展 productChannelId 解析。
*/
private String channelId;
/** ISO2; countryName alternative */
private String countryCode;
/** country display name; countryCode alternative */
@@ -103,7 +103,7 @@ public class TmsPriceQuoteResult implements Serializable
private String creditArrearsStatus;
/** NONE / REFUNDED */
private String refundStatus;
/** Billing fail: 0 ok; 1/2/3 sales; 23/24/25 catalog (soft-fail on bill sync) */
/** Billing fail: 0 ok (income bill+fee); 1/2/3 sales; 23/24/25 catalog */
private Integer billingFailStatus;
private Integer pieces;
private BigDecimal actualWeight;
@@ -6,7 +6,8 @@ package com.bms.price.enums;
* 1/2/3 sales-price (package) miss: product / country / weight;
* 23/24/25 product-catalog price miss: product / country / weight;
* 4+ map to prc_billing_task.fail_code.
* Soft-fail income bill: 0/1/2/3/23/24/25; fee rows only for 0.
* 26 not billed yet (order-source sync only).
* Income bill + fee rows: only status 0.
*/
public enum BillBillingFailStatus
{
@@ -38,7 +39,9 @@ public enum BillBillingFailStatus
/** Product catalog miss: product hit but country/zone miss. */
CATALOG_COUNTRY(24),
/** Product catalog miss: product+country hit but weight band miss. */
CATALOG_WEIGHT(25);
CATALOG_WEIGHT(25),
/** Order landed from upstream but not billed yet. */
NOT_BILLED(26);
private final int code;
@@ -70,16 +73,23 @@ public enum BillBillingFailStatus
public static boolean isFail(Integer code)
{
return code != null && code.intValue() > SUCCESS.code;
if (code == null)
{
return false;
}
int value = code.intValue();
return value != SUCCESS.code && value != NOT_BILLED.code;
}
/** Soft-fail sales/catalog misses also persist prc_income_bill. */
public static boolean isNotBilled(Integer code)
{
return code != null && code.intValue() == NOT_BILLED.code;
}
/** Only success (0) persists prc_income_bill. */
public static boolean storesIncomeBill(Integer code)
{
int value = code == null ? SUCCESS.code : code.intValue();
return value == SUCCESS.code
|| value == PRODUCT.code || value == COUNTRY.code || value == WEIGHT.code
|| value == CATALOG_PRODUCT.code || value == CATALOG_COUNTRY.code || value == CATALOG_WEIGHT.code;
return code == null || code.intValue() == SUCCESS.code;
}
/** 仅 0 落 prc_income_bill_fee。 */
@@ -96,7 +106,7 @@ public enum BillBillingFailStatus
}
for (BillBillingFailStatus status : values())
{
if (status == SUCCESS)
if (status == SUCCESS || status == NOT_BILLED)
{
continue;
}
@@ -113,6 +123,7 @@ public enum BillBillingFailStatus
switch (this)
{
case SUCCESS:
case NOT_BILLED:
return null;
case PRODUCT:
return BillTaskFailCode.PRODUCT_NOT_HIT.getCode();
@@ -16,6 +16,11 @@ public enum ProfitAreaRule
this.customerArea = customerArea;
}
public String getCustomerArea()
{
return customerArea;
}
public static ProfitAreaRule fromCustomerArea(String customerArea)
{
if (customerArea != null)
@@ -1,5 +1,6 @@
package com.bms.price.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.ChannelProductMap;
@@ -10,9 +11,14 @@ public interface ChannelProductMapMapper
{
ChannelProductMap selectByChannelAndType(@Param("channelId") String channelId, @Param("payType") String payType);
List<ChannelProductMap> selectByPriceSetId(@Param("priceSetId") Long priceSetId);
int upsert(ChannelProductMap row);
int deleteByChannelAndType(@Param("channelId") String channelId, @Param("payType") String payType);
int deleteByChannelTypeAndPriceSet(@Param("channelId") String channelId, @Param("payType") String payType,
@Param("priceSetId") Long priceSetId);
int deleteByProductId(@Param("productId") Long productId);
}
@@ -8,26 +8,90 @@ import com.bms.price.domain.PayBillLog;
import com.bms.price.domain.PayBillOrder;
import com.bms.price.domain.PrcPayBillFee;
/** 供应商应付账单 pay_bill 及其明细、日志。 */
public interface PayBillMapper
{
/**
* 按账单号、供应商、状态、币种查询账单头。
*
* @param query 查询条件
* @return 账单头列表
*/
List<PayBill> selectPayBillList(PayBill query);
/**
* 按主键读取一张账单头。
*
* @param billId 应付账单ID
* @return 账单头,不存在时为 null
*/
PayBill selectPayBillById(Long billId);
/**
* 读取一张账单的费用快照。
*
* @param billId 应付账单ID
* @return 费用行
*/
List<PayBillLine> selectLines(Long billId);
/**
* 读取一张账单的操作日志。
*
* @param billId 应付账单ID
* @return 按写入顺序排列的日志
*/
List<PayBillLog> selectLogs(Long billId);
/**
* 按订单号、计费日或提单号查找可出账订单,并标出已挂在未作废账单上的账单号。
*
* @param orderNos 订单号,空则不按订单号限制
* @param beginDate 计费日起,yyyy-MM-dd,空则不限制
* @param endDate 计费日止,含当天,空则不限制
* @param ladingNos 提单号,同时匹配订单上的航空主单号和应付提单
* @return 最多 2000 票订单
*/
List<PayBillOrder> selectCandidateOrders(@Param("orderNos") List<String> orderNos, @Param("beginDate") String beginDate,
@Param("endDate") String endDate, @Param("ladingNos") List<String> ladingNos);
/**
* 读取这些订单当前的应付费用,供生成账单时抄成快照。
*
* @param billIds 计费订单ID
* @return 订单应付费用
*/
List<PrcPayBillFee> selectOrderFees(@Param("billIds") List<String> billIds);
/**
* 插入一张草稿应付账单。
*
* @param bill 账单头,账单号和供应商由调用方填好
* @return 影响行数
*/
int insertPayBill(PayBill bill);
/**
* 更新账单状态。作废时同时写原因、作废人和作废时间。
*
* @param bill 至少包含账单ID、状态和更新人
* @return 影响行数
*/
int updatePayBillStatus(PayBill bill);
/**
* 批量写入账单费用快照。
*
* @param list 费用行,每行已带账单ID
* @return 影响行数
*/
int insertLines(@Param("list") List<PayBillLine> list);
/**
* 写入一条账单操作日志。
*
* @param log 操作类型、前后状态和说明
* @return 影响行数
*/
int insertLog(PayBillLog log);
}
@@ -24,6 +24,9 @@ public interface PayPostcodeMapper
List<PayPostcodeGroup> selectGroupsByTokens(@Param("tokens") List<String> tokens);
/** 报价表、销售产品或工作表与产品名称完全一致的邮编配置 */
List<PayPostcodeGroup> selectGroupsForProduct(@Param("names") List<String> names);
List<PayPostcodeLine> selectRegionKeys(@Param("groupIds") List<Long> groupIds);
List<PayPostcodeLine> selectLinesByGroups(@Param("groupIds") List<Long> groupIds);
@@ -22,7 +22,7 @@ public interface PayProductMapper
Long selectTemplateId(@Param("dictValue") String dictValue);
List<PayProduct> selectTemplateOptions();
List<PayProduct> selectTemplateOptions(@Param("payType") String payType);
Integer selectMaxVersion(@Param("originId") Long originId);
@@ -38,16 +38,33 @@ public interface PayProductMapper
List<PayWeightBand> selectWeightBands(@Param("productIds") List<Long> productIds);
List<PayWeightBand> selectWeightBandsByTerm(@Param("termIds") List<Long> termIds);
List<PaySurcharge> selectSurcharges(@Param("productIds") List<Long> productIds);
List<PaySurcharge> selectSurchargesByTerm(@Param("termIds") List<Long> termIds);
List<PayExtraLine> selectExtraLines(@Param("productIds") List<Long> productIds);
List<PayExtraLine> selectExtraLinesByTerm(@Param("termIds") List<Long> termIds);
int deleteWeightBands(@Param("productIds") List<Long> productIds);
int deleteSurcharges(@Param("productIds") List<Long> productIds);
int deleteExtraLines(@Param("productIds") List<Long> productIds);
int deleteWeightBandsByTerm(@Param("termIds") List<Long> termIds);
int deleteSurchargesByTerm(@Param("termIds") List<Long> termIds);
int deleteExtraLinesByTerm(@Param("termIds") List<Long> termIds);
Long selectTemplateIdByType(@Param("dictValue") String dictValue, @Param("productType") String productType);
/** 打单专用:命中仅属于打单套餐的 AR 产品,不命中应付公共模板 */
Long selectLabelProductIdByDict(@Param("dictValue") String dictValue);
int deletePayProducts(@Param("productIds") List<Long> productIds);
List<Long> selectFamilyIds(@Param("rootId") Long rootId);
@@ -3,6 +3,7 @@ package com.bms.price.mapper;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.LabelPackageVersion;
import com.bms.price.domain.PayProductTerm;
/**
@@ -16,6 +17,31 @@ public interface PayProductTermMapper
PayProductTerm selectByProductId(Long productId);
/** 打单产品所属套餐 ID */
Long selectLabelPriceSetIdByProduct(@Param("productId") Long productId);
List<PayProductTerm> selectByPriceSetId(@Param("priceSetId") Long priceSetId);
List<PayProductTerm> selectByPriceSetIdAndVersion(@Param("priceSetId") Long priceSetId,
@Param("versionNo") Integer versionNo);
/** 打单计费:套餐+产品+计费日命中 term(时间窗口优先) */
Long selectTermIdBySetProductAt(@Param("priceSetId") Long priceSetId, @Param("productId") Long productId,
@Param("bizDate") Date bizDate);
/** 打单套餐:按 version_no 聚合版本(含已失效) */
List<LabelPackageVersion> selectLabelVersionGroups(@Param("priceSetId") Long priceSetId);
/** 打单套餐:批量改某一版的生效起止与状态 */
int updateLabelVersionPeriod(@Param("priceSetId") Long priceSetId, @Param("versionNo") Integer versionNo,
@Param("effectiveStart") Date effectiveStart, @Param("effectiveEnd") Date effectiveEnd,
@Param("status") String status, @Param("updateBy") String updateBy);
Integer selectMaxVersionByProduct(@Param("productId") Long productId, @Param("priceSetId") Long priceSetId);
/** 打单套餐下最大 version_no */
Integer selectMaxVersionByPriceSet(@Param("priceSetId") Long priceSetId);
int insertTerm(PayProductTerm term);
int updatePeriod(PayProductTerm term);
@@ -25,7 +51,32 @@ public interface PayProductTermMapper
/** 新版本生效时,把同一产品仍生效的旧版本关掉,结束日收到新版本开始的前一天 */
int closeOpenTerms(@Param("dictValue") String dictValue, @Param("endDate") Date endDate, @Param("updateBy") String updateBy);
/** 打单套餐:按套餐+产品关闭仍生效的旧周期 */
int closeOpenTermsBySetProduct(@Param("priceSetId") Long priceSetId, @Param("productId") Long productId,
@Param("endDate") Date endDate, @Param("updateBy") String updateBy);
/** 打单:只关掉某产品本套餐待生效 term */
int closePendingBySetProduct(@Param("priceSetId") Long priceSetId, @Param("productId") Long productId,
@Param("endDate") Date endDate, @Param("updateBy") String updateBy);
/** 打单:启动某版本时,关掉本套餐其它版本的生效 term */
int closeEffectExceptVersion(@Param("priceSetId") Long priceSetId, @Param("versionNo") Integer versionNo,
@Param("endDate") Date endDate, @Param("updateBy") String updateBy);
/** 打单:预约未来生效时,只写旧版失效日,仍保持生效;并恢复被提前关掉但未到期的旧版 */
int scheduleEndExceptVersion(@Param("priceSetId") Long priceSetId, @Param("versionNo") Integer versionNo,
@Param("endDate") Date endDate, @Param("today") Date today, @Param("updateBy") String updateBy);
/** 打单:恢复「失效日未到却被标成已失效」的 term */
int restorePrematureClosed(@Param("priceSetId") Long priceSetId, @Param("today") Date today,
@Param("updateBy") String updateBy);
/** 打单:删除待生效版后,清掉旧版预约失效日 */
int clearScheduledEnd(@Param("priceSetId") Long priceSetId, @Param("updateBy") String updateBy);
int deleteByProductIds(@Param("productIds") List<Long> productIds);
int deleteByTermIds(@Param("termIds") List<Long> termIds);
int updateProductEffectiveDate(@Param("productId") Long productId, @Param("effectiveDate") Date effectiveDate);
}
@@ -137,4 +137,7 @@ public interface PrcOrderBillMapper
/** 只更新应付合计,不改应收。 */
int updatePayTotal(@Param("billId") String billId, @Param("payTotal") BigDecimal payTotal);
/** Count order bills that reference this sales package version. */
int countByPsvId(@Param("psvId") Long psvId);
}
@@ -4,14 +4,55 @@ import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.PrcPayBillFee;
/** 应付账单费用 mapper */
/** 订单应付费用 prc_pay_bill_fee。 */
public interface PrcPayBillFeeMapper
{
/**
* 读取一票订单的全部应付费用,运费在前,附加费在后。
*
* @param billId 计费订单ID
* @return 费用明细
*/
public List<PrcPayBillFee> selectByBillId(String billId);
/**
* 插入一条订单应付费用。
*
* @param fee 费用类型、名称、金额和币种
* @return 影响行数
*/
public int insertPrcPayBillFee(PrcPayBillFee fee);
/**
* 批量插入订单应付费用。
*
* @param fees 本次要保存的费用
* @return 影响行数
*/
public int insertBatch(@Param("list") List<PrcPayBillFee> fees);
/**
* 删除一票订单上来源为计算的费用。提单分摊和人工费用保留。
*
* @param billId 计费订单ID
* @return 影响行数
*/
public int deleteByBillId(String billId);
/**
* 逻辑删除某一条提单费用分摊到订单上的明细。
*
* @param feeId 提单费用 ID,保存在 sc_id
* @return 影响行数
*/
public int markLadingFeeDeleted(@Param("feeId") Long feeId);
/**
* 这条提单费用分摊到的订单里,取一个已经生成应付账单的订单号。
* 是否出账看 prc_order_bill_ext.is_meet:1 已生成。
*
* @param feeId 提单费用 ID,保存在 sc_id
* @return 订单号,没有已出账订单时为空
*/
public String selectBilledOrderNo(@Param("feeId") Long feeId);
}
@@ -2,18 +2,54 @@ package com.bms.price.mapper;
import com.bms.price.domain.PrcPayBill;
/** prc_pay_bill mapper */
/** 订单应付主表 prc_pay_bill。一票计费订单对应一行。 */
public interface PrcPayBillMapper
{
/**
* 按计费订单读取应付主表。
*
* @param billId 计费订单ID
* @return 订单应付,没有时为 null
*/
PrcPayBill selectByBillId(String billId);
/**
* 按应付主表ID读取。
*
* @param payBillId 订单应付ID
* @return 订单应付,没有时为 null
*/
PrcPayBill selectByPayBillId(String payBillId);
/**
* 新增一票订单的应付主表。
*
* @param row 应付合计、币种和业务员
* @return 影响行数
*/
int insertPrcPayBill(PrcPayBill row);
/**
* 更新已有订单应付的合计和业务员。
*
* @param row 含应付主表ID的更新内容
* @return 影响行数
*/
int updatePrcPayBill(PrcPayBill row);
/**
* 按计费订单插入或更新应付主表。
*
* @param row 订单应付
* @return 影响行数
*/
int upsertPrcPayBill(PrcPayBill row);
/**
* 删除一票订单的应付主表。
*
* @param billId 计费订单ID
* @return 影响行数
*/
int deleteByBillId(String billId);
}
@@ -0,0 +1,56 @@
package com.bms.price.mapper;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.airbill.domain.SrvBillAirAllocFee;
import com.bms.price.airbill.domain.SrvBillAirAllocOrder;
import com.bms.price.domain.PrcPayBill;
/**
* 提单费用分摊到订单。
*/
public interface SrvBillAirAllocMapper
{
/**
* 查询这些提单上尚未分摊、且标记为需要分摊的费用。
*
* @param billCodes 提单号
* @return 待分摊费用
*/
List<SrvBillAirAllocFee> selectPendingFees(@Param("billCodes") List<String> billCodes);
/**
* 按提单号取出实际重量和打板重量,只供按重量分摊计算。
*
* @param billCodes 提单号
* @return 提单号、实际重量、打板重量
*/
List<SrvBillAirAllocFee> selectLadingWeight(@Param("billCodes") List<String> billCodes);
/**
* 按提单号查出关联订单。订单号在扩展表,计费单号和重量在订单表。
*
* @param billCodes 提单号,对应 prc_order_bill_ext.air_no_old
* @return 订单
*/
List<SrvBillAirAllocOrder> selectOrders(@Param("billCodes") List<String> billCodes);
/**
* 按计费订单号取出已有的应付主表。
*
* @param billIds 计费订单 ID
* @return 应付主表编号
*/
List<PrcPayBill> selectPayBills(@Param("billIds") List<String> billIds);
/**
* 把仍是未分摊的费用改为已分摊。已经不是未分摊的行不会被改到。
*
* @param ids 提单费用 ID
* @param updateBy 操作人
* @param updateTime 操作时间
* @return 实际改到的行数
*/
int markAllocated(@Param("ids") List<Long> ids, @Param("updateBy") String updateBy, @Param("updateTime") Date updateTime);
}
@@ -22,6 +22,14 @@ public interface SrvBillAirFeeMapper
int deleteFee(@Param("id") Long id, @Param("billCode") String billCode, @Param("updateBy") String updateBy,
@Param("updateTime") java.util.Date updateTime);
/** 已分摊改为已确定。 */
int confirmFee(@Param("id") Long id, @Param("billCode") String billCode, @Param("updateBy") String updateBy,
@Param("updateTime") java.util.Date updateTime);
/** 已分摊或已确定的费用作废:状态改为已作废,并逻辑删除。 */
int voidFee(@Param("id") Long id, @Param("billCode") String billCode, @Param("updateBy") String updateBy,
@Param("updateTime") java.util.Date updateTime);
int insertLog(SrvBillAirFeeLog log);
List<SrvBillAirFeeLog> selectLogs(String billCode);
@@ -47,7 +47,7 @@ public class OracleOrderBillMapper
req.setCountryCode(firstStr(row, "COUNTRY"));
String countryName = firstStr(row, "COUNTRY_NAME", "COUNTRY_EINGTH_NAME", "COUNTRY");
req.setCountryName(countryName);
req.setDestPostcode(firstStr(row, "CONSIGNEE_POSTCODE"));
req.setDestPostcode(StringUtils.normalizePostcode(firstStr(row, "CONSIGNEE_POSTCODE")));
// Prefer CONFIRM_WEIGHT (customer confirmed); fallback DIMENSIONAL_WEIGHT_FACTOR (charge weight).
BigDecimal weight = firstPositiveDecimal(row, "CONFIRM_WEIGHT", "DIMENSIONAL_WEIGHT_FACTOR");
req.setWeight(weight);
@@ -24,18 +24,69 @@ public final class PayCostCalculator
{
private static final ZoneId SHANGHAI = ZoneId.of("GMT+8");
// 定义常量集合,建议放在类级别作为 static final 常量
private static final Set<Integer> REFUND_STATUS_SET = Set.of(9, 10);
private PayCostCalculator()
{
}
/**
* 按重量、尺寸和邮编计算一票尾程应付。不指定地区,也不传入偏远命中结果。
*
* @param product 当前价卡版本,含重量段和附加费
* @param weight 计费重,公斤
* @param length 长,厘米
* @param width 宽,厘米
* @param height 高,厘米
* @param postcode 收件邮编
* @param bizDate 取价日,用来判断附加费是否在有效期内
* @param orderStatus 订单状态,退件时才收退件类附加费
* @return 费用明细和算不了的附加费说明
*/
public static PayOrderCostResult calculate(PayProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, Date bizDate, Integer orderStatus)
{
return calculate(product, weight, length, width, height, postcode, null, bizDate, orderStatus);
}
/**
* 在已经选定价卡地区时计算尾程应付。偏远仍按价卡上的邮编条件判断。
*
* @param product 当前价卡版本
* @param weight 计费重,公斤
* @param length 长,厘米
* @param width 宽,厘米
* @param height 高,厘米
* @param postcode 收件邮编
* @param zoneName 邮编对上的价卡地区,空表示不按地区过滤
* @param bizDate 取价日
* @param orderStatus 订单状态
* @return 费用明细和算不了的附加费说明
*/
public static PayOrderCostResult calculate(PayProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus)
{
return calculate(product, weight, length, width, height, postcode, zoneName, bizDate, orderStatus, null);
}
/**
* 计算一票尾程应付。remoteHits 为空列表表示产品有偏远邮编但这次没命中;为 null 表示没有这份配置,仍按价卡上的邮编条件。
*
* @param product 当前价卡版本
* @param weight 计费重,公斤
* @param length 长,厘米
* @param width 宽,厘米
* @param height 高,厘米
* @param postcode 收件邮编
* @param zoneName 价卡地区
* @param bizDate 取价日
* @param orderStatus 订单状态
* @param remoteHits 偏远邮编命中结果
* @return 费用明细和算不了的附加费说明
*/
public static PayOrderCostResult calculate(PayProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus, List<PayRemoteBook.Hit> remoteHits)
{
PayOrderCostResult result = new PayOrderCostResult();
result.setFees(new ArrayList<>());
@@ -52,7 +103,12 @@ public final class PayCostCalculator
result.setMessage("订单没有计费重");
return result;
}
List<PayWeightBand> bands = forZone(usableBands(product.getWeightBands()), zoneName);
List<PayWeightBand> usable = usableBands(product.getWeightBands());
List<PayWeightBand> bands = forZone(usable, zoneName);
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty() && hasZoneFee(product, zoneName))
{
bands = deliveryBands(usable, product);
}
if (zoneName != null && !zoneName.isBlank() && bands.isEmpty())
{
result.setMessage("邮编对应的地区「" + zoneName + "」不在价卡重量段里");
@@ -88,7 +144,7 @@ public final class PayCostCalculator
result.getFees().add(freightLine);
result.setCurrency(currency);
addSurcharges(product, weight, length, width, height, postcode, zoneName, bizDate, orderStatus, freight, currency,
band.getSectionName(), result);
band.getSectionName(), remoteHits, result);
BigDecimal total = BigDecimal.ZERO;
for (PayCostLine fee : result.getFees())
{
@@ -99,6 +155,79 @@ public final class PayCostCalculator
return result;
}
/** 邮编落到偏远分区,而价卡重量段只有大陆派送费时,运费用大陆档。 */
private static boolean hasZoneFee(PayProduct product, String zoneName)
{
if (product.getSurcharges() == null)
{
return false;
}
for (PaySurcharge fee : product.getSurcharges())
{
if (fee != null && PaySurchargeRules.ZONE.equals(fee.getCalcRule()) && PayZoneMatcher.sameZone(fee.getZoneName(), zoneName))
{
return true;
}
}
return false;
}
private static List<PayWeightBand> deliveryBands(List<PayWeightBand> bands, PayProduct product)
{
List<String> remoteZones = new ArrayList<>();
if (product.getSurcharges() != null)
{
for (PaySurcharge fee : product.getSurcharges())
{
if (fee != null && PaySurchargeRules.ZONE.equals(fee.getCalcRule()) && fee.getZoneName() != null && !fee.getZoneName().isBlank())
{
remoteZones.add(fee.getZoneName());
}
}
}
List<PayWeightBand> kept = new ArrayList<>();
for (PayWeightBand band : bands)
{
boolean remote = false;
for (String zone : remoteZones)
{
if (PayZoneMatcher.sameZone(band.getZoneName(), zone))
{
remote = true;
break;
}
}
if (!remote)
{
kept.add(band);
}
}
return kept;
}
/** 首重对更重的包裹仍然收取,超出部分由续重另计。 */
private static boolean weightAtLeast(PaySurcharge fee, BigDecimal weight)
{
if (fee.getWeightMin() == null || weight == null)
{
return true;
}
return weight.compareTo(fee.getWeightMin()) >= 0;
}
private static boolean weightIn(PaySurcharge fee, BigDecimal weight)
{
if (weight == null || (fee.getWeightMin() == null && fee.getWeightMax() == null))
{
return false;
}
if (fee.getWeightMin() != null && weight.compareTo(fee.getWeightMin()) < 0)
{
return false;
}
return fee.getWeightMax() == null || weight.compareTo(fee.getWeightMax()) <= 0;
}
private static List<PayWeightBand> forZone(List<PayWeightBand> bands, String zoneName)
{
if (zoneName == null || zoneName.isBlank())
@@ -116,9 +245,26 @@ public final class PayCostCalculator
return kept;
}
/**
* 添加相关附加费,根据计费规则去判断
* @param product
* @param weight
* @param length
* @param width
* @param height
* @param postcode
* @param zoneName
* @param bizDate
* @param orderStatus
* @param freight
* @param currency
* @param freightSection
* @param remoteHits
* @param result
*/
private static void addSurcharges(PayProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus, BigDecimal freight, String currency,
String freightSection, PayOrderCostResult result)
String freightSection, List<PayRemoteBook.Hit> remoteHits, PayOrderCostResult result)
{
if (product.getSurcharges() == null)
{
@@ -131,24 +277,59 @@ public final class PayCostCalculator
{
continue;
}
if (zoneName != null && !zoneName.isBlank() && fee.getZoneName() != null && !fee.getZoneName().isBlank()
&& !PayZoneMatcher.sameZone(fee.getZoneName(), zoneName))
{
continue;
}
String rule = fee.getCalcRule() == null || fee.getCalcRule().isBlank() ? PaySurchargeRules.MANUAL : fee.getCalcRule();
String name = blank(fee.getFeeName());
if (PaySurchargeRules.POSTCODE.equals(rule))
if (remoteHits != null && remoteFee(fee))
{
String name = blank(fee.getFeeName());
if (postcode == null || postcode.isBlank())
{
result.getSkipped().add(name + ":订单没有邮编");
}
else if (PaySurchargeRules.matchesPostcode(fee.getCalcParam(), postcode))
else if (bookApplies(remoteHits, fee, rule))
{
String remark = "邮编 " + postcode.trim();
if (PaySurchargeRules.EXTRA_KG.equals(rule))
{
addExtraKg(result.getFees(), fee, weight, currency);
}
else if (perKg(fee))
{
addPerKg(result.getFees(), fee, weight, currency, remark);
}
else
{
addFlat(result.getFees(), fee, currency, remark);
}
}
continue;
}
boolean postcodeDriven = PaySurchargeRules.POSTCODE.equals(rule) || !blank(fee.getPostcodeParam()).isEmpty();
if (!postcodeDriven && zoneName != null && !zoneName.isBlank() && fee.getZoneName() != null && !fee.getZoneName().isBlank()
&& !PayZoneMatcher.sameZone(fee.getZoneName(), zoneName))
{
continue;
}
String name = blank(fee.getFeeName());
if (PaySurchargeRules.POSTCODE.equals(rule))
{
String param = blank(fee.getPostcodeParam()).isEmpty() ? fee.getCalcParam() : fee.getPostcodeParam();
if (postcode == null || postcode.isBlank())
{
result.getSkipped().add(name + ":订单没有邮编");
}
else if (PaySurchargeRules.matchesPostcode(param, postcode) && weightAtLeast(fee, weight))
{
addFlat(result.getFees(), fee, currency, "邮编 " + postcode.trim());
}
}
else if (PaySurchargeRules.ZONE.equals(rule))
{
boolean already = result.getFees().stream().anyMatch(line -> name.equals(line.getFeeName()));
if (!already && zoneName != null && !zoneName.isBlank() && PayZoneMatcher.sameZone(fee.getZoneName(), zoneName) && weightIn(fee, weight))
{
addFlat(result.getFees(), fee, currency, "地区 " + zoneName.replace('\n', ' '));
}
}
else if (PaySurchargeRules.WEIGHT.equals(rule))
{
if (PaySurchargeRules.matchesWeight(fee.getCalcParam(), weight))
@@ -156,6 +337,7 @@ public final class PayCostCalculator
addFlat(result.getFees(), fee, currency, "计费重超过 " + fee.getCalcParam() + "kg");
}
}
// 超出尺寸费用
else if (PaySurchargeRules.SIZE.equals(rule))
{
if (length == null || width == null || height == null)
@@ -171,16 +353,29 @@ public final class PayCostCalculator
}
}
}
// 退件费用
else if (PaySurchargeRules.RETURN.equals(rule))
{
if (orderStatus != null && orderStatus == 9)
if (orderStatus != null && REFUND_STATUS_SET.contains(orderStatus))
{
addFlat(result.getFees(), fee, currency, "订单已退件");
}
}
// 超重费
else if (PaySurchargeRules.EXTRA_KG.equals(rule))
{
if (sameSection(fee.getSectionName(), freightSection))
if (postcodeDriven)
{
if (postcode == null || postcode.isBlank())
{
result.getSkipped().add(name + ":订单没有邮编");
}
else if (PaySurchargeRules.matchesPostcode(fee.getPostcodeParam(), postcode))
{
addExtraKg(result.getFees(), fee, weight, currency);
}
}
else if (sameSection(fee.getSectionName(), freightSection))
{
addExtraKg(result.getFees(), fee, weight, currency);
}
@@ -278,7 +473,8 @@ public final class PayCostCalculator
}
for (PaySurcharge fee : product.getSurcharges())
{
if (fee == null || !PaySurchargeRules.EXTRA_KG.equals(fee.getCalcRule()) || fee.getAmount() == null)
if (fee == null || !PaySurchargeRules.EXTRA_KG.equals(fee.getCalcRule()) || fee.getAmount() == null
|| !blank(fee.getPostcodeParam()).isEmpty())
{
continue;
}
@@ -319,6 +515,90 @@ public final class PayCostCalculator
return top;
}
private static boolean remoteFee(PaySurcharge fee)
{
String name = blank(fee.getFeeName()).toLowerCase(Locale.ROOT);
return name.contains("偏远") || name.contains("岛屿") || name.contains("remote") || name.contains("island");
}
/** 邮编配置命中后,金额相同的那一档才收;分区写明时还要对上地区。 */
private static boolean bookApplies(List<PayRemoteBook.Hit> hits, PaySurcharge fee, String rule)
{
boolean extra = PaySurchargeRules.EXTRA_KG.equals(rule);
boolean zoned = !blank(fee.getZoneName()).isEmpty();
for (PayRemoteBook.Hit hit : hits)
{
if (hit == null || !sameFeeName(hit.getFeeName(), fee.getFeeName()))
{
continue;
}
boolean amountKnown = hit.getAmount() != null && fee.getAmount() != null;
if (amountKnown && hit.getAmount().compareTo(fee.getAmount()) != 0 && !extra)
{
continue;
}
boolean areaKnown = !blank(hit.getZoneName()).isEmpty() || !blank(hit.getRegionName()).isEmpty();
if (zoned && areaKnown && !sameArea(hit, fee))
{
continue;
}
if (extra && zoned && !sameArea(hit, fee))
{
continue;
}
if (extra && amountKnown && hit.getAmount().compareTo(fee.getAmount()) != 0 && !sameArea(hit, fee))
{
continue;
}
return true;
}
return false;
}
private static boolean sameFeeName(String bookName, String feeName)
{
String book = feeKey(bookName);
String fee = feeKey(feeName);
if (book.isEmpty())
{
return fee.contains("偏远") || fee.contains("岛屿") || fee.contains("remote") || fee.contains("island");
}
return fee.contains(book) || book.contains(fee);
}
private static String feeKey(String name)
{
return blank(name).toLowerCase(Locale.ROOT).replace("地区", "").replace(" ", "");
}
private static boolean sameArea(PayRemoteBook.Hit hit, PaySurcharge fee)
{
return PayZoneMatcher.sameZone(fee.getZoneName(), hit.getZoneName())
|| PayZoneMatcher.sameZone(fee.getZoneName(), hit.getRegionName());
}
private static boolean perKg(PaySurcharge fee)
{
String unit = blank(fee.getPriceUnit()).toUpperCase(Locale.ROOT);
return unit.contains("KG") || unit.contains("公斤");
}
private static void addPerKg(List<PayCostLine> fees, PaySurcharge fee, BigDecimal weight, String currency, String remark)
{
if (fee.getAmount() == null || weight == null)
{
return;
}
String feeCurrency = normalize(fee.getCurrency());
if (!feeCurrency.isEmpty() && !feeCurrency.equals(currency))
{
return;
}
BigDecimal amount = fee.getAmount().multiply(weight).setScale(2, RoundingMode.HALF_UP);
long scId = fee.getSurchargeId() == null ? 0L : fee.getSurchargeId();
fees.add(line("SURCHARGE", blank(fee.getFeeName()), scId, amount, currency, remark + " × " + plain(weight) + "kg"));
}
private static void addFlat(List<PayCostLine> fees, PaySurcharge fee, String currency, String remark)
{
PayCostLine line = matchedFee(fee, null, currency, remark);
@@ -0,0 +1,177 @@
package com.bms.price.pay;
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 java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.bms.price.domain.PayPostcodeGroup;
import com.bms.price.domain.PayPostcodeLine;
/**
* 产品在应付邮编配置里的偏远名单。报价表或销售产品与价卡一致时,这份名单决定是否加偏远附加费。
*/
public final class PayRemoteBook
{
private static final Pattern AMOUNT = Pattern.compile("(\\d+(?:\\.\\d+)?)");
private PayRemoteBook()
{
}
/** 命中的一条偏远邮编,带上这一组的费用名和金额。 */
public static final class Hit
{
private final String feeName;
private final BigDecimal amount;
private final String zoneName;
private final String regionName;
public Hit(String feeName, BigDecimal amount, String zoneName, String regionName)
{
this.feeName = feeName == null ? "" : feeName;
this.amount = amount;
this.zoneName = zoneName == null ? "" : zoneName;
this.regionName = regionName == null ? "" : regionName;
}
public String getFeeName()
{
return feeName;
}
public BigDecimal getAmount()
{
return amount;
}
public String getZoneName()
{
return zoneName;
}
public String getRegionName()
{
return regionName;
}
}
public static boolean remoteGroup(PayPostcodeGroup group)
{
if (group == null)
{
return false;
}
String coverage = group.getCoverage() == null ? "" : group.getCoverage().trim();
if ("REMOTE".equalsIgnoreCase(coverage))
{
return true;
}
if ("REACH".equalsIgnoreCase(coverage) || "UNREACH".equalsIgnoreCase(coverage))
{
return false;
}
String fee = group.getFeeName() == null ? "" : group.getFeeName();
return fee.contains("偏远") || fee.toLowerCase(Locale.ROOT).contains("remote");
}
/**
* 没有偏远配置时返回 null,沿用价卡上的邮编条件。
* 有配置但邮编没命中时返回空列表,不加偏远附加费。
*/
public static List<Hit> hits(List<PayPostcodeGroup> groups, List<PayPostcodeLine> lines, String postcode,
String countryCode, String countryName)
{
if (groups == null || groups.isEmpty())
{
return null;
}
boolean anyRemote = false;
Map<Long, PayPostcodeGroup> remote = new LinkedHashMap<>();
for (PayPostcodeGroup group : groups)
{
if (group == null || group.getGroupId() == null || !remoteGroup(group))
{
continue;
}
anyRemote = true;
if (sameCountry(group, countryCode, countryName))
{
remote.put(group.getGroupId(), group);
}
}
if (!anyRemote)
{
return null;
}
if (remote.isEmpty())
{
return new ArrayList<>();
}
if (postcode == null || postcode.isBlank() || lines == null || lines.isEmpty())
{
return new ArrayList<>();
}
List<Hit> hits = new ArrayList<>();
for (PayPostcodeLine line : lines)
{
if (line == null || !remote.containsKey(line.getGroupId()) || !PayZoneMatcher.matchesLine(line, postcode))
{
continue;
}
PayPostcodeGroup group = remote.get(line.getGroupId());
String region = first(line.getRegionName(), line.getRegionNameCn());
hits.add(new Hit(group.getFeeName(), amountOf(group.getFeeText()), line.getZoneName(), region));
}
return hits;
}
public static BigDecimal amountOf(String feeText)
{
if (feeText == null || feeText.isBlank())
{
return null;
}
Matcher matcher = AMOUNT.matcher(feeText);
if (!matcher.find())
{
return null;
}
return new BigDecimal(matcher.group(1));
}
private static boolean sameCountry(PayPostcodeGroup group, String countryCode, String countryName)
{
boolean orderBlank = blank(countryCode) && blank(countryName);
boolean groupBlank = blank(group.getCountryCode()) && blank(group.getCountryName());
if (orderBlank || groupBlank)
{
return true;
}
if (!blank(countryCode) && countryCode.equalsIgnoreCase(group.getCountryCode().trim()))
{
return true;
}
return !blank(countryName) && countryName.trim().equals(group.getCountryName() == null ? "" : group.getCountryName().trim());
}
private static String first(String left, String right)
{
if (left != null && !left.isBlank())
{
return left.trim();
}
return right == null ? "" : right.trim();
}
private static boolean blank(String value)
{
return value == null || value.isBlank();
}
}
@@ -29,6 +29,11 @@ public final class PaySurchargeRules
/** 超过重量段上限后,按超出的公斤数乘单价 */
public static final String EXTRA_KG = "EXTRA_KG";
/** 邮编已经落到这个分区,再按重量区间收取,例如英国高地 */
public static final String ZONE = "ZONE";
private static final Pattern REMOTE_PREFIX = Pattern.compile("(\\d{1,5}(?:\\s*[、,,]\\s*\\d{1,5})*)\\s*邮编");
private static final Pattern RANGE = Pattern.compile("([A-Z]{1,2})(\\d{1,2})\\s*-\\s*(\\d{1,2})");
private static final Pattern DISTRICT = Pattern.compile("([A-Z]{1,2})(\\d{1,2})");
@@ -107,14 +112,24 @@ public final class PaySurchargeRules
public static boolean matchesPostcode(String param, String postcode)
{
UkPostcode parsed = parseUk(postcode);
if (parsed == null || param == null || param.isBlank())
if (param == null || param.isBlank() || postcode == null || postcode.isBlank())
{
return false;
}
UkPostcode parsed = parseUk(postcode);
String digits = postcode.replaceAll("\\D", "");
for (String token : param.split(","))
{
if (tokenMatches(token.trim().toUpperCase(Locale.ROOT), parsed))
String value = token.trim().toUpperCase(Locale.ROOT);
if (value.isEmpty())
{
continue;
}
if (parsed != null && tokenMatches(value, parsed))
{
return true;
}
if (parsed == null && value.matches("\\d{1,5}") && !digits.isEmpty() && digits.startsWith(value))
{
return true;
}
@@ -122,6 +137,28 @@ public final class PaySurchargeRules
return false;
}
/** 从“07邮编开头”“35、38邮编开头”取出数字前缀。没有邮编字样时不猜。 */
public static String remotePrefixes(String text)
{
if (text == null || !text.contains("邮编"))
{
return "";
}
List<String> tokens = new ArrayList<>();
Matcher matcher = REMOTE_PREFIX.matcher(text);
while (matcher.find())
{
for (String part : matcher.group(1).split("[、,,\\s]+"))
{
if (part.matches("\\d{1,5}") && !tokens.contains(part))
{
tokens.add(part);
}
}
}
return String.join(",", tokens);
}
public static boolean matchesWeight(String param, BigDecimal weight)
{
if (param == null || param.isBlank() || weight == null)
@@ -212,7 +249,7 @@ public final class PaySurchargeRules
}
int cut = Math.max(desc.lastIndexOf(';'), desc.lastIndexOf(';'));
String source = cut >= 0 ? desc.substring(cut + 1) : desc;
String upper = source.toUpperCase(Locale.ROOT).replace(',', ',').replace('、', ',').replace('.', ',');
String upper = source.replace("邮编开头", " ").toUpperCase(Locale.ROOT).replace(',', ',').replace('、', ',').replace('.', ',');
List<String> tokens = new ArrayList<>();
for (String raw : upper.split("[,\\s]+"))
{
@@ -442,6 +442,7 @@ public class PayWorkbookParser
PaySurcharge copy = new PaySurcharge();
copy.setSectionName(fee.getSectionName());
copy.setFeeName(fee.getFeeName());
copy.setScId(fee.getScId());
copy.setZoneName(fee.getZoneName());
copy.setChargeText(fee.getChargeText());
copy.setAmount(fee.getAmount());
@@ -454,6 +455,9 @@ public class PayWorkbookParser
copy.setChargeTiming(fee.getChargeTiming());
copy.setCalcRule(fee.getCalcRule());
copy.setCalcParam(fee.getCalcParam());
copy.setPostcodeParam(fee.getPostcodeParam());
copy.setWeightMin(fee.getWeightMin());
copy.setWeightMax(fee.getWeightMax());
return copy;
}
@@ -1186,7 +1190,12 @@ public class PayWorkbookParser
{
detectedCurrency = product.getCurrency();
}
if (detectedCurrency == null || detectedCurrency.isBlank())
{
detectedCurrency = "EUR";
}
product.setCurrency(detectedCurrency);
fillSurchargeCurrency(product, detectedCurrency);
product.setWeightCount(product.getWeightBands().size());
product.setSurchargeCount(product.getSurcharges().size());
product.setExtraCount(product.getExtraLines().size());
@@ -1250,6 +1259,7 @@ public class PayWorkbookParser
kind[col] = columnKind(head, numericBelow(grid, col, data));
}
int added = product.getSurcharges().size();
Map<String, BigDecimal> includedKg = new LinkedHashMap<>();
while (data < grid.rows())
{
if (grid.blankRow(data) || isHardHeader(grid, data))
@@ -1296,8 +1306,7 @@ public class PayWorkbookParser
String desc = country.isBlank() ? weight : country + ";" + weight;
addSurcharge(product, feeName, feeName, zone, standard.trim(), desc, "");
PaySurcharge fee = product.getSurcharges().get(product.getSurcharges().size() - 1);
fee.setCalcRule(PaySurchargeRules.MANUAL);
fee.setCalcParam(weight);
applyFeeRateRule(fee, feeName, zone, weight, includedKg);
}
if (!priced && joinRow(grid, data).length() > 40)
{
@@ -1452,6 +1461,11 @@ public class PayWorkbookParser
}
}
priced = true;
if (isSurchargePriceHead(parent[col]))
{
addPricedSurcharge(product, blankTo(section, "价格"), parent[col], zoneOf(sub[col], parent[col]), weight, price);
continue;
}
boolean feeHead = isPriceHead(parent[col]);
PayWeightBand band = new PayWeightBand();
band.setSectionName(blankTo(section, "价格"));
@@ -3286,11 +3300,37 @@ public class PayWorkbookParser
fee.setCurrency("");
fee.setPriceUnit("");
}
if (fee.getCurrency() == null || fee.getCurrency().isBlank())
{
String cardCurrency = product.getCurrency();
fee.setCurrency(cardCurrency == null || cardCurrency.isBlank() ? "EUR" : cardCurrency.trim().toUpperCase(Locale.ROOT));
}
fee.setSortNo(product.getSurcharges().size() + 1);
PaySurchargeRules.apply(fee);
product.getSurcharges().add(fee);
}
/** 附加费币种为空时取价卡币种,价卡也没有则默认 EUR。 */
private static void fillSurchargeCurrency(PayProduct product, String cardCurrency)
{
if (product == null || product.getSurcharges() == null || product.getSurcharges().isEmpty())
{
return;
}
String fallback = cardCurrency == null || cardCurrency.isBlank() ? "EUR" : cardCurrency.trim().toUpperCase(Locale.ROOT);
for (PaySurcharge fee : product.getSurcharges())
{
if (fee == null)
{
continue;
}
if (fee.getCurrency() == null || fee.getCurrency().isBlank())
{
fee.setCurrency(fallback);
}
}
}
/** 燃油、去碳列是整张表的包含说明,只记一条,不跟每个重量段重复。 */
private void readFuelMark(ExcelGrid grid, PayProduct product)
{
@@ -4156,6 +4196,60 @@ public class PayWorkbookParser
|| lower.contains("line haul");
}
/**
* 偏远行按邮编前缀计费:首重整段收取,每增加只收超出部分。没有邮编列表的费用保持人工。
*/
private static void applyFeeRateRule(PaySurcharge fee, String feeName, String zone, String weight, Map<String, BigDecimal> includedKg)
{
boolean remote = feeName != null && feeName.contains("偏远");
boolean step = weight != null && (weight.contains("每增加") || weight.toLowerCase(Locale.ROOT).contains("additional"));
BigDecimal[] bounds = PayTexts.weightBounds(weight);
String prefixes = PaySurchargeRules.remotePrefixes(zone);
if (!step && bounds[1] != null)
{
includedKg.put(zone, bounds[1]);
}
BigDecimal included = includedKg.get(zone);
if (remote && step && !prefixes.isEmpty())
{
fee.setCalcRule(PaySurchargeRules.EXTRA_KG);
fee.setCalcParam(included == null ? "1" : included.stripTrailingZeros().toPlainString());
fee.setPostcodeParam(prefixes);
fee.setWeightMin(null);
fee.setWeightMax(null);
}
else if (remote && !prefixes.isEmpty())
{
fee.setCalcRule(PaySurchargeRules.POSTCODE);
fee.setCalcParam(prefixes);
fee.setPostcodeParam(prefixes);
fee.setWeightMin(bounds[0]);
fee.setWeightMax(bounds[1]);
}
else
{
fee.setCalcRule(PaySurchargeRules.MANUAL);
fee.setCalcParam(weight);
}
}
/** 价格表里和派送费并排的偏远列,按分区和重量区间记附加费,不进重量段。 */
private void addPricedSurcharge(PayProduct product, String section, String head, String zone, String weight, BigDecimal price)
{
String feeName = shortCharge(head);
String standard = price.stripTrailingZeros().toPlainString() + " " + feeUnit(head, weight);
addSurcharge(product, section, feeName, zone, standard.trim(), weight, "");
PaySurcharge fee = product.getSurcharges().get(product.getSurcharges().size() - 1);
BigDecimal[] bounds = PayTexts.weightBounds(weight);
if (bounds[0] != null && bounds[1] != null)
{
fee.setWeightMin(bounds[0]);
fee.setWeightMax(bounds[1]);
fee.setCalcRule(PaySurchargeRules.ZONE);
fee.setCalcParam(null);
}
}
private static String feeUnit(String head, String weight)
{
String unit = unitOf(head + " " + weight);
@@ -88,6 +88,11 @@ public final class PayZoneMatcher
}
}
public static boolean matchesLine(PayPostcodeLine line, String postcode)
{
return line != null && matchedLength(line, postcode) >= 0;
}
public static Decision resolve(List<String> zoneNames, List<PayPostcodeLine> lines, String postcode)
{
if (zoneNames == null || zoneNames.size() <= 1)
@@ -69,8 +69,8 @@ public class EsBillSearchStore implements IBillSearchStore
doc.put("bizId", bizId.trim());
doc.put("status", StringUtils.isEmpty(status) ? EsBizLogSupport.STATUS_SUCCESS : status.trim());
doc.put("error", StringUtils.isEmpty(errorMessage) ? null : errorMessage);
doc.put("request", parseOrRaw(requestJson));
// Normalize response.ok boolean -> 1/0: index mapping typed response.ok as long.
// Index dynamic mapping is strict on a few fields; coerce before PUT.
doc.put("request", normalizeRequestForEs(parseOrRaw(requestJson)));
doc.put("response", normalizeResponseForEs(parseOrRaw(responseJson)));
String ts = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
doc.put("updatedAt", ts);
@@ -86,7 +86,26 @@ public class EsBillSearchStore implements IBillSearchStore
}
}
/** Index historically mapped response.ok as long; coerce boolean to 1/0. */
/**
* request.bizDate is mapped as date (ISO / epoch only); bill writes "yyyy-MM-dd HH:mm:ss".
* request.taskId is mapped as long; UUID strings must not stay under taskId.
*/
private Object normalizeRequestForEs(Object request)
{
if (!(request instanceof JSONObject))
{
return request;
}
JSONObject obj = (JSONObject) request;
normalizeBizDateField(obj);
relocateNonNumericTaskId(obj);
return obj;
}
/**
* response.ok mapped as long; response.success as boolean; response.taskId as long.
* Local rebill DONE used UUID taskId + numeric success and was rejected by ES.
*/
private Object normalizeResponseForEs(Object response)
{
if (!(response instanceof JSONObject))
@@ -99,9 +118,54 @@ public class EsBillSearchStore implements IBillSearchStore
{
obj.put("ok", Boolean.TRUE.equals(ok) ? Integer.valueOf(1) : Integer.valueOf(0));
}
Object success = obj.get("success");
if (success instanceof Number)
{
obj.put("success", Boolean.valueOf(((Number) success).intValue() != 0));
}
relocateNonNumericTaskId(obj);
return obj;
}
private void normalizeBizDateField(JSONObject obj)
{
Object raw = obj.get("bizDate");
if (!(raw instanceof String))
{
return;
}
String bizDate = ((String) raw).trim();
// "yyyy-MM-dd HH:mm:ss" -> ISO-local so ES date mapper accepts it.
if (bizDate.length() >= 19 && bizDate.charAt(10) == ' ')
{
obj.put("bizDate", bizDate.substring(0, 10) + "T" + bizDate.substring(11));
}
}
private void relocateNonNumericTaskId(JSONObject obj)
{
Object taskId = obj.get("taskId");
if (!(taskId instanceof String))
{
return;
}
String text = ((String) taskId).trim();
if (text.isEmpty())
{
obj.remove("taskId");
return;
}
try
{
obj.put("taskId", Long.valueOf(Long.parseLong(text)));
}
catch (NumberFormatException e)
{
obj.remove("taskId");
obj.put("taskIdStr", text);
}
}
@Override
public BillSyncSnapshot get(String logType, String bizId)
{
@@ -5,19 +5,65 @@ import com.bms.price.domain.PayBill;
import com.bms.price.domain.PayBillCommand;
import com.bms.price.domain.PayBillPreview;
/**
* 应付账单。查询、预览、生成,以及确认、付款、作废。
*/
public interface IPayBillService
{
/**
* 按条件查询应付账单列表。
*
* @param query 账单号、供应商、状态、币种,空着的条件不过滤
* @return 账单头列表
*/
List<PayBill> selectPayBillList(PayBill query);
/**
* 查询一张应付账单,带上费用明细和操作日志。
*
* @param billId 应付账单ID
* @return 账单详情
*/
PayBill selectPayBillDetail(Long billId);
/**
* 预览可生成的订单。不重算费用,也不写账单。
*
* @param command 查询方式,以及订单号、计费日起止或提单号
* @return 可生成订单、未找到的单号、已经入账的订单
*/
PayBillPreview preview(PayBillCommand command);
/**
* 生成应付账单。重算范围内订单的尾程应付,再把订单费用抄成账单明细。
* 已经挂在未作废账单上的订单不会进入本次账单。
*
* @param command 供应商和取数范围
* @return 草稿账单,含明细和生成日志
*/
PayBill generate(PayBillCommand command);
/**
* 把草稿确认为已确认。
*
* @param billId 应付账单ID
* @return 成功时为 1
*/
int confirm(Long billId);
/**
* 把已确认账单登记为已付款。
*
* @param billId 应付账单ID
* @return 成功时为 1
*/
int markPaid(Long billId);
/**
* 作废账单。已付款的不能作废,作废后数据仍保留。
*
* @param command 账单ID和作废原因
* @return 成功时为 1
*/
int voidBill(PayBillCommand command);
}
@@ -2,8 +2,16 @@ package com.bms.price.service;
import com.bms.price.domain.PayOrderCostResult;
/** 按订单生成应付:渠道服务商上的应付产品,用订单基础数据计算。 */
/**
* 按订单计算尾程应付。用渠道上的应付产品和订单重量、尺寸、邮编取价,并写入订单应付。
*/
public interface IPayOrderCostService
{
/**
* 重算一票订单的尾程应付,覆盖原来的计算费用。
*
* @param billId 计费订单ID,对应 prc_order_bill.bill_id
* @return 本次算出的产品、版本、币种和费用明细
*/
PayOrderCostResult generate(String billId);
}
@@ -3,9 +3,11 @@ package com.bms.price.service;
import java.io.OutputStream;
import java.util.List;
import java.util.Date;
import com.bms.price.domain.LabelPackageVersion;
import com.bms.price.domain.PayParseProgress;
import com.bms.price.domain.PayPreview;
import com.bms.price.domain.PayPriceCompare;
import com.bms.price.domain.ChannelProductMap;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PayProductTerm;
import com.bms.price.domain.PaySaveCommand;
@@ -47,11 +49,56 @@ public interface IPayProductService
/** 公共模板下拉。payType 为空时按应付 AP */
List<PayProduct> selectTemplateOptions(String payType);
/** 渠道绑定的产品。返回的 originId 是不变的产品编号,价格是当前有效版 */
/** 渠道绑定的产品。返回的 originId 是不变的产品编号,价格是当前有效版;默认应付 AP */
PayProduct selectChannelPrice(String channelId);
/** 只绑定产品编号,不产生新版本。payType 为空时按应付 AP */
void bindChannel(String channelId, Long productId, Long priceSetId, String payType);
/** 按收付类型查询渠道绑定产品,payType 为空时按应付 AP */
PayProduct selectChannelPrice(String channelId, String payType);
/** 只绑定产品编号,不产生新版本;同时落 channel_code。payType 为空时按应付 AP */
void bindChannel(String channelId, Long productId, String payType);
/** 批量绑定渠道应收/应付产品;未传的产品不改原绑定 */
String batchBindChannel(java.util.List<String> channelIds, Long apProductId, Long arProductId);
/**
* 打单套餐预览:解析复用应付解析器,但「已存在」只按本套餐 price_set_id 判断,
* 不与应付公共模板互相挡导入。
*/
PayPreview previewLabel(byte[] bytes, String filename, String dictValue, String progressId, Long priceSetId);
/** 打单套餐导入:稳定 product_id,明细挂 term_id,term 写 price_set_id;跳过仅限本套餐已有生效版 */
String saveLabel(PaySaveCommand command);
/** 打单套餐价卡版本列表(按 term.version_no 聚合) */
List<LabelPackageVersion> selectLabelVersions(Long priceSetId);
/** 启动/修改打单套餐某一版生效时间,并视情况启用套餐 */
String activateLabelVersion(Long priceSetId, Integer versionNo, Date effectiveTime);
/** 删除打单套餐待生效版本(仅 status=0) */
int deleteLabelVersion(Long priceSetId, Integer versionNo);
/** 打单套餐内当前生效/待生效产品列表 */
List<PayProduct> selectLabelProducts(Long priceSetId);
/** 打单套餐某一版本的产品列表 */
List<PayProduct> selectLabelProductsByVersion(Long priceSetId, Integer versionNo);
/** 按 term 加载明细 */
PayProduct selectPayProductDetailByTerm(Long termId);
/** 从打单套餐移除产品(失效/清理对应 term 明细) */
int removeLabelProducts(Long priceSetId, Long[] productIds);
/** 打单套餐已绑定渠道列表 */
java.util.List<ChannelProductMap> listLabelChannels(Long priceSetId);
/** 打单套餐批量绑定渠道(写 AR + price_set_id) */
String bindLabelChannels(Long priceSetId, java.util.List<String> channelIds, Long productId);
/** 打单套餐解绑渠道 */
int unbindLabelChannel(Long priceSetId, String channelId);
/** 取消渠道上指定收付类型的产品。payType 为空时按应付 AP */
void unbindChannel(String channelId, String payType);
@@ -59,6 +106,11 @@ public interface IPayProductService
/** 按订单时间取这一产品当时有效的价格版本 */
PayProduct selectPriceForDate(String channelId, Date bizDate);
/**
* 打单套餐计费取价:渠道 AR 映射 → 稳定 product_id,再按套餐+计费日命中 term。
*/
PayProduct selectLabelPriceForDate(Long priceSetId, String channelId, Date bizDate);
/** 对照两个版本的重量段和附加费 */
PayPriceCompare compare(Long leftId, Long rightId);
@@ -0,0 +1,26 @@
package com.bms.price.service;
import java.util.List;
import com.bms.price.airbill.domain.SrvBillAirAllocFee;
/**
* 把提单上待分摊的费用均摊到关联订单。
*/
public interface ISrvBillAirAllocService
{
/**
* 查出勾选提单上需要分摊、且尚未分摊的费用。
*
* @param billCodes 提单号,最多 5 个
* @return 费用和不能分摊的原因
*/
List<SrvBillAirAllocFee> preview(List<String> billCodes);
/**
* 按费用上的分摊维度把金额摊到每个订单,并改费用状态为已分摊。整次处理在一个事务里,写入按 1000 条一批。
*
* @param billCodes 提单号,最多 5 个
* @return 给页面的处理结果
*/
String allocate(List<String> billCodes);
}
@@ -16,4 +16,22 @@ public interface ISrvBillAirFeeService
/** 只写入有变动的行,并按行记录修改前后。返回给页面的提示。 */
String save(SrvBillAirFeeSave command);
/**
* 已分摊的费用确认为已确定。
*
* @param billCode 提单号
* @param feeId 费用 ID
* @return 给页面的提示
*/
String confirm(String billCode, Long feeId);
/**
* 作废已分摊或已确定的费用。订单上的分摊明细逻辑删除,这条提单费用也逻辑删除。
*
* @param billCode 提单号
* @param feeId 费用 ID
* @return 给页面的提示
*/
String voidFee(String billCode, Long feeId);
}
@@ -48,12 +48,24 @@ public class PayBillServiceImpl implements IPayBillService
@Autowired
private BmsSupplierMapper supplierMapper;
/**
* 按账单号、供应商、状态、币种查询应付账单。
*
* @param query 查询条件,空字段不参与过滤
* @return 账单头列表
*/
@Override
public List<PayBill> selectPayBillList(PayBill query)
{
return payBillMapper.selectPayBillList(query);
}
/**
* 查询一张应付账单,并装上费用明细和操作日志。
*
* @param billId 应付账单ID
* @return 账单详情
*/
@Override
public PayBill selectPayBillDetail(Long billId)
{
@@ -67,12 +79,25 @@ public class PayBillServiceImpl implements IPayBillService
return bill;
}
/**
* 预览可生成的订单。不重算尾程,也不写账单。
*
* @param command 查询方式,以及订单号、计费日或提单号
* @return 可生成订单、未找到的单号、已经入账的订单
*/
@Override
public PayBillPreview preview(PayBillCommand command)
{
return collect(command, false);
}
/**
* 生成应付账单。校验供应商后,对未入账订单重算尾程,再把订单费用抄成账单明细。
* 所选订单币种必须一致。账单以草稿写入,并记一条生成日志。
*
* @param command 供应商和取数范围。sourceType 为 ORDER、TIME 或 LADING
* @return 刚生成的草稿账单,含明细和日志
*/
@Override
@Transactional(rollbackFor = Exception.class)
public PayBill generate(PayBillCommand command)
@@ -165,6 +190,12 @@ public class PayBillServiceImpl implements IPayBillService
return selectPayBillDetail(bill.getBillId());
}
/**
* 把草稿账单改为已确认。
*
* @param billId 应付账单ID
* @return 成功时为 1
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int confirm(Long billId)
@@ -182,6 +213,12 @@ public class PayBillServiceImpl implements IPayBillService
return 1;
}
/**
* 把已确认账单登记为已付款。
*
* @param billId 应付账单ID
* @return 成功时为 1
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int markPaid(Long billId)
@@ -199,6 +236,12 @@ public class PayBillServiceImpl implements IPayBillService
return 1;
}
/**
* 作废账单。必须填写作废原因。已作废的不能再作废,已付款的不能直接作废。
*
* @param command 账单ID和作废原因
* @return 成功时为 1
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int voidBill(PayBillCommand command)
@@ -232,6 +275,13 @@ public class PayBillServiceImpl implements IPayBillService
return 1;
}
/**
* 按订单号、计费日或提单号查出订单,并分成可生成和已入账两组。
*
* @param command 查询方式和对应的单号或日期
* @param forGenerate 为 true 时不把未找到的单号写进提示,留给生成时抛错
* @return 预览结果。可生成订单放在 orders,已入账订单放在 occupied
*/
private PayBillPreview collect(PayBillCommand command, boolean forGenerate)
{
String mode = mode(command);
@@ -301,11 +351,23 @@ public class PayBillServiceImpl implements IPayBillService
return preview;
}
/**
* 取出还没有挂在未作废账单上的订单。
*
* @param preview 预览结果
* @return 可以进入本次账单的订单
*/
private List<PayBillOrder> freeOrders(PayBillPreview preview)
{
return preview.getOrders();
}
/**
* 取这批订单里第一个非空币种。都没有时用 CNY,后面仍会按费用行再核对。
*
* @param orders 本次要出账的订单
* @return 币种代码
*/
private String currencyOf(List<PayBillOrder> orders)
{
String currency = "";
@@ -320,6 +382,13 @@ public class PayBillServiceImpl implements IPayBillService
return currency.isEmpty() ? "CNY" : currency;
}
/**
* 用计费订单ID找到对应订单,用来回填订单号和提单号。
*
* @param orders 本次订单
* @param billId 计费订单ID
* @return 订单;对不上时返回 null
*/
private PayBillOrder findOrder(List<PayBillOrder> orders, String billId)
{
for (PayBillOrder order : orders)
@@ -332,6 +401,12 @@ public class PayBillServiceImpl implements IPayBillService
return null;
}
/**
* 读取账单头。账单不存在时抛出业务异常。
*
* @param billId 应付账单ID
* @return 账单头
*/
private PayBill required(Long billId)
{
PayBill bill = payBillMapper.selectPayBillById(billId);
@@ -342,6 +417,16 @@ public class PayBillServiceImpl implements IPayBillService
return bill;
}
/**
* 写一条应付账单操作日志。
*
* @param billId 应付账单ID
* @param type 操作类型:CREATE 生成、CONFIRM 确认、PAY 付款、VOID 作废
* @param from 变更前状态,新建时为空
* @param to 变更后状态
* @param desc 操作说明
* @param operator 操作人账号
*/
private void writeLog(Long billId, String type, String from, String to, String desc, String operator)
{
PayBillLog log = new PayBillLog();
@@ -354,12 +439,23 @@ public class PayBillServiceImpl implements IPayBillService
payBillMapper.insertLog(log);
}
/**
* 生成应付账单号。格式为 AP、年月、8 位随机码。
*
* @return 账单号
*/
private String nextNo()
{
return "AP" + new SimpleDateFormat("yyyyMM").format(new Date())
+ IdUtils.fastSimpleUUID().substring(0, 8).toUpperCase();
}
/**
* 把 yyyy-MM-dd 转成日期。空文本返回 null。
*
* @param text 计费日起或止
* @return 日期
*/
private Date parseDay(String text)
{
if (text == null || text.isBlank())
@@ -370,6 +466,12 @@ public class PayBillServiceImpl implements IPayBillService
return java.sql.Date.valueOf(day);
}
/**
* 读取查询方式,并转成大写。
*
* @param command 预览或生成参数
* @return ORDER 订单号、TIME 计费日、LADING 提单号
*/
private String mode(PayBillCommand command)
{
if (command == null || command.getSourceType() == null || command.getSourceType().isBlank())
@@ -379,6 +481,12 @@ public class PayBillServiceImpl implements IPayBillService
return command.getSourceType().trim().toUpperCase(Locale.ROOT);
}
/**
* 把订单号或提单号按逗号、顿号、分号、空白拆开,并去掉重复和空白。
*
* @param text 页面上粘贴的单号原文
* @return 去重后的单号
*/
static List<String> tokens(String text)
{
LinkedHashSet<String> values = new LinkedHashSet<>();
@@ -1,11 +1,8 @@
package com.bms.price.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -18,6 +15,7 @@ import com.bms.price.domain.PayOrderCostResult;
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.PayWeightBand;
import com.bms.price.domain.PrcOrderBill;
import com.bms.price.domain.PrcOrderBillExt;
@@ -29,6 +27,8 @@ 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.PayRemoteBook;
import com.bms.price.pay.PaySurchargeRules;
import com.bms.price.pay.PayZoneMatcher;
import com.bms.price.service.IPayOrderCostService;
import com.bms.price.service.IPayProductService;
@@ -60,6 +60,13 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
@Autowired
private PayPostcodeMapper payPostcodeMapper;
/**
* 重算一票订单的尾程应付并落库。
* 先找渠道和计费日对应的价卡版本,再用重量、尺寸、邮编算出费用,写回订单应付。
*
* @param billId 计费订单ID
* @return 本次使用的渠道、价卡版本和费用明细
*/
@Override
@Transactional(rollbackFor = Exception.class)
public PayOrderCostResult generate(String billId)
@@ -75,13 +82,16 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
}
PrcOrderBillExt ext = orderBillExtMapper.selectByBillId(bill.getBillId());
ServiceChannel channel = resolveChannel(ext);
java.util.Date bizDate = bill.getBizDate() != null ? bill.getBizDate() : bill.getOrderTime();
Date bizDate = bill.getBizDate() != null ? bill.getBizDate() : bill.getOrderTime();
PayProduct product = payProductService.selectPriceForDate(channel.getId(), bizDate);
BigDecimal weight = firstPositive(bill.getChargeWeight(), bill.getWeight(), bill.getActualWeight(), bill.getReceiveWeight());
Integer orderStatus = bill.getOrderStatus() != null ? bill.getOrderStatus() : (ext == null ? null : ext.getOrderStatus());
String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
List<PayPostcodeGroup> linked = linkedGroups(product);
String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked);
// 根据邮编判断是否是偏远地区
List<PayRemoteBook.Hit> remoteHits = remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName());
PayOrderCostResult result = PayCostCalculator.calculate(product, weight, bill.getPkgLength(), bill.getPkgWidth(),
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, bizDate, orderStatus);
bill.getPkgHeight(), bill.getDestPostcode(), zoneName, bizDate, orderStatus, remoteHits);
result.setBillId(bill.getBillId());
result.setChannelId(channel.getId());
result.setChannelName(channel.getChannelName());
@@ -101,14 +111,109 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return result;
}
/** 价卡分成多个地区时,用邮编在对应分区表里选出价格列。 */
private String resolveZone(ServiceChannel channel, PayProduct product, String postcode, String countryCode, String countryName)
/**
* 用产品名称、报价工作表、字典值和关联分区表,对上这份产品的邮编配置。
*
* @param product 当前价卡版本
* @return 名称能对上的邮编组,没有时为空列表
*/
private List<PayPostcodeGroup> linkedGroups(PayProduct product)
{
List<String> names = new ArrayList<>();
addName(names, product.getProductName());
addName(names, product.getSheetName());
addName(names, product.getDictValue());
addName(names, product.getRelatedSheet());
if (names.isEmpty())
{
return new ArrayList<>();
}
List<PayPostcodeGroup> found = payPostcodeMapper.selectGroupsForProduct(names);
return found == null ? new ArrayList<>() : found;
}
/**
* 把非空名称放进匹配列表,已有的不重复加入。
*
* @param names 已经收集的名称
* @param value 产品名、工作表名或字典值
*/
private static void addName(List<String> names, String value)
{
if (value == null || value.isBlank())
{
return;
}
String name = value.trim();
if (!names.contains(name))
{
names.add(name);
}
}
/**
* 用产品自己的偏远邮编判断这票是否偏远。没有偏远配置时返回 null,计费改看价卡上的邮编条件。
*
* @param linked 已对上的邮编组
* @param postcode 收件邮编
* @param countryCode 目的国二字码
* @param countryName 目的国名称
* @return 命中的偏远分区;有配置但没命中时返回空列表
*/
private List<PayRemoteBook.Hit> remoteHits(List<PayPostcodeGroup> linked, String postcode, String countryCode, String countryName)
{
List<Long> remoteIds = new ArrayList<>();
boolean anyRemote = false;
for (PayPostcodeGroup group : linked)
{
if (group == null || group.getGroupId() == null || !PayRemoteBook.remoteGroup(group))
{
continue;
}
anyRemote = true;
if (sameCountry(group, countryCode, countryName))
{
remoteIds.add(group.getGroupId());
}
}
if (!anyRemote)
{
return null;
}
if (remoteIds.isEmpty())
{
return new ArrayList<>();
}
List<PayPostcodeLine> lines = postcode == null || postcode.isBlank()
? new ArrayList<>() : payPostcodeMapper.selectLinesByGroups(remoteIds);
return PayRemoteBook.hits(linked, lines, postcode, countryCode, countryName);
}
/**
* 价卡有多个地区时,选出这一票对应的价格列。优先用产品关联的邮编分区,对不上再按名称关键字找。
* 只有一个地区时返回 null,计费不再按分区过滤。
*
* @param channel 订单渠道,关键字匹配时备用
* @param product 当前价卡版本
* @param postcode 收件邮编
* @param countryCode 目的国二字码
* @param countryName 目的国名称
* @param linked 已对上的邮编组
* @return 价卡上的地区名
*/
private String resolveZone(ServiceChannel channel, PayProduct product, String postcode, String countryCode, String countryName,
List<PayPostcodeGroup> linked)
{
List<String> zoneNames = zoneNames(product);
if (zoneNames.size() <= 1)
{
return null;
}
List<Long> linkedZoneIds = zoneGroupIds(linked, countryCode, countryName);
if (!linkedZoneIds.isEmpty())
{
return decideZone(zoneNames, linkedZoneIds, postcode);
}
List<String> tokens = PayZoneMatcher.searchTokens(product.getProductName(), product.getSheetName());
if (tokens.isEmpty())
{
@@ -148,35 +253,105 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
{
throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,邮编分区对不上价卡上的地区");
}
PayZoneMatcher.Decision decision = PayZoneMatcher.resolve(zoneNames, payPostcodeMapper.selectLinesByGroups(new ArrayList<>(usable)), postcode);
return decideZone(zoneNames, new ArrayList<>(usable), postcode);
}
/**
* 在给定邮编组里,用收件邮编决定价卡地区。对不上时抛出业务异常。
*
* @param zoneNames 价卡上的地区名
* @param groupIds 参与匹配的邮编组
* @param postcode 收件邮编
* @return 命中的地区名
*/
private String decideZone(List<String> zoneNames, List<Long> groupIds, String postcode)
{
PayZoneMatcher.Decision decision = PayZoneMatcher.resolve(zoneNames, payPostcodeMapper.selectLinesByGroups(groupIds), postcode);
if (decision.getMessage() != null)
{
throw new ServiceException(decision.getMessage());
}
if (decision.getZoneName() == null)
{
throw new ServiceException("邮编没有对上产品「" + product.getProductName() + "」的地区");
throw new ServiceException("邮编没有对上价卡地区");
}
return decision.getZoneName();
}
/**
* 取出用来选派送费的普通分区。偏远、附加费邮编和不可达不参与选区。
*
* @param linked 已对上的邮编组
* @param countryCode 目的国二字码
* @param countryName 目的国名称
* @return 可参与选区的邮编组ID
*/
private static List<Long> zoneGroupIds(List<PayPostcodeGroup> linked, String countryCode, String countryName)
{
List<Long> ids = new ArrayList<>();
if (linked == null)
{
return ids;
}
for (PayPostcodeGroup group : linked)
{
if (group == null || group.getGroupId() == null || PayRemoteBook.remoteGroup(group) || "FEE".equals(group.getConfigKind()))
{
continue;
}
if ("UNREACH".equalsIgnoreCase(group.getCoverage() == null ? "" : group.getCoverage().trim()))
{
continue;
}
if (!sameCountry(group, countryCode, countryName))
{
continue;
}
ids.add(group.getGroupId());
}
return ids;
}
/**
* 收集价卡重量段和分区附加费上的地区名。
*
* @param product 当前价卡版本
* @return 去重后的地区名
*/
private static List<String> zoneNames(PayProduct product)
{
Set<String> names = new LinkedHashSet<>();
if (product.getWeightBands() == null)
if (product.getWeightBands() != null)
{
return new ArrayList<>();
}
for (PayWeightBand band : product.getWeightBands())
{
if (band != null && band.getZoneName() != null && !band.getZoneName().isBlank())
for (PayWeightBand band : product.getWeightBands())
{
names.add(band.getZoneName().trim());
if (band != null && band.getZoneName() != null && !band.getZoneName().isBlank())
{
names.add(band.getZoneName().trim());
}
}
}
if (product.getSurcharges() != null)
{
for (PaySurcharge fee : product.getSurcharges())
{
if (fee != null && PaySurchargeRules.ZONE.equals(fee.getCalcRule()) && fee.getZoneName() != null && !fee.getZoneName().isBlank())
{
names.add(fee.getZoneName().trim());
}
}
}
return new ArrayList<>(names);
}
/**
* 判断邮编组是否和订单目的国相同。两边都没写国家时视为相同。
*
* @param group 邮编组
* @param countryCode 订单目的国二字码
* @param countryName 订单目的国名称
* @return 国家能对上时为 true
*/
private static boolean sameCountry(PayPostcodeGroup group, String countryCode, String countryName)
{
if (blank(countryCode) && blank(countryName))
@@ -194,6 +369,12 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return !blank(countryName) && countryName.equals(group.getCountryName());
}
/**
* 从订单扩展找出渠道。先按渠道ID,再按渠道编码,最后按渠道名称。
*
* @param ext 订单计费扩展
* @return 服务渠道
*/
private ServiceChannel resolveChannel(PrcOrderBillExt ext)
{
if (ext == null)
@@ -221,6 +402,14 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return channel;
}
/**
* 保存订单应付主表。已有记录则更新合计,没有则新建。合计只写本次尾程结果。
*
* @param bill 计费订单
* @param result 本次尾程计算结果
* @param operator 操作人账号
* @return 保存后的订单应付
*/
private PrcPayBill saveBill(PrcOrderBill bill, PayOrderCostResult result, String operator)
{
PrcPayBill existed = payBillMapper.selectByBillId(bill.getBillId());
@@ -250,6 +439,13 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return row;
}
/**
* 用本次算出的尾程费用替换订单上的计算费用。来源不是计算的费用行会保留。
*
* @param billId 计费订单ID
* @param payBillId 订单应付主表ID
* @param fees 本次算出的费用
*/
private void saveFees(String billId, String payBillId, List<PayCostLine> fees)
{
payBillFeeMapper.deleteByBillId(billId);
@@ -281,6 +477,12 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
}
}
/**
* 把日期格式化成 yyyy-MM-dd,供结果说明使用。空日期表示不限。
*
* @param date 有效期起或止
* @return 日期文本
*/
private static String day(java.util.Date date)
{
if (date == null)
@@ -294,6 +496,12 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return date.toInstant().atZone(java.time.ZoneId.of("GMT+8")).toLocalDate().toString();
}
/**
* 按传入顺序取第一个大于 0 的重量。
*
* @param values 计费重、重量、实重、收货重
* @return 第一个正数;都没有时返回 null
*/
private static BigDecimal firstPositive(BigDecimal... values)
{
if (values == null)
@@ -310,6 +518,12 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
return null;
}
/**
* 判断文本是否为空。
*
* @param value 待判断文本
* @return 为 null 或空白时返回 true
*/
private static boolean blank(String value)
{
return value == null || value.isBlank();
File diff suppressed because it is too large Load Diff
@@ -6,7 +6,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
@@ -28,8 +27,8 @@ import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bms.ar.enums.ArIncomeBillFeeStatus;
import com.bms.ar.enums.ArOrderBillStatus;
import com.bms.receivable.enums.ArIncomeBillFeeStatus;
import com.bms.receivable.enums.ArOrderBillStatus;
import com.bms.common.annotation.DataScope;
import com.bms.common.core.domain.entity.SysUser;
import com.bms.common.exception.ServiceException;
@@ -207,21 +206,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
assertOrderBillEditable(request.getOrderNo());
PrcOrderBill existed = orderBillMapper.selectPrcOrderBillByOrderNo(request.getOrderNo());
BigDecimal systemWeight = request.getWeight();
// Upstream Oracle sync: always use TAB_ORDER weight (same overwrite as weight/charge_weight).
// Local rebill / manual charge_weight edit: keep resolveCalcWeight preference.
BigDecimal calcWeight = isUpstreamSyncRequest(request)
? systemWeight
: resolveCalcWeight(existed, systemWeight);
// Three-side sum rule disabled: upstream already applies it.
// Manual charge_weight wins; otherwise apply active biz rules (e.g. three-side).
// if (!isManualChargeWeight(existed))
// {
// BigDecimal ruled = bizRuleService.resolveWeightByRule(request, systemWeight);
// if (ruled != null)
// {
// calcWeight = ruled;
// }
// }
BigDecimal calcWeight = resolveBillCalcWeight(request, existed, systemWeight);
request.setWeight(calcWeight);
TmsPriceQuoteResult result = tmsPriceQuoteService.calculate(request);
persistBill(request, systemWeight, bizDate, result);
@@ -1836,8 +1821,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
bill.setCountryName(result.getCountryName());
}
// weight = system/original; charge_weight follows weight on upstream sync,
// otherwise may keep manual override via resolvePersistChargeWeight.
// weight = system/original upstream weight; charge_weight may differ when VOL_8000
// (or manual override) raised/lowered the billed weight.
bill.setWeight(weight);
bill.setBizDate(bizDate);
bill.setTmsId(request.getTmsId() == null ? null : Long.valueOf(request.getTmsId()));
@@ -1857,7 +1842,9 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
bill.setEffectiveDate(result.getEffectiveDate());
if (isUpstreamSyncRequest(request))
{
bill.setChargeWeight(weight);
// request.weight already carries ruled/calc weight used for quote
BigDecimal cw = request.getWeight() != null ? request.getWeight() : weight;
bill.setChargeWeight(cw);
}
else
{
@@ -2883,6 +2870,51 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
return systemWeight;
}
/**
* Resolve weight used for quote/persist.
* Upstream: TAB_ORDER weight then biz-rule. Local: manual charge_weight wins, else biz-rule.
*/
private BigDecimal resolveBillCalcWeight(TmsPriceBillRequest request, PrcOrderBill existed,
BigDecimal systemWeight)
{
BigDecimal calcWeight = isUpstreamSyncRequest(request)
? systemWeight
: resolveCalcWeight(existed, systemWeight);
if (isUpstreamSyncRequest(request) || !isManualChargeWeight(existed))
{
calcWeight = applyBizRuleWeight(request, calcWeight);
}
return calcWeight;
}
/**
* Upstream sync / soft-fail: keep original weight, charge_weight may follow biz-rule.
*/
private void applyUpstreamWeightFields(PrcOrderBill bill, TmsPriceBillRequest request)
{
if (bill == null || request == null || request.getWeight() == null)
{
return;
}
BigDecimal systemWeight = request.getWeight();
bill.setWeight(systemWeight);
bill.setChargeWeight(applyBizRuleWeight(request, systemWeight));
}
/**
* Biz-rule charge weight (VOL_8000 etc).
* To disable: comment out the resolveWeightByRule call and always return baseWeight.
*/
private BigDecimal applyBizRuleWeight(TmsPriceBillRequest request, BigDecimal baseWeight)
{
if (request == null || baseWeight == null)
{
return baseWeight;
}
BigDecimal ruled = bizRuleService.resolveWeightByRule(request, baseWeight);
return ruled != null ? ruled : baseWeight;
}
/**
* Persist charge_weight: keep manual override when calc weight != system weight,
* or when existing bill already had a manual override.
@@ -3057,7 +3089,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
bill.setBillId(UUID.randomUUID().toString());
bill.setArBillStatus(ArOrderBillStatus.UNBILLED.getCode());
bill.setRefundStatus(BillRefundStatus.NONE.getCode());
bill.setBillingFailStatus(Integer.valueOf(BillBillingFailStatus.SUCCESS.getCode()));
// Order-source sync only: mark not billed until quote/bill runs.
bill.setBillingFailStatus(Integer.valueOf(BillBillingFailStatus.NOT_BILLED.getCode()));
bill.setFreightRate(BigDecimal.ZERO);
bill.setBaseFreightRate(BigDecimal.ZERO);
bill.setRegistrationFee(BigDecimal.ZERO);
@@ -3077,12 +3110,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
applyProductCodeMapping(bill, request);
Long customerId = resolveCustomerIdByCode(request.getCustomerCode(), bill.getCustomerId());
bill.setCustomerId(customerId == null ? Long.valueOf(0L) : customerId);
// Order-source sync: overwrite weight and charge_weight the same way from upstream.
if (request.getWeight() != null)
{
bill.setWeight(request.getWeight());
bill.setChargeWeight(request.getWeight());
}
applyUpstreamWeightFields(bill, request);
if (creating)
{
Date bizDate = request.getPickupDate() != null ? request.getPickupDate() : new Date();
@@ -3194,12 +3222,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
bill.setCustomerActiveStatus(BillCustomerActiveStatus.ACTIVE.getCode());
}
// Soft-fail snapshot: overwrite weight and charge_weight the same way from upstream.
bill.setWeight(request.getWeight());
if (request.getWeight() != null)
{
bill.setChargeWeight(request.getWeight());
}
applyUpstreamWeightFields(bill, request);
Date bizDate = StringUtils.isEmpty(request.getBizDate()) ? new Date() : resolveBizDate(request.getBizDate());
bill.setBizDate(bizDate);
if (StringUtils.isEmpty(bill.getCurrency()))
@@ -3267,11 +3290,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
applyUpstreamBillHeaderFields(bill, request);
applyProductCodeMapping(bill, request);
if (request.getWeight() != null)
{
bill.setWeight(request.getWeight());
bill.setChargeWeight(request.getWeight());
}
applyUpstreamWeightFields(bill, request);
}
applyBillingFailText(bill, billingFailStatus, errorMessage);
orderBillMapper.updatePrcOrderBill(bill);
@@ -3324,7 +3343,7 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
bill.setPkgHeight(request.getPkgHeight());
bill.setShipperName(request.getShipperName());
bill.setConsigneeName(request.getConsigneeName());
bill.setDestPostcode(request.getDestPostcode());
bill.setDestPostcode(StringUtils.normalizePostcode(request.getDestPostcode()));
bill.setWarehouseCode(request.getWarehouseCode());
bill.setOrderTime(request.getOrderTime());
applyUpstreamOrderStatus(bill, request);
@@ -40,6 +40,7 @@ import com.bms.price.domain.PrcSurchargeRel;
import com.bms.price.mapper.BmsProductCountryMapper;
import com.bms.price.mapper.BmsProductMapper;
import com.bms.price.mapper.PrcCustomerPriceSetMapper;
import com.bms.price.mapper.PrcOrderBillMapper;
import com.bms.price.mapper.PrcPriceSetDetailMapper;
import com.bms.price.mapper.PrcPriceSetMapper;
import com.bms.price.mapper.PrcPriceSetProductMapper;
@@ -76,6 +77,7 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
private static final String TYPE_FIXED = "FIXED";
private static final String CATEGORY_PACKAGE = PrcPriceSet.CATEGORY_PACKAGE;
private static final String CATEGORY_EXCLUSIVE = PrcPriceSet.CATEGORY_EXCLUSIVE;
private static final String CATEGORY_LABEL = PrcPriceSet.CATEGORY_LABEL;
private static final String TYPE_DISCOUNT = "DISCOUNT";
private static final String VER_DRAFT = "0";
private static final String VER_EFFECT = "1";
@@ -141,6 +143,9 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
@Autowired
private IBmsCustomerService bmsCustomerService;
@Autowired
private PrcOrderBillMapper orderBillMapper;
@Override
public PrcPriceSet selectPrcPriceSetById(Long priceSetId)
{
@@ -626,7 +631,7 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
{
throw new ServiceException(MessageUtils.message("price.set.version.notExists"));
}
// Draft / pending: hard delete; EFFECT: soft delete then reopen previous via refreshVersionStatus
// Draft / pending / effect may be deleted; expired stays view-only.
if (!VER_DRAFT.equals(version.getStatus())
&& !VER_PENDING.equals(version.getStatus())
&& !VER_EFFECT.equals(version.getStatus()))
@@ -634,9 +639,13 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
throw new ServiceException(MessageUtils.message("price.set.version.delete.statusNotAllowed"));
}
requireSet(version.getPriceSetId());
wipeVersionChildren(psvId, version.getStatus());
// Products / details / surcharge always physical delete.
surchargeRelMapper.physicalDeleteByPsvId(psvId);
detailMapper.physicalDeleteByPsvId(psvId);
setProductMapper.physicalDeleteByPsvId(psvId);
// Version: soft-delete when any order bill references psv_id; otherwise hard-delete.
int rows;
if (VER_EFFECT.equals(version.getStatus()))
if (orderBillMapper.countByPsvId(psvId) > 0)
{
rows = versionMapper.softDeleteById(psvId, updateBy);
}
@@ -2971,16 +2980,23 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
/** PACKAGE (default) or EXCLUSIVE. */
public static String normalizeSetCategory(String setCategory)
{
if (CATEGORY_EXCLUSIVE.equalsIgnoreCase(StringUtils.trim(setCategory)))
String raw = StringUtils.trim(setCategory);
if (CATEGORY_EXCLUSIVE.equalsIgnoreCase(raw))
{
return CATEGORY_EXCLUSIVE;
}
if (CATEGORY_LABEL.equalsIgnoreCase(raw))
{
return CATEGORY_LABEL;
}
return CATEGORY_PACKAGE;
}
private static String buildPriceSetCode(String setCategory, Long priceSetId)
{
String prefix = CATEGORY_EXCLUSIVE.equals(normalizeSetCategory(setCategory)) ? "EXC" : "SET";
String category = normalizeSetCategory(setCategory);
String prefix = CATEGORY_EXCLUSIVE.equals(category) ? "EXC"
: (CATEGORY_LABEL.equals(category) ? "LBL" : "SET");
return String.format("%s%04d", prefix, priceSetId);
}
@@ -783,15 +783,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
private static String normalizePostcode(String postcode)
{
if (StringUtils.isEmpty(postcode))
{
return postcode;
}
if (postcode.endsWith(".0") && postcode.matches("\\d+\\.0"))
{
return postcode.substring(0, postcode.length() - 2);
}
return postcode;
return StringUtils.normalizePostcode(postcode);
}
private static String normalizeCell(String text)
@@ -0,0 +1,472 @@
package com.bms.price.service.impl;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.bms.common.core.domain.entity.SysUser;
import com.bms.common.exception.ServiceException;
import com.bms.common.utils.DateUtils;
import com.bms.common.utils.SecurityUtils;
import com.bms.price.airbill.domain.SrvBillAirAllocFee;
import com.bms.price.airbill.domain.SrvBillAirAllocOrder;
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.mapper.SrvBillAirFeeMapper;
import com.bms.price.mapper.SrvBillAirMapper;
import com.bms.price.mapper.PrcPayBillFeeMapper;
import com.bms.price.service.ISrvBillAirAllocService;
/**
* 提单费用分摊。只处理标记为分摊、状态仍是未分摊的费用。
*/
@Service
public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService
{
private static final int MAX_BILLS = 5;
private static final int BATCH_SIZE = 1000;
private static final String DIM_ORDER = "1";
private static final String DIM_WEIGHT = "2";
private static final String FEE_TYPE = "LADING";
private static final String FEE_SOURCE = "LADING";
private static final BigDecimal ZERO = BigDecimal.ZERO;
@Autowired
private SrvBillAirAllocMapper allocMapper;
@Autowired
private SrvBillAirMapper billMapper;
@Autowired
private SrvBillAirFeeMapper feeMapper;
@Autowired
private PrcPayBillFeeMapper payBillFeeMapper;
@Override
public List<SrvBillAirAllocFee> preview(List<String> billCodes)
{
List<String> codes = normalize(billCodes);
List<SrvBillAirAllocFee> fees = dedupe(allocMapper.selectPendingFees(codes));
fillWeight(fees);
Map<String, List<SrvBillAirAllocOrder>> orders = ordersOf(codes);
for (SrvBillAirAllocFee fee : fees)
{
List<SrvBillAirAllocOrder> rows = orders.getOrDefault(fee.getBillCode(), List.of());
fee.setOrderCount(rows.size());
fee.setBlockReason(blockReason(fee, rows));
}
return fees;
}
@Override
@Transactional(rollbackFor = Exception.class)
public String allocate(List<String> billCodes)
{
List<String> codes = normalize(billCodes);
List<SrvBillAirAllocFee> fees = dedupe(allocMapper.selectPendingFees(codes));
fillWeight(fees);
if (fees.isEmpty())
{
throw new ServiceException("所选提单没有需要分摊的费用");
}
Map<String, List<SrvBillAirAllocOrder>> orders = ordersOf(codes);
for (SrvBillAirAllocFee fee : fees)
{
List<SrvBillAirAllocOrder> rows = orders.getOrDefault(fee.getBillCode(), List.of());
fee.setOrderCount(rows.size());
String reason = blockReason(fee, rows);
if (!reason.isEmpty())
{
throw new ServiceException(fee.getBillCode() + " " + blankName(fee) + ":" + reason);
}
}
Map<String, String> payBillIds = payBillIds(orders);
List<PrcPayBillFee> batch = new ArrayList<>(BATCH_SIZE);
int lineCount = 0;
for (SrvBillAirAllocFee fee : fees)
{
List<SrvBillAirAllocOrder> rows = orders.get(fee.getBillCode());
fee.setOrderCount(rows.size());
boolean byWeight = DIM_WEIGHT.equals(fee.getAllocDim());
List<BigDecimal> shares = split(byWeight ? weightAmount(fee) : fee.getPrice(), rows, byWeight);
for (int i = 0; i < rows.size(); i++)
{
batch.add(toOrderFee(fee, rows.get(i), shares.get(i), payBillIds));
if (batch.size() == BATCH_SIZE)
{
lineCount += flush(batch);
}
}
}
lineCount += flush(batch);
Date now = DateUtils.getNowDate();
String operator = SecurityUtils.getUsername();
int updated = allocMapper.markAllocated(feeIds(fees), operator, now);
if (updated != fees.size())
{
throw new ServiceException("费用状态已变化,请重新打开后再分摊");
}
writeLogs(fees, operator, now);
return "已将 " + fees.size() + " 条费用分摊为 " + lineCount + " 笔订单费用";
}
/**
* 按重量分摊的费用,按提单号补上实际重量和打板重量。按订单数量分摊的不查、不填。
* 这两个值只参与计算,不返回给页面。
*/
private void fillWeight(List<SrvBillAirAllocFee> fees)
{
List<String> codes = new ArrayList<>();
for (SrvBillAirAllocFee fee : fees)
{
if (fee != null && DIM_WEIGHT.equals(fee.getAllocDim()) && fee.getBillCode() != null && !codes.contains(fee.getBillCode()))
{
codes.add(fee.getBillCode());
}
}
if (codes.isEmpty())
{
return;
}
Map<String, SrvBillAirAllocFee> weights = new LinkedHashMap<>();
for (SrvBillAirAllocFee row : allocMapper.selectLadingWeight(codes))
{
if (row != null && row.getBillCode() != null)
{
weights.put(row.getBillCode(), row);
}
}
for (SrvBillAirAllocFee fee : fees)
{
if (fee == null || !DIM_WEIGHT.equals(fee.getAllocDim()))
{
continue;
}
SrvBillAirAllocFee weight = weights.get(fee.getBillCode());
if (weight == null)
{
continue;
}
fee.setActualWeight(weight.getActualWeight());
fee.setBandBoxWeight(weight.getBandBoxWeight());
}
}
/** 提单号去重、去空白,并限制单次 5 条。 */
private List<String> normalize(List<String> billCodes)
{
LinkedHashSet<String> codes = new LinkedHashSet<>();
if (billCodes != null)
{
for (String raw : billCodes)
{
if (raw == null)
{
continue;
}
for (String part : raw.split("[,,\\s]+"))
{
if (!part.isBlank())
{
codes.add(part.trim());
}
}
}
}
if (codes.isEmpty())
{
throw new ServiceException("请勾选提单");
}
if (codes.size() > MAX_BILLS)
{
throw new ServiceException("单次最多处理5条提单");
}
for (String code : codes)
{
if (billMapper.selectSrvBillAirByBillCode(code) == null)
{
throw new ServiceException("提单不存在:" + code);
}
}
return new ArrayList<>(codes);
}
private Map<String, List<SrvBillAirAllocOrder>> ordersOf(List<String> codes)
{
Map<String, List<SrvBillAirAllocOrder>> grouped = new LinkedHashMap<>();
for (SrvBillAirAllocOrder order : allocMapper.selectOrders(codes))
{
if (order.getBillId() == null || order.getBillId().isBlank())
{
continue;
}
grouped.computeIfAbsent(order.getBillCode(), key -> new ArrayList<>()).add(order);
}
return grouped;
}
private Map<String, String> payBillIds(Map<String, List<SrvBillAirAllocOrder>> orders)
{
List<String> billIds = new ArrayList<>();
for (List<SrvBillAirAllocOrder> rows : orders.values())
{
for (SrvBillAirAllocOrder order : rows)
{
billIds.add(order.getBillId());
}
}
Map<String, String> payIds = new LinkedHashMap<>();
for (int from = 0; from < billIds.size(); from += BATCH_SIZE)
{
List<String> chunk = billIds.subList(from, Math.min(from + BATCH_SIZE, billIds.size()));
for (PrcPayBill payBill : allocMapper.selectPayBills(chunk))
{
if (payBill.getBillId() != null && payBill.getPayBillId() != null)
{
payIds.put(payBill.getBillId(), payBill.getPayBillId());
}
}
}
return payIds;
}
private String blockReason(SrvBillAirAllocFee fee, List<SrvBillAirAllocOrder> orders)
{
if (fee.getPrice() == null)
{
return "费用没有价格";
}
if (fee.getPrice().signum() < 0)
{
return "费用价格不能小于0";
}
if (fee.getCurrency() == null || fee.getCurrency().isBlank())
{
return "费用没有币种";
}
if (fee.getLadingId() == null || fee.getLadingId().isBlank())
{
return "提单缺少主键";
}
if (!DIM_ORDER.equals(fee.getAllocDim()) && !DIM_WEIGHT.equals(fee.getAllocDim()))
{
return "未选择分摊维度";
}
if (orders == null || orders.isEmpty())
{
return "提单下没有关联订单";
}
if (DIM_WEIGHT.equals(fee.getAllocDim()))
{
if (fee.getActualWeight() == null || fee.getActualWeight().signum() <= 0)
{
return "提单没有实际重量,无法按重量分摊";
}
if (fee.getBandBoxWeight() == null || fee.getBandBoxWeight().signum() <= 0)
{
return "干线没有打板重量,无法按重量分摊";
}
if (totalWeight(orders).signum() <= 0)
{
return "订单没有可用重量,无法按重量分摊";
}
}
return "";
}
private PrcPayBillFee toOrderFee(SrvBillAirAllocFee fee, SrvBillAirAllocOrder order, BigDecimal amount, Map<String, String> payBillIds)
{
PrcPayBillFee row = new PrcPayBillFee();
row.setFeeId(UUID.randomUUID().toString());
row.setBillId(order.getBillId());
row.setPayBillId(payBillIds.get(order.getBillId()));
row.setFeeType(FEE_TYPE);
row.setFeeName(blankName(fee));
row.setScId(fee.getId() == null ? 0L : fee.getId());
row.setFeeLevel(fee.getFeeLevel());
row.setAmount(amount);
row.setCurrency(fee.getCurrency().trim());
row.setRoundMode("HALF_UP");
row.setRemark(remark(fee));
row.setFeeSource(FEE_SOURCE);
row.setSourceId(fee.getLadingId().trim());
row.setIsDeleted("0");
return row;
}
private int flush(List<PrcPayBillFee> batch)
{
if (batch.isEmpty())
{
return 0;
}
int rows = batch.size();
payBillFeeMapper.insertBatch(batch);
batch.clear();
return rows;
}
private void writeLogs(List<SrvBillAirAllocFee> fees, String operator, Date now)
{
SysUser user = SecurityUtils.getLoginUser().getUser();
String name = user.getNickName() == null || user.getNickName().isBlank() ? operator : user.getNickName();
for (SrvBillAirAllocFee fee : fees)
{
SrvBillAirFeeLog log = new SrvBillAirFeeLog();
log.setBillCode(fee.getBillCode());
log.setFeeId(fee.getId());
log.setOperationType(SrvBillAirFeeLog.UPDATE);
log.setSummary("分摊到 " + fee.getOrderCount() + " 票订单");
log.setChangeContent(JSON.toJSONString(List.of(
new SrvBillAirFeeLog.FieldChange("billFeeStatus", "费用状态", "未分摊", "已分摊"))));
log.setCreateBy(operator);
log.setCreateByName(name);
log.setCreateTime(now);
feeMapper.insertLog(log);
}
}
/**
* 按重量分摊时,先算出这一票提单实际可分摊的金额。
* 百分比 = 提单实际重量 srv_bill_air.actual_weight / 干线打板重量 srv_bill_air_flight.band_box_weight。
* 可分摊金额 = 费用价格 × 百分比,保留两位,四舍五入。
* 调用前须已确认实际重量和打板重量都大于 0。
*
* @param fee 待分摊的提单费用,带有实际重量和打板重量
* @return 按百分比算出的可分摊金额
*/
private static BigDecimal weightAmount(SrvBillAirAllocFee fee)
{
BigDecimal price = fee.getPrice().setScale(2, RoundingMode.HALF_UP);
return price.multiply(fee.getActualWeight()).divide(fee.getBandBoxWeight(), 2, RoundingMode.HALF_UP);
}
/**
* 把金额拆到每一票订单,结果保留两位。
* 按订单数量:每一票先向下取整,差额补在最后一票,合计等于费用价格。
* 按重量:传入的金额已是「费用价格 × 提单实际重量 / 干线打板重量」。
* 再按订单重量占这些订单总重量的比例分摊;前面的订单向下取整,差额补在最后一票有重量的订单上,合计等于这笔金额。
* 订单重量优先取计费重,没有计费重时取实际重量,再没有取收货重量。
*
* @param price 本次要拆开的金额。按重量时是百分比计算后的可分摊金额
* @param orders 该提单下的订单
* @param byWeight true 按订单重量占比,false 按订单数量均分
* @return 与订单顺序一致的分摊金额
*/
private static List<BigDecimal> split(BigDecimal price, List<SrvBillAirAllocOrder> orders, boolean byWeight)
{
BigDecimal total = price.setScale(2, RoundingMode.HALF_UP);
int count = orders.size();
List<BigDecimal> shares = new ArrayList<>(count);
if (!byWeight)
{
BigDecimal each = total.divide(BigDecimal.valueOf(count), 2, RoundingMode.DOWN);
BigDecimal used = ZERO;
for (int i = 0; i < count - 1; i++)
{
shares.add(each);
used = used.add(each);
}
shares.add(total.subtract(used));
return shares;
}
BigDecimal sum = totalWeight(orders);
int last = count - 1;
for (int i = count - 1; i >= 0; i--)
{
if (weight(orders.get(i)).signum() > 0)
{
last = i;
break;
}
}
BigDecimal used = ZERO;
for (int i = 0; i < count; i++)
{
if (i == last)
{
shares.add(null);
continue;
}
BigDecimal share = total.multiply(weight(orders.get(i))).divide(sum, 2, RoundingMode.DOWN);
shares.add(share);
used = used.add(share);
}
shares.set(last, total.subtract(used));
return shares;
}
private static BigDecimal totalWeight(List<SrvBillAirAllocOrder> orders)
{
BigDecimal sum = ZERO;
for (SrvBillAirAllocOrder order : orders)
{
sum = sum.add(weight(order));
}
return sum;
}
private static BigDecimal weight(SrvBillAirAllocOrder order)
{
return order.getChargeWeight() == null ? ZERO : order.getChargeWeight();
}
private static List<SrvBillAirAllocFee> dedupe(List<SrvBillAirAllocFee> fees)
{
Map<Long, SrvBillAirAllocFee> unique = new LinkedHashMap<>();
if (fees != null)
{
for (SrvBillAirAllocFee fee : fees)
{
if (fee != null && fee.getId() != null)
{
unique.putIfAbsent(fee.getId(), fee);
}
}
}
return new ArrayList<>(unique.values());
}
private static List<Long> feeIds(List<SrvBillAirAllocFee> fees)
{
List<Long> ids = new ArrayList<>();
for (SrvBillAirAllocFee fee : fees)
{
ids.add(fee.getId());
}
return ids;
}
private static String blankName(SrvBillAirAllocFee fee)
{
if (fee.getFeeName() != null && !fee.getFeeName().isBlank())
{
return fee.getFeeName().trim();
}
return "提单费用";
}
private static String remark(SrvBillAirAllocFee fee)
{
String dim = DIM_WEIGHT.equals(fee.getAllocDim()) ? "重量" : "订单";
return "提单" + fee.getBillCode() + "按" + dim + "分摊";
}
}
@@ -21,8 +21,11 @@ import com.bms.common.utils.SecurityUtils;
import com.bms.price.airbill.domain.SrvBillAirFee;
import com.bms.price.airbill.domain.SrvBillAirFeeLog;
import com.bms.price.airbill.domain.SrvBillAirFeeSave;
import com.bms.price.domain.PrcSurcharge;
import com.bms.price.mapper.PrcPayBillFeeMapper;
import com.bms.price.mapper.SrvBillAirFeeMapper;
import com.bms.price.mapper.SrvBillAirMapper;
import com.bms.price.service.IPrcSurchargeService;
import com.bms.price.service.ISrvBillAirFeeService;
import com.bms.system.service.ISysDictTypeService;
@@ -32,13 +35,29 @@ import com.bms.system.service.ISysDictTypeService;
@Service
public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
{
private static final String FEE_DICT = "bms_fee_type";
private static final String LEVEL_DICT = "bms_fee_level";
private static final String ALLOC_DICT = "bill_fee_alloc";
private static final String ALLOC_DIM_DICT = "bill_fee_alloc_dim";
private static final String STATUS_DICT = "bill_fee_status";
private static final String STATUS_ALLOCATED = "1";
private static final String STATUS_CONFIRMED = "3";
private static final String CURRENCY_DICT = "bms_currency";
@Autowired
private SrvBillAirFeeMapper feeMapper;
@Autowired
private PrcPayBillFeeMapper payBillFeeMapper;
@Autowired
private IPrcSurchargeService surchargeService;
@Autowired
private SrvBillAirMapper billMapper;
@@ -84,7 +103,10 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
{
throw new ServiceException("没有需要保存的变更");
}
Map<String, String> feeLabels = dictLabels(FEE_DICT, "费用类型");
Map<String, String> levelLabels = dictLabels(LEVEL_DICT, "费用阶段");
Map<String, String> allocLabels = dictLabels(ALLOC_DICT, "是否分摊");
Map<String, String> dimLabels = dictLabels(ALLOC_DIM_DICT, "分摊维度");
Map<String, String> statusLabels = dictLabels(STATUS_DICT, "费用状态");
Map<String, String> currencyLabels = dictLabels(CURRENCY_DICT, "币种");
Operator operator = operator();
Date now = DateUtils.getNowDate();
@@ -107,10 +129,14 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
{
throw new ServiceException("费用已删除或不属于该提单");
}
if (locked(current))
{
throw new ServiceException("已分摊或已确定的费用不能删除,请使用作废");
}
int rows = feeMapper.deleteFee(current.getId(), billCode, operator.account, now);
if (rows > 0)
{
writeLog(billCode, id, SrvBillAirFeeLog.DELETE, current, null, feeLabels, currencyLabels, operator, now);
writeLog(billCode, id, SrvBillAirFeeLog.DELETE, current, null, feeNames(current, null), levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels, operator, now);
removed++;
}
}
@@ -129,8 +155,14 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
{
throw new ServiceException("费用已删除或不属于该提单");
}
SrvBillAirFee next = normalize(incoming, feeLabels, currencyLabels);
List<SrvBillAirFeeLog.FieldChange> changes = diff(current, next, feeLabels, currencyLabels);
if (locked(current))
{
throw new ServiceException("已分摊或已确定的费用不能修改");
}
SrvBillAirFee next = normalize(incoming, levelLabels, allocLabels, dimLabels, currencyLabels);
next.setBillFeeStatus(current.getBillFeeStatus() == null || current.getBillFeeStatus().isBlank() ? "0" : current.getBillFeeStatus());
Map<String, String> feeNames = feeNames(current, next);
List<SrvBillAirFeeLog.FieldChange> changes = diff(current, next, feeNames, levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels);
if (changes.isEmpty())
{
continue;
@@ -141,17 +173,19 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
next.setUpdateTime(now);
if (feeMapper.updateFee(next) > 0)
{
writeLog(billCode, current.getId(), SrvBillAirFeeLog.UPDATE, current, next, feeLabels, currencyLabels, operator, now);
writeLog(billCode, current.getId(), SrvBillAirFeeLog.UPDATE, current, next, feeNames, levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels, operator, now);
updated++;
}
}
for (SrvBillAirFee incoming : inserts)
{
if (incoming == null || blank(incoming.getFeeType()) && incoming.getPrice() == null && blank(incoming.getCurrency()) && blank(incoming.getRemark()))
if (incoming == null || blank(incoming.getFeeType()) && blank(incoming.getFeeLevel()) && incoming.getPrice() == null
&& blank(incoming.getCurrency()) && blank(incoming.getRemark()))
{
continue;
}
SrvBillAirFee next = normalize(incoming, feeLabels, currencyLabels);
SrvBillAirFee next = normalize(incoming, levelLabels, allocLabels, dimLabels, currencyLabels);
next.setBillFeeStatus("0");
next.setId(null);
next.setBillCode(billCode);
next.setCreateBy(operator.account);
@@ -159,7 +193,7 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
next.setUpdateBy(operator.account);
next.setUpdateTime(now);
feeMapper.insertFee(next);
writeLog(billCode, next.getId(), SrvBillAirFeeLog.INSERT, null, next, feeLabels, currencyLabels, operator, now);
writeLog(billCode, next.getId(), SrvBillAirFeeLog.INSERT, null, next, feeNames(null, next), levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels, operator, now);
inserted++;
}
if (inserted + updated + removed == 0)
@@ -169,23 +203,132 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
return "已保存:新增 " + inserted + " 条,修改 " + updated + " 条,删除 " + removed + " 条";
}
@Override
@Transactional(rollbackFor = Exception.class)
public String confirm(String billCode, Long feeId)
{
String code = requireBill(billCode);
if (feeId == null)
{
throw new ServiceException("请选择要确定的费用");
}
SrvBillAirFee current = liveFee(feeId, code);
if (current == null)
{
throw new ServiceException("费用已删除或不属于该提单");
}
if (!STATUS_ALLOCATED.equals(current.getBillFeeStatus()))
{
throw new ServiceException("只有已分摊的费用可以确定");
}
Operator operator = operator();
Date now = DateUtils.getNowDate();
if (feeMapper.confirmFee(feeId, code, operator.account, now) != 1)
{
throw new ServiceException("费用状态已变化,请刷新后再确定");
}
writePlainLog(code, feeId, SrvBillAirFeeLog.CONFIRM, "确定费用", operator, now);
return "费用已确定";
}
@Override
@Transactional(rollbackFor = Exception.class)
public String voidFee(String billCode, Long feeId)
{
String code = requireBill(billCode);
if (feeId == null)
{
throw new ServiceException("请选择要作废的费用");
}
SrvBillAirFee current = liveFee(feeId, code);
if (current == null)
{
throw new ServiceException("费用已删除或不属于该提单");
}
if (!locked(current))
{
throw new ServiceException("只有已分摊或已确定的费用可以作废");
}
String billedOrderNo = payBillFeeMapper.selectBilledOrderNo(feeId);
if (billedOrderNo != null)
{
String orderNo = billedOrderNo.trim();
if (orderNo.isEmpty())
{
orderNo = "未知订单";
}
throw new ServiceException("该费用存在单笔或多笔订单已出账单-如:" + orderNo + ",不可作废");
}
Operator operator = operator();
Date now = DateUtils.getNowDate();
payBillFeeMapper.markLadingFeeDeleted(feeId);
if (feeMapper.voidFee(feeId, code, operator.account, now) != 1)
{
throw new ServiceException("费用状态已变化,请刷新后再作废");
}
Map<String, String> levelLabels = dictLabels(LEVEL_DICT, "费用阶段");
Map<String, String> allocLabels = dictLabels(ALLOC_DICT, "是否分摊");
Map<String, String> dimLabels = dictLabels(ALLOC_DIM_DICT, "分摊维度");
Map<String, String> statusLabels = dictLabels(STATUS_DICT, "费用状态");
Map<String, String> currencyLabels = dictLabels(CURRENCY_DICT, "币种");
writeLog(code, feeId, SrvBillAirFeeLog.VOID, current, null, feeNames(current, null),
levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels, operator, now);
return "费用已作废";
}
private SrvBillAirFee liveFee(Long id, String billCode)
{
return feeMapper.selectLive(id, billCode);
}
private SrvBillAirFee normalize(SrvBillAirFee raw, Map<String, String> feeLabels, Map<String, String> currencyLabels)
private static boolean locked(SrvBillAirFee fee)
{
String status = fee == null ? "" : text(fee.getBillFeeStatus());
return STATUS_ALLOCATED.equals(status) || STATUS_CONFIRMED.equals(status);
}
private SrvBillAirFee normalize(SrvBillAirFee raw, Map<String, String> levelLabels,
Map<String, String> allocLabels, Map<String, String> dimLabels, Map<String, String> currencyLabels)
{
String feeType = trim(raw.getFeeType());
String feeLevel = trim(raw.getFeeLevel());
String allocFlag = trim(raw.getAllocFlag());
String allocDim = trim(raw.getAllocDim());
String currency = trim(raw.getCurrency());
String remark = trim(raw.getRemark());
if (feeType.isEmpty())
Long scId = parseScId(feeType);
if (scId == null)
{
throw new ServiceException("请选择费用项");
}
if (feeType.length() > 32 || !feeLabels.containsKey(feeType))
PrcSurcharge surcharge = surchargeService.selectPrcSurchargeById(scId);
if (surcharge == null)
{
throw new ServiceException("费用项不在费用类型字典中");
throw new ServiceException("费用项不存在");
}
feeType = String.valueOf(scId);
if (allocFlag.isEmpty() || !allocLabels.containsKey(allocFlag))
{
throw new ServiceException("请选择是否分摊");
}
if (!feeLevel.isEmpty() && (feeLevel.length() > 32 || !levelLabels.containsKey(feeLevel)))
{
throw new ServiceException("费用阶段不在字典中");
}
if ("1".equals(allocFlag) && feeLevel.isEmpty())
{
throw new ServiceException("如需分摊费用至订单,请选择费用所属阶段");
}
if ("1".equals(allocFlag))
{
if (allocDim.isEmpty() || !dimLabels.containsKey(allocDim))
{
throw new ServiceException("如需分摊费用至订单,请选择分摊维度");
}
}
else
{
allocDim = "";
}
if (raw.getPrice() == null)
{
@@ -213,16 +356,36 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
}
SrvBillAirFee fee = new SrvBillAirFee();
fee.setFeeType(feeType);
fee.setFeeLevel(feeLevel);
fee.setAllocFlag(allocFlag);
fee.setAllocDim(allocDim);
fee.setPrice(raw.getPrice());
fee.setCurrency(currency);
fee.setRemark(remark);
return fee;
}
/**
* 费用日志组装
* @param billCode
* @param feeId
* @param operation
* @param before
* @param after
* @param feeLabels
* @param levelLabels
* @param allocLabels
* @param dimLabels
* @param statusLabels
* @param currencyLabels
* @param operator
* @param now
*/
private void writeLog(String billCode, Long feeId, String operation, SrvBillAirFee before, SrvBillAirFee after,
Map<String, String> feeLabels, Map<String, String> currencyLabels, Operator operator, Date now)
Map<String, String> feeLabels, Map<String, String> levelLabels, Map<String, String> allocLabels,
Map<String, String> dimLabels, Map<String, String> statusLabels, Map<String, String> currencyLabels, Operator operator, Date now)
{
List<SrvBillAirFeeLog.FieldChange> changes = diff(before, after, feeLabels, currencyLabels);
List<SrvBillAirFeeLog.FieldChange> changes = diff(before, after, feeLabels, levelLabels, allocLabels, dimLabels, statusLabels, currencyLabels);
SrvBillAirFeeLog log = new SrvBillAirFeeLog();
log.setBillCode(billCode);
log.setFeeId(feeId);
@@ -235,12 +398,36 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
feeMapper.insertLog(log);
}
/** 确定费用不比较字段,更改前和更改后都留空。 */
private void writePlainLog(String billCode, Long feeId, String operation, String summary, Operator operator, Date now)
{
SrvBillAirFeeLog log = new SrvBillAirFeeLog();
log.setBillCode(billCode);
log.setFeeId(feeId);
log.setOperationType(operation);
log.setSummary(summary);
log.setChangeContent("[]");
log.setCreateBy(operator.account);
log.setCreateByName(operator.name);
log.setCreateTime(now);
feeMapper.insertLog(log);
}
private static List<SrvBillAirFeeLog.FieldChange> diff(SrvBillAirFee before, SrvBillAirFee after,
Map<String, String> feeLabels, Map<String, String> currencyLabels)
Map<String, String> feeLabels, Map<String, String> levelLabels, Map<String, String> allocLabels,
Map<String, String> dimLabels, Map<String, String> statusLabels, Map<String, String> currencyLabels)
{
List<SrvBillAirFeeLog.FieldChange> changes = new ArrayList<>();
addChange(changes, "feeType", "费用类型", label(feeLabels, value(before, SrvBillAirFee::getFeeType)),
addChange(changes, "feeType", "费用项", label(feeLabels, value(before, SrvBillAirFee::getFeeType)),
label(feeLabels, value(after, SrvBillAirFee::getFeeType)));
addChange(changes, "feeLevel", "费用阶段", label(levelLabels, value(before, SrvBillAirFee::getFeeLevel)),
label(levelLabels, value(after, SrvBillAirFee::getFeeLevel)));
addChange(changes, "allocFlag", "是否分摊", label(allocLabels, value(before, SrvBillAirFee::getAllocFlag)),
label(allocLabels, value(after, SrvBillAirFee::getAllocFlag)));
addChange(changes, "allocDim", "分摊维度(票)", label(dimLabels, value(before, SrvBillAirFee::getAllocDim)),
label(dimLabels, value(after, SrvBillAirFee::getAllocDim)));
addChange(changes, "billFeeStatus", "费用状态", label(statusLabels, value(before, SrvBillAirFee::getBillFeeStatus)),
label(statusLabels, value(after, SrvBillAirFee::getBillFeeStatus)));
addChange(changes, "price", "价格", priceText(before), priceText(after));
addChange(changes, "currency", "收费币种", label(currencyLabels, value(before, SrvBillAirFee::getCurrency)),
label(currencyLabels, value(after, SrvBillAirFee::getCurrency)));
@@ -262,7 +449,9 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
private static String summary(String operation, List<SrvBillAirFeeLog.FieldChange> changes)
{
String action = SrvBillAirFeeLog.INSERT.equals(operation) ? "新增费用"
: SrvBillAirFeeLog.DELETE.equals(operation) ? "删除费用" : "修改费用";
: SrvBillAirFeeLog.DELETE.equals(operation) ? "删除费用"
: SrvBillAirFeeLog.CONFIRM.equals(operation) ? "确定费用"
: SrvBillAirFeeLog.VOID.equals(operation) ? "作废费用" : "修改费用";
StringBuilder text = new StringBuilder(action);
for (SrvBillAirFeeLog.FieldChange change : changes)
{
@@ -329,6 +518,60 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService
return fee.getPrice().stripTrailingZeros().toPlainString();
}
private Map<String, String> feeNames(SrvBillAirFee before, SrvBillAirFee after)
{
Map<String, String> names = new LinkedHashMap<>();
putFeeName(names, before);
putFeeName(names, after);
return names;
}
private void putFeeName(Map<String, String> names, SrvBillAirFee fee)
{
if (fee == null)
{
return;
}
String id = trim(fee.getFeeType());
if (id.isEmpty() || names.containsKey(id))
{
return;
}
names.put(id, surchargeName(id));
}
private String surchargeName(String feeType)
{
Long scId = parseScId(feeType);
if (scId == null)
{
return feeType;
}
PrcSurcharge surcharge = surchargeService.selectPrcSurchargeById(scId);
if (surcharge == null || surcharge.getScName() == null || surcharge.getScName().isBlank())
{
return feeType;
}
return surcharge.getScName().trim();
}
private static Long parseScId(String feeType)
{
if (feeType == null || feeType.isBlank() || !feeType.chars().allMatch(Character::isDigit))
{
return null;
}
try
{
long id = Long.parseLong(feeType);
return id > 0 ? id : null;
}
catch (NumberFormatException ex)
{
return null;
}
}
private static String label(Map<String, String> labels, String value)
{
if (value == null || value.isBlank())
@@ -28,7 +28,11 @@ import com.bms.customer.customerinfo.mapper.BmsCustomerMapper;
import com.bms.price.domain.BmsProduct;
import com.bms.price.domain.BmsProductCountry;
import com.bms.price.domain.BmsRedlineProductCountry;
import com.bms.price.domain.PayCostLine;
import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayProduct;
import com.bms.price.domain.PrcCustomerPriceSet;
import com.bms.price.domain.PrcOrderBillExt;
import com.bms.price.domain.PrcPriceSet;
import com.bms.price.domain.PrcPriceSetDetail;
import com.bms.price.domain.PrcPriceSetProduct;
@@ -37,6 +41,7 @@ import com.bms.price.domain.PrcQuote;
import com.bms.price.domain.PrcQuoteFee;
import com.bms.price.domain.PrcSurchargeRel;
import com.bms.price.domain.PrcZone;
import com.bms.price.pay.PayCostCalculator;
import com.bms.price.mapper.PrcZoneDetailMapper;
import com.bms.price.domain.vo.TmsPriceBillRequest;
import com.bms.price.domain.vo.TmsPriceQuoteFeeLine;
@@ -48,6 +53,7 @@ import com.bms.price.mapper.BmsProductCountryMapper;
import com.bms.price.mapper.BmsProductMapper;
import com.bms.price.mapper.BmsRedlineProductCountryMapper;
import com.bms.price.mapper.PrcCustomerPriceSetMapper;
import com.bms.price.mapper.PrcOrderBillExtMapper;
import com.bms.price.mapper.PrcPriceSetDetailMapper;
import com.bms.price.mapper.PrcPriceSetMapper;
import com.bms.price.mapper.PrcPriceSetProductMapper;
@@ -58,12 +64,14 @@ import com.bms.price.mapper.PrcSurchargeRelMapper;
import com.bms.price.search.EsBizLogSupport;
import com.bms.price.search.EsLogType;
import com.bms.price.search.IBillSearchStore;
import com.bms.price.service.IPayProductService;
import com.bms.price.service.ITmsPriceQuoteService;
import com.bms.system.service.IBmsProductCodeMappingService;
/**
* 共用的试算/计费计算:按 bizDate 取客户绑定和套餐版本(版本 effective_time)。
* 绑定的 pr_begindate/pr_enddate 不作为计费时间门槛。
* 先按 prc_price_set.set_category 分流:LABEL 走打单 pay_*;PACKAGE/EXCLUSIVE 走销售快照。
* 销售价只来自套餐快照(FIXED 明细 / 按目录底价 DISCOUNT)。
* 无绑定或无生效版本:试算和计费都直接失败(不用 PRODUCT_DEFAULT)。
* 账单同步时,产品/国家/重量段未命中为软失败(billing_fail_status 1/2/3,金额为 0)。
@@ -78,6 +86,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
private static final String TYPE_DISCOUNT = "DISCOUNT";
private static final String SRC_FIXED = "PACKAGE_FIXED";
private static final String SRC_DISCOUNT = "PACKAGE_DISCOUNT";
private static final String SRC_LABEL = "LABEL_PAY";
private static final String FEE_BASIC = "BASIC_FREIGHT";
private static final String FEE_REG = "REGISTRATION_FEE";
@@ -128,6 +137,12 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
@Autowired
private BmsCustomerMapper bmsCustomerMapper;
@Autowired
private IPayProductService payProductService;
@Autowired
private PrcOrderBillExtMapper orderBillExtMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public TmsPriceQuoteResult quote(TmsPriceQuoteRequest request)
@@ -169,7 +184,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return toResult(cached, fees, true);
}
TmsPriceQuoteResult refreshed = doQuote(request, bizDate);
applySurchargesAndFees(refreshed);
applySalesSurchargesIfNeeded(refreshed);
replaceQuoteFees(cached.getQuoteId(), refreshed);
refreshed.setQuoteId(cached.getQuoteId());
refreshed.setFromCache(false);
@@ -179,11 +194,21 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
}
TmsPriceQuoteResult result = doQuote(request, bizDate);
applySurchargesAndFees(result);
applySalesSurchargesIfNeeded(result);
persistQuote(quoteKey, request, weight, bizDate, result);
return result;
}
/** LABEL 费用已由 PayCostCalculator 算完,不再叠加销售附加费。 */
private void applySalesSurchargesIfNeeded(TmsPriceQuoteResult result)
{
if (result == null || SRC_LABEL.equals(result.getMatchSource()))
{
return;
}
applySurchargesAndFees(result);
}
/**
* Cached quotes from pre-package-snapshot logic (PRODUCT_DEFAULT / missing package id)
* must not be reused after billing rules changed.
@@ -211,7 +236,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
TmsPriceQuoteResult result = doQuote(request, bizDate);
if (!BillBillingFailStatus.isFail(result.getBillingFailStatus()))
{
applySurchargesAndFees(result);
applySalesSurchargesIfNeeded(result);
result.setBillingFailStatus(BillBillingFailStatus.SUCCESS.getCode());
}
result.setCustomerActiveStatus(customerActiveStatus);
@@ -388,7 +413,11 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
}
// Charge weight keeps 3 decimals; freight unit price keeps 2 (see buildFromRates).
BigDecimal weight = request.getWeight().setScale(3, RoundingMode.HALF_UP);
String destPostcode = emptyToNull(request.getDestPostcode());
String destPostcode = emptyToNull(normalizePostcode(request.getDestPostcode()));
if (destPostcode != null)
{
request.setDestPostcode(destPostcode);
}
String productName = null;
if (request instanceof TmsPriceBillRequest)
{
@@ -438,6 +467,13 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
continue;
}
anyEnabledSet = true;
// 打单套餐:独立 pay_* 链路,不走销售版本明细
if (PrcPriceSet.CATEGORY_LABEL.equals(
PrcPriceSetServiceImpl.normalizeSetCategory(set.getSetCategory())))
{
return doLabelQuote(request, bind, set, productCode, productName, countryCode, countryName,
weight, bizDate);
}
// Temporal gate: prc_price_set_version.effective_time / expire_time (not bind pr_begindate)
PrcPriceSetVersion version = versionMapper.selectActiveByPriceSetAt(set.getPriceSetId(), asOf);
if (version == null || version.getPsvId() == null)
@@ -618,6 +654,171 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
throw new ServiceException(MessageUtils.message(missKey));
}
/**
* 打单套餐计费:渠道 AR → product_id,套餐+时间 → term,PayCostCalculator 算费。
*/
private TmsPriceQuoteResult doLabelQuote(TmsPriceQuoteRequest request, PrcCustomerPriceSet bind,
PrcPriceSet set, String productCode, String productName, String countryCode, String countryName,
BigDecimal weight, Date bizDate)
{
String channelId = resolveLabelChannelId(request);
if (StringUtils.isEmpty(channelId))
{
if (request instanceof TmsPriceBillRequest)
{
return buildBillingMissResult(request, productCode, productName, countryCode, countryName,
weight, bizDate, BillBillingFailStatus.PRICE_NOT_HIT.getCode());
}
throw new ServiceException("打单计费需要渠道");
}
PayProduct product;
try
{
product = payProductService.selectLabelPriceForDate(set.getPriceSetId(), channelId, bizDate);
}
catch (ServiceException ex)
{
if (request instanceof TmsPriceBillRequest)
{
return buildBillingMissResult(request, productCode, productName, countryCode, countryName,
weight, bizDate, BillBillingFailStatus.NO_ACTIVE_PACKAGE_VERSION.getCode());
}
throw ex;
}
BigDecimal length = null;
BigDecimal width = null;
BigDecimal height = null;
Integer orderStatus = null;
if (request instanceof TmsPriceBillRequest)
{
TmsPriceBillRequest billReq = (TmsPriceBillRequest) request;
length = billReq.getPkgLength();
width = billReq.getPkgWidth();
height = billReq.getPkgHeight();
orderStatus = billReq.getOrderStatus();
}
PayOrderCostResult cost = PayCostCalculator.calculate(product, weight, length, width, height,
request.getDestPostcode(), bizDate, orderStatus);
if (cost == null || cost.getFees() == null || cost.getFees().isEmpty())
{
if (request instanceof TmsPriceBillRequest)
{
return buildBillingMissResult(request, productCode, productName, countryCode, countryName,
weight, bizDate, BillBillingFailStatus.PRICE_NOT_HIT.getCode());
}
throw new ServiceException(cost != null && StringUtils.isNotEmpty(cost.getMessage())
? cost.getMessage() : "打单价卡未算出费用");
}
TmsPriceQuoteResult r = mapLabelCostToQuote(cost, product, request, bind, set,
productCode, productName, countryCode, countryName, weight, bizDate);
stampRequestMeta(request, r);
return r;
}
/** 试算用 request.channelId;计费优先订单扩展 productChannelId。 */
private String resolveLabelChannelId(TmsPriceQuoteRequest request)
{
if (request != null && StringUtils.isNotEmpty(request.getChannelId()))
{
return request.getChannelId().trim();
}
if (!(request instanceof TmsPriceBillRequest))
{
return null;
}
TmsPriceBillRequest billReq = (TmsPriceBillRequest) request;
PrcOrderBillExt ext = null;
if (StringUtils.isNotEmpty(billReq.getOrderNo()))
{
ext = orderBillExtMapper.selectByOrderNo(billReq.getOrderNo().trim());
}
if (ext == null)
{
return null;
}
if (StringUtils.isNotEmpty(ext.getProductChannelId()))
{
return ext.getProductChannelId().trim();
}
if (StringUtils.isNotEmpty(ext.getProductFloorCode()))
{
return ext.getProductFloorCode().trim();
}
return null;
}
private TmsPriceQuoteResult mapLabelCostToQuote(PayOrderCostResult cost, PayProduct product,
TmsPriceQuoteRequest request, PrcCustomerPriceSet bind, PrcPriceSet set,
String productCode, String productName, String countryCode, String countryName,
BigDecimal weight, Date bizDate)
{
RoundingMode rm = RoundingMode.HALF_UP;
String currency = normalizeCurrency(cost.getCurrency());
List<TmsPriceQuoteFeeLine> lines = new ArrayList<TmsPriceQuoteFeeLine>();
BigDecimal freightAmount = BigDecimal.ZERO;
BigDecimal surchargeAmount = BigDecimal.ZERO;
BigDecimal registrationFee = BigDecimal.ZERO;
for (PayCostLine fee : cost.getFees())
{
if (fee == null || fee.getAmount() == null)
{
continue;
}
String feeType = StringUtils.isEmpty(fee.getFeeType()) ? FEE_SUR : fee.getFeeType().trim();
String feeName = StringUtils.isEmpty(fee.getFeeName()) ? feeNameOf(feeType) : fee.getFeeName();
BigDecimal amount = fee.getAmount().setScale(2, rm);
Long scId = fee.getScId() == null ? 0L : fee.getScId();
lines.add(feeLine(feeType, feeName, scId, amount, currency, "HALF_UP", fee.getRemark()));
if (FEE_BASIC.equals(feeType))
{
freightAmount = freightAmount.add(amount);
}
else if (FEE_REG.equals(feeType))
{
registrationFee = registrationFee.add(amount);
}
else
{
surchargeAmount = surchargeAmount.add(amount);
}
}
BigDecimal incomeTotal = nvl(cost.getPayTotal());
if (incomeTotal.compareTo(BigDecimal.ZERO) <= 0)
{
incomeTotal = freightAmount.add(registrationFee).add(surchargeAmount).setScale(2, rm);
}
String labelProductName = StringUtils.isNotEmpty(product.getProductName())
? product.getProductName() : productName;
TmsPriceQuoteResult r = new TmsPriceQuoteResult();
r.setMatchSource(SRC_LABEL);
r.setMatchMessage("hit label package pay card V"
+ (product.getVersionNo() == null ? "?" : product.getVersionNo()));
fillPackage(r, bind, set);
r.setVersionNo(product.getVersionNo() == null ? null : ("V" + product.getVersionNo()));
r.setCustomerId(bind.getCustomerId());
r.setProductCode(productCode);
r.setProductName(labelProductName);
r.setCountryCode(countryCode);
r.setCountryName(countryName);
r.setWeight(weight);
r.setChargeWeight(weight);
r.setBizDate(bizDate);
r.setEffectiveDate(product.getTermStart() != null ? product.getTermStart() : product.getEffectiveDate());
r.setFreightRate(weight != null && weight.compareTo(BigDecimal.ZERO) > 0
? freightAmount.divide(weight, 2, rm) : freightAmount);
r.setFreightAmount(freightAmount.setScale(2, rm));
r.setRegistrationFee(registrationFee.setScale(2, rm));
r.setSurchargeAmount(surchargeAmount.setScale(2, rm));
r.setPayableTotal(incomeTotal);
r.setIncomeTotal(incomeTotal);
r.setCurrency(currency);
r.setRoundMode("HALF_UP");
r.setFromCache(false);
r.setFeeDetails(lines);
r.setPayFeeDetails(Collections.<TmsPriceQuoteFeeLine>emptyList());
return r;
}
/**
* Diagnose FIXED miss: product rows absent -> 1; country/zone absent -> 2; else weight -> 3.
*/
@@ -992,16 +1193,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
private static String normalizePostcode(String postcode)
{
if (StringUtils.isEmpty(postcode))
{
return postcode;
}
String n = postcode.trim().replace(" ", "");
if (n.endsWith(".0") && n.matches("\\d+\\.0"))
{
return n.substring(0, n.length() - 2);
}
return n;
return StringUtils.normalizePostcode(postcode);
}
private TmsPriceQuoteResult tryFixed(PrcCustomerPriceSet bind, PrcPriceSet set, PrcPriceSetVersion version,
@@ -265,6 +265,7 @@ public final class OrderBillExportSupport
case 20: return "客户已停用";
case 21: return "运费为空";
case 22: return "未知失败";
case 26: return "未计费";
default: return String.valueOf(status);
}
}
@@ -16,13 +16,13 @@ import com.bms.price.mapper.PrcBillingTaskMapper;
import com.bms.price.service.IPrcBillingTaskService;
/**
* 夜间窗口按 prc_billing_task 自动重计费。
* Auto retry prc_billing_task on a schedule.
*
* <p>在 [startHour, endHour) 内(默认 00:00-09:00):最多拉取 {@value #DEFAULT_BATCH}
* 条任务 id(不限 success_status)-> 全部计费 -> 立刻拉下一页。
* 空页则跳过计费并结束本轮(下次 cron 再处理新数据)。</p>
* <p>Within [startHour, endHour) (default all day 00:00-24:00): pull up to {@value #DEFAULT_BATCH}
* task ids (any success_status) -> bill all -> pull next page.
* Empty page skips billing and ends this tick (next cron handles new rows).</p>
*
* <p>与监控手工重试 / 条件重试同一条重计费路径(先重置为 WAITING 再处理)。</p>
* <p>Same path as monitor manual / filter retry (reset to WAITING then process).</p>
*/
@Component
public class PrcBillingTaskNightRetryTask
@@ -52,10 +52,10 @@ public class PrcBillingTaskNightRetryTask
private IPrcBillingTaskService billingTaskService;
/**
* Fire every minute; if a previous run is still paging batches, skip.
* Fire every hour by default; if a previous run is still paging batches, skip.
* Hour gate uses bms.billing.night-retry start/end.
*/
@Scheduled(cron = "${bms.billing.night-retry.cron:0 0/1 0-8 * * ?}")
@Scheduled(cron = "${bms.billing.night-retry.cron:0 0 * * * ?}")
public void scheduledTick()
{
BillingProperties.NightRetry cfg = billingProperties == null ? null : billingProperties.getNightRetry();
@@ -1,4 +1,4 @@
package com.bms.ar.config;
package com.bms.receivable.config;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.math.BigDecimal;
import java.util.Date;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.util.Date;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.math.BigDecimal;
import java.util.Date;
@@ -36,6 +36,11 @@ public class ArBill extends BaseEntity {
private Long customerId;
private String customerCode;
private String customerName;
/** 创建账单时的客户区域和负责人快照。 */
private String profitCustomerArea;
private Long profitSalesUserId;
private String profitSalesUserCode;
private String profitSalesUserName;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
/** 账单所属期开始日期,导出模板展示用。 */
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.util.Date;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.util.Date;
@@ -1,4 +1,4 @@
package com.bms.ar.domain;
package com.bms.receivable.domain;
import java.io.Serializable;
import java.util.Date;
@@ -1,4 +1,4 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import lombok.Data;
@@ -1,4 +1,4 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.io.Serializable;
import java.math.BigDecimal;
@@ -37,10 +37,10 @@ public class ArBillGeneratePreviewExportRow implements Serializable {
@Excel(name = "国家/地区", sort = 6, width = 18)
private String countryName;
@Excel(name = "实际重(kg)", sort = 7, scale = 2, width = 16)
@Excel(name = "实际重(kg)", sort = 7, width = 16)
private BigDecimal actualWeight;
@Excel(name = "计费重(kg)", sort = 8, scale = 2, width = 16)
@Excel(name = "计费重(kg)", sort = 8, width = 16)
private BigDecimal chargeWeight;
@Excel(name = "应收金额", sort = 9, scale = 2, width = 16)
@@ -1,4 +1,4 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
@@ -1,4 +1,4 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.util.Date;
import java.util.List;
@@ -8,7 +8,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import com.bms.common.config.serializer.StrictDateDeserializer;
import com.bms.ar.enums.ArBillSelectionMode;
import com.bms.receivable.enums.ArBillSelectionMode;
import lombok.Data;
/** 从订单计费结果生成正式账单的参数。 */
@@ -1,11 +1,11 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import com.bms.ar.domain.ArBill;
import com.bms.ar.enums.ArBillStatus;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.enums.ArBillStatus;
import com.bms.common.annotation.Excel;
import lombok.Data;
@@ -1,9 +1,9 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.util.Date;
import java.util.List;
import org.springframework.format.annotation.DateTimeFormat;
import com.bms.ar.domain.ArBill;
import com.bms.receivable.domain.ArBill;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -1,4 +1,4 @@
package com.bms.ar.domain.vo;
package com.bms.receivable.domain.vo;
import java.io.Serializable;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.bms.ar.enums;
package com.bms.receivable.enums;
/**
* 应收账单余额核销单状态。
@@ -1,4 +1,4 @@
package com.bms.ar.enums;
package com.bms.receivable.enums;
/** 应收账单生成时用于截止日筛选的来源订单日期字段。 */
public enum ArBillDateType
@@ -1,4 +1,4 @@
package com.bms.ar.enums;
package com.bms.receivable.enums;
/** 应收账单异步生成任务状态。 */
public final class ArBillGenerateTaskStatus
@@ -1,4 +1,4 @@
package com.bms.ar.enums;
package com.bms.receivable.enums;
/** 应收账单生成状态,与账单业务状态分离。 */
public final class ArBillGenerationStatus
@@ -1,4 +1,4 @@
package com.bms.ar.enums;
package com.bms.receivable.enums;
/**
* 应收账单生成时的订单选择模式。

Some files were not shown because too many files have changed in this diff Show More