10 Commits

Author SHA1 Message Date
liuminghui b8b943ef51 偏远地区邮编判断调整 2026-11-09 15:58:27 +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
71 changed files with 3669 additions and 143 deletions
@@ -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)
@@ -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.ar.profit.ArCommissionRate;
import com.bms.ar.profit.ArCommissionService;
import com.bms.ar.profit.ArProfitQuery;
import com.bms.ar.profit.ArProfitService;
import com.bms.ar.profit.ArWriteoffRate;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import jakarta.servlet.http.HttpServletResponse;
import com.bms.ar.profit.ArProfitRow;
import com.bms.ar.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:commission')")
@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:commission')")
@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.results(billId, false), "应收账单提成明细");
}
@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), "应收账单毛利分析");
}
}
@@ -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();
@@ -204,7 +204,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 +213,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 +288,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 +326,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
{
@@ -418,7 +441,7 @@ class PayWorkbookParserTest
@Test
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 +454,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 +474,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 +743,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,83 @@
package com.bms.report;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
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.ar.domain.ArBalanceWriteoff;
import com.bms.ar.domain.ArBill;
import com.bms.ar.mapper.ArCommissionMapper;
import com.bms.ar.profit.ArCommissionRate;
import com.bms.ar.profit.ArCommissionResult;
import com.bms.ar.profit.ArCommissionService;
class ArCommissionServiceTest
{
@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,68 @@
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.ar.profit.ArProfitQuery;
import com.bms.ar.profit.ArProfitScope;
import com.bms.ar.profit.ArCommissionResult;
class ArProfitMapperSqlTest
{
@Test
void parsesReportAndCommissionMappersAndScopesEachReportQuery() throws Exception
{
Configuration configuration = new Configuration();
for (String resource : new String[] { "mapper/ar/ArProfitMapper.xml", "mapper/ar/ArCommissionMapper.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"));
}
ArProfitQuery orderFilter = new ArProfitQuery();
orderFilter.setOrderNo("ORDER-1");
String bills = configuration.getMappedStatement("com.bms.ar.mapper.ArProfitMapper.selectBills")
.getBoundSql(Map.of("query", orderFilter, "scope", new ArProfitScope(true, false, false, 8L, 10L))).getSql();
assertTrue(bills.contains("from ar_bill b"));
assertTrue(bills.contains("exists (select 1 from ar_bill_detail matched"));
assertFalse(bills.contains("and d.order_no like"));
String billCommission = configuration.getMappedStatement("com.bms.ar.mapper.ArCommissionMapper.selectCommissionSummary")
.getBoundSql(Map.of("billId", 9L)).getSql();
assertTrue(billCommission.contains("r.ar_bill_id = ?"));
assertTrue(billCommission.contains("then null"));
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,52 @@
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.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.bms.ar.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.ar.profit.CommissionCalculator;
import com.bms.ar.profit.ArCommissionResult;
import com.bms.ar.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;
}
/**
* 替换指定字符串的指定区间内字符为"*"
*
@@ -36,6 +36,13 @@ 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;
/** NEW=生成时固化;BACKFILLED=历史补录,来源为补录时可取得的数据。 */
private String profitSnapshotSource;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
/** 账单所属期开始日期,导出模板展示用。 */
@@ -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)
@@ -0,0 +1,30 @@
package com.bms.ar.mapper;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.ar.profit.ArCommissionRate;
import com.bms.ar.profit.ArWriteoffRate;
import com.bms.ar.profit.ArCommissionResult;
import com.bms.ar.profit.ArCommissionSummary;
public interface ArCommissionMapper
{
List<ArCommissionRate> selectRates();
ArCommissionRate selectEffective(@Param("salesUserId") Long salesUserId, @Param("at") Date at);
int insertRate(ArCommissionRate rate);
Long lockSalesUser(@Param("salesUserId") Long salesUserId);
int insertWriteoffRate(@Param("writeoffId") Long writeoffId, @Param("salesUserId") Long salesUserId,
@Param("rateId") Long rateId, @Param("rate") java.math.BigDecimal rate);
int reverseResults(@Param("billId") Long billId, @Param("operator") String operator);
List<ArCommissionResult> selectSettlementInputs(@Param("billId") Long billId);
int insertResults(@Param("items") List<ArCommissionResult> items, @Param("operator") String operator);
List<ArWriteoffRate> selectMissingRates();
List<ArWriteoffRate> selectWriteoffRates(@Param("billId") Long billId);
Long selectBillIdByWriteoffId(@Param("writeoffId") Long writeoffId);
int countMissingRates(@Param("billId") Long billId);
int confirmMissingRate(@Param("writeoffId") Long writeoffId, @Param("rate") java.math.BigDecimal rate,
@Param("operator") String operator, @Param("remark") String remark);
List<ArCommissionResult> selectResults(@Param("billId") Long billId, @Param("includeReversed") boolean includeReversed);
List<ArCommissionSummary> selectCommissionSummary(@Param("billId") Long billId);
}
@@ -0,0 +1,20 @@
package com.bms.ar.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.ar.profit.ArProfitQuery;
import com.bms.ar.profit.ArProfitRow;
import com.bms.ar.profit.ArProfitScope;
import com.bms.ar.profit.ArProfitSummary;
import com.bms.ar.profit.ArProfitSalesOption;
import com.bms.ar.domain.ArBillDetailFee;
import com.bms.ar.domain.ArBillDetail;
public interface ArProfitMapper
{
List<ArProfitRow> selectBills(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
List<ArProfitSummary> selectSummary(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
List<ArProfitSalesOption> selectSalesOptions(@Param("keyword") String keyword);
List<ArBillDetail> selectBillDetails(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
List<ArBillDetailFee> selectFees(@Param("query") ArProfitQuery query, @Param("scope") ArProfitScope scope);
}
@@ -0,0 +1,22 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
@Data
public class ArCommissionRate
{
private Long rateId;
private Long salesUserId;
private String salesUserCode;
private String salesUserName;
private BigDecimal rate;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date effectiveAt;
private String createBy;
private String remark;
}
@@ -0,0 +1,27 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
import com.bms.common.annotation.Excel;
@Data
public class ArCommissionResult
{
private Long resultId;
private Long arBillId;
private Long detailId;
private Long salesUserId;
@Excel(name = "账单号", width = 20) private String billNo;
@Excel(name = "订单号", width = 22) private String orderNo;
@Excel(name = "销售员", width = 16) private String salesUserName;
@Excel(name = "币种", width = 10) private String currency;
@Excel(name = "销售毛利", scale = 4, width = 16) private BigDecimal grossProfit;
@Excel(name = "正式提成", scale = 2, width = 16) private BigDecimal commissionAmount;
@Excel(name = "状态", readConverterExp = "READY=已计算,MISSING_RATE=比例待确认,MISSING_PRICE=价格缺失,MISSING_SNAPSHOT=归属或区域缺失,WRITEOFF_MISMATCH=核销金额不一致,REVERSED=已冲回", width = 20) private String resultStatus;
private Date createTime;
private String reversedBy;
private Date reversedTime;
private BigDecimal weightedRate;
private BigDecimal billAmount;
}
@@ -0,0 +1,148 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bms.ar.domain.ArBalanceWriteoff;
import com.bms.ar.domain.ArBill;
import com.bms.ar.mapper.ArCommissionMapper;
import com.bms.ar.mapper.ArBillMapper;
import com.bms.ar.enums.ArBillStatus;
import com.bms.ar.enums.ArBillGenerationStatus;
import com.bms.ar.security.ArBillRoleKeys;
import com.bms.common.exception.ServiceException;
import com.bms.common.core.domain.entity.SysUser;
import com.bms.common.utils.SecurityUtils;
import com.bms.system.mapper.SysUserMapper;
@Service
public class ArCommissionService
{
private final ArCommissionMapper mapper;
private final ArProfitScopeResolver scopeResolver;
private final SysUserMapper userMapper;
private final ArBillMapper billMapper;
public ArCommissionService(ArCommissionMapper mapper, ArProfitScopeResolver scopeResolver, SysUserMapper userMapper,
ArBillMapper billMapper)
{
this.mapper = mapper;
this.scopeResolver = scopeResolver;
this.userMapper = userMapper;
this.billMapper = billMapper;
}
public List<ArCommissionRate> selectRates()
{
requireFinance();
return mapper.selectRates();
}
@Transactional(rollbackFor = Exception.class)
public void addRate(ArCommissionRate rate)
{
requireFinance();
SysUser sales = rate == null || rate.getSalesUserId() == null ? null : userMapper.selectUserById(rate.getSalesUserId());
if (sales == null || !"0".equals(sales.getStatus()) || !"0".equals(sales.getDelFlag())
|| sales.getRoles() == null || sales.getRoles().stream().noneMatch(role -> role != null
&& "0".equals(role.getStatus()) && ArBillRoleKeys.SALES.equals(role.getRoleKey())))
throw new ServiceException("请选择有效销售员");
if (rate.getRate() == null || rate.getRate().signum() < 0 || rate.getRate().compareTo(new BigDecimal("100")) > 0
|| rate.getRate().scale() > 4)
throw new ServiceException("提成比例须为 0 至 100,最多四位小数");
if (rate.getRemark() != null && rate.getRemark().length() > 500)
throw new ServiceException("备注不能超过 500 字");
mapper.lockSalesUser(rate.getSalesUserId());
Date now = new Date();
if (rate.getEffectiveAt() == null) rate.setEffectiveAt(now);
if (rate.getEffectiveAt().before(now)) throw new ServiceException("提成比例生效时间不能早于当前时间");
rate.setCreateBy(SecurityUtils.getUsername());
mapper.insertRate(rate);
}
/** 在核销事务内固化该次操作时的比例;未配置时保留空值,待财务处理。 */
public void snapshotWriteoff(ArBill bill, ArBalanceWriteoff writeoff)
{
Long salesUserId = bill.getProfitSalesUserId();
if (salesUserId != null) mapper.lockSalesUser(salesUserId);
ArCommissionRate rate = salesUserId == null ? null : mapper.selectEffective(salesUserId, new Date());
mapper.insertWriteoffRate(writeoff.getWriteoffId(), salesUserId,
rate == null ? null : rate.getRateId(), rate == null ? null : rate.getRate());
}
/** 完全核销后生成逐单结果;由外部账单锁及核销事务保证并发一致。 */
public void createFinalResults(Long billId, String operator)
{
List<ArCommissionResult> items = mapper.selectSettlementInputs(billId);
CommissionCalculator.allocateFinalAmounts(items);
for (int offset = 0; offset < items.size(); offset += 300)
{
mapper.insertResults(items.subList(offset, Math.min(offset + 300, items.size())), operator);
}
}
/** 反核销保留原记录并标记冲回。 */
public void reverseFinalResults(Long billId, String operator)
{
mapper.reverseResults(billId, operator);
}
public List<ArWriteoffRate> missingRates()
{
requireFinance();
return mapper.selectMissingRates();
}
public List<ArCommissionResult> results(Long billId, boolean includeReversed)
{
requireFinance();
return mapper.selectResults(billId, includeReversed);
}
public List<ArCommissionSummary> summary(Long billId)
{
requireFinance();
return mapper.selectCommissionSummary(billId);
}
public List<ArWriteoffRate> writeoffRates(Long billId)
{
requireFinance();
return mapper.selectWriteoffRates(billId);
}
@Transactional(rollbackFor = Exception.class)
public void confirmMissingRate(ArWriteoffRate input)
{
requireFinance();
if (input == null || input.getWriteoffId() == null || input.getRate() == null
|| input.getRate().signum() < 0 || input.getRate().compareTo(new BigDecimal("100")) > 0
|| input.getRate().scale() > 4 || input.getRemark() == null || input.getRemark().isBlank()
|| input.getRemark().length() > 500)
throw new ServiceException("请填写 0 至 100 的提成比例及核对说明");
Long billId = mapper.selectBillIdByWriteoffId(input.getWriteoffId());
ArBill bill = billId == null ? null : billMapper.selectArBillByIdForUpdate(billId);
if (bill == null || bill.getProfitSalesUserId() == null)
throw new ServiceException("核销记录无效或账单销售员快照缺失");
if (!ArBillGenerationStatus.READY.equals(bill.getGenerationStatus())
|| !(ArBillStatus.CONFIRMED.getCode().equals(bill.getStatus())
|| ArBillStatus.PARTIAL_WRITTEN_OFF.getCode().equals(bill.getStatus())
|| ArBillStatus.WRITTEN_OFF.getCode().equals(bill.getStatus())))
throw new ServiceException("账单未生成完成或状态不允许确认提成比例");
String operator = SecurityUtils.getUsername();
if (mapper.confirmMissingRate(input.getWriteoffId(), input.getRate(), operator, input.getRemark().trim()) != 1)
throw new ServiceException("比例已确认或核销状态已变化,请刷新");
if (ArBillStatus.WRITTEN_OFF.getCode().equals(bill.getStatus()) && mapper.countMissingRates(billId) == 0)
{
mapper.reverseResults(billId, operator);
createFinalResults(billId, operator);
}
}
private void requireFinance()
{
if (!scopeResolver.resolve().all()) throw new ServiceException("仅财务和系统管理员可查看或维护提成");
}
}
@@ -0,0 +1,15 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class ArCommissionSummary
{
private Long salesUserId;
private String salesUserName;
private String currency;
private Long orderCount;
private Long pendingCount;
private BigDecimal commissionAmount;
}
@@ -0,0 +1,21 @@
package com.bms.ar.profit;
import java.util.Date;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
@Data
public class ArProfitQuery
{
private Long customerId;
private String billNo;
private String orderNo;
private String status;
private Long salesUserId;
private Long arBillId;
private Long detailId;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date beginBillDate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date endBillDate;
}
@@ -0,0 +1,30 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.bms.common.annotation.Excel;
@Data
public class ArProfitRow
{
private Long arBillId;
@Excel(name = "账单号", width = 20) private String billNo;
@Excel(name = "客户代码", width = 16) private String customerCode;
@Excel(name = "客户名称", width = 24) private String customerName;
private String customerArea;
@Excel(name = "归属来源", readConverterExp = "NEW=生成时快照,BACKFILLED=历史补录", width = 14) private String snapshotSource;
@Excel(name = "销售员", width = 16) private String salesUserName;
@Excel(name = "币种", width = 10) private String currency;
@Excel(name = "账单状态", readConverterExp = "CONFIRMED=已确认,PARTIAL_WRITTEN_OFF=部分核销,WRITTEN_OFF=已核销", width = 14) private String status;
@Excel(name = "账单日期", dateFormat = "yyyy-MM-dd", width = 15)
@JsonFormat(pattern = "yyyy-MM-dd")
private Date billDate;
@Excel(name = "销售价", scale = 4, width = 16) private BigDecimal salesAmount;
@Excel(name = "产品价", scale = 4, width = 16) private BigDecimal productAmount;
@Excel(name = "销售毛利", scale = 4, width = 16) private BigDecimal salesGrossProfit;
@Excel(name = "销售毛利率(%)", scale = 4, width = 18) private BigDecimal salesGrossMarginRate;
@Excel(name = "账单已核销", scale = 2, width = 16) private BigDecimal writtenOffAmount;
@Excel(name = "账单未核销", scale = 2, width = 16) private BigDecimal unwrittenAmount;
}
@@ -0,0 +1,11 @@
package com.bms.ar.profit;
import lombok.Data;
@Data
public class ArProfitSalesOption
{
private Long userId;
private String name;
private String code;
}
@@ -0,0 +1,11 @@
package com.bms.ar.profit;
/** 后端构造的数据范围,不接收前端传入的权限参数。 */
public record ArProfitScope(boolean all, boolean self, boolean department, Long userId, Long deptId)
{
public boolean isAll() { return all; }
public boolean isSelf() { return self; }
public boolean isDepartment() { return department; }
public Long getUserId() { return userId; }
public Long getDeptId() { return deptId; }
}
@@ -0,0 +1,58 @@
package com.bms.ar.profit;
import java.util.Arrays;
import java.util.Set;
import org.springframework.stereotype.Component;
import com.bms.ar.security.ArBillRoleKeys;
import com.bms.common.constant.Constants;
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;
import com.bms.common.utils.PermissionContext;
import com.bms.common.utils.SecurityUtils;
@Component
public class ArProfitScopeResolver
{
public ArProfitScope resolve()
{
return resolve(SecurityUtils.getLoginUser(), PermissionContext.get());
}
public ArProfitScope resolve(LoginUser actor, String permission)
{
if (actor == null || actor.getUser() == null || actor.getUserId() == null)
{
throw new ServiceException("登录状态无效,请重新登录", 401);
}
SysUser user = actor.getUser();
if (!"0".equals(user.getStatus()) || !"0".equals(user.getDelFlag()))
{
return new ArProfitScope(false, false, false, actor.getUserId(), actor.getDeptId());
}
if (user.isAdmin()) return new ArProfitScope(true, false, false, actor.getUserId(), actor.getDeptId());
boolean all = false, self = false, department = false;
if (permission != null && !permission.isBlank() && user.getRoles() != null)
{
for (SysRole role : user.getRoles())
{
if (role == null || !"0".equals(role.getStatus()) || !permits(role.getPermissions(), permission)) continue;
String key = role.getRoleKey();
all |= ArBillRoleKeys.ALL_DATA_ROLES.contains(key == null ? "" : key);
self |= ArBillRoleKeys.SALES.equals(key);
department |= ArBillRoleKeys.SALES_MANAGER.equals(key);
}
}
if (!all && !self && !department) throw new ServiceException("无权访问应收账单毛利分析");
return new ArProfitScope(all, self && actor.getUserId() > 0,
department && actor.getDeptId() != null && actor.getDeptId() > 0,
actor.getUserId(), actor.getDeptId());
}
private boolean permits(Set<String> permissions, String required)
{
return permissions != null && (permissions.contains(Constants.ALL_PERMISSION)
|| Arrays.stream(required.split(Constants.PERMISSION_DELIMITER)).map(String::trim).anyMatch(permissions::contains));
}
}
@@ -0,0 +1,59 @@
package com.bms.ar.profit;
import java.util.List;
import org.springframework.stereotype.Service;
import com.bms.ar.mapper.ArProfitMapper;
import com.bms.ar.domain.ArBillDetailFee;
import com.bms.ar.domain.ArBillDetail;
@Service
public class ArProfitService
{
private final ArProfitMapper mapper;
private final ArProfitScopeResolver scopeResolver;
public ArProfitService(ArProfitMapper mapper, ArProfitScopeResolver scopeResolver)
{
this.mapper = mapper;
this.scopeResolver = scopeResolver;
}
public List<ArProfitRow> selectBills(ArProfitQuery query)
{
return mapper.selectBills(query == null ? new ArProfitQuery() : query, scopeResolver.resolve());
}
public List<ArProfitSummary> selectSummary(ArProfitQuery query)
{
return mapper.selectSummary(query == null ? new ArProfitQuery() : query, scopeResolver.resolve());
}
public List<ArProfitSalesOption> selectSalesOptions(String keyword)
{
ArProfitScope scope = scopeResolver.resolve();
if (!scope.all() && !scope.self() && !scope.department())
{
return List.of();
}
if (keyword != null)
{
keyword = keyword.trim();
if (keyword.length() > 100) keyword = keyword.substring(0, 100);
}
return mapper.selectSalesOptions(keyword);
}
public List<ArBillDetailFee> selectFees(Long detailId)
{
ArProfitQuery query = new ArProfitQuery();
query.setDetailId(detailId);
return mapper.selectFees(query, scopeResolver.resolve());
}
public List<ArBillDetail> selectBillDetails(Long billId)
{
ArProfitQuery query = new ArProfitQuery();
query.setArBillId(billId);
return mapper.selectBillDetails(query, scopeResolver.resolve());
}
}
@@ -0,0 +1,18 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class ArProfitSummary
{
private String currency;
private Long billCount;
private Long invalidBillCount;
private BigDecimal salesAmount;
private BigDecimal productAmount;
private BigDecimal salesGrossProfit;
private BigDecimal salesGrossMarginRate;
private BigDecimal writtenOffAmount;
private BigDecimal unwrittenAmount;
}
@@ -0,0 +1,23 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
@Data
public class ArWriteoffRate
{
private Long writeoffId;
private Long arBillId;
private String billNo;
private String customerName;
private Long salesUserId;
private String salesUserName;
private BigDecimal writeoffAmount;
private Date writeoffDate;
private BigDecimal rate;
private String remark;
private String status;
private String confirmedBy;
private Date confirmedTime;
}
@@ -0,0 +1,88 @@
package com.bms.ar.profit;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
/** 根据账单有效核销及当时比例计算单个账单订单的提成。 */
public final class CommissionCalculator
{
private static final BigDecimal HUNDRED = new BigDecimal("100");
private CommissionCalculator() {}
/** 比例以百分数表示,10 代表 10%;缺失比例不得按零处理。 */
public record Writeoff(BigDecimal amount, BigDecimal rate) {}
public record Result(BigDecimal estimated, BigDecimal formal, boolean complete) {}
public static Result calculate(BigDecimal billAmount, BigDecimal orderProfit, List<Writeoff> writeoffs)
{
if (billAmount == null || billAmount.signum() <= 0 || orderProfit == null || writeoffs == null)
{
return new Result(null, null, false);
}
BigDecimal written = BigDecimal.ZERO;
BigDecimal weightedRates = BigDecimal.ZERO;
boolean hasMissingRate = false;
for (Writeoff writeoff : writeoffs)
{
if (writeoff == null || writeoff.amount() == null || writeoff.amount().signum() <= 0)
{
throw new IllegalArgumentException("核销金额必须大于零");
}
written = written.add(writeoff.amount());
if (writeoff.rate() == null)
{
hasMissingRate = true;
}
else
{
if (writeoff.rate().signum() < 0 || writeoff.rate().compareTo(HUNDRED) > 0)
{
throw new IllegalArgumentException("提成比例必须在 0 至 100 之间");
}
weightedRates = weightedRates.add(writeoff.amount().multiply(writeoff.rate()));
}
}
if (written.compareTo(billAmount) > 0)
{
throw new IllegalArgumentException("有效核销金额超过账单金额");
}
boolean complete = written.compareTo(billAmount) == 0;
if (hasMissingRate)
{
return new Result(null, null, complete);
}
BigDecimal amount = orderProfit.multiply(weightedRates)
.divide(billAmount.multiply(HUNDRED), 2, RoundingMode.HALF_UP);
return new Result(amount, complete ? amount : null, complete);
}
/** 对同一账单的结果按明细顺序分配舍入尾差,使逐单金额之和等于该账单精确总额的四舍五入。 */
public static void allocateFinalAmounts(List<ArCommissionResult> items)
{
BigDecimal cumulativeNumerator = BigDecimal.ZERO;
BigDecimal allocated = BigDecimal.ZERO;
BigDecimal billAmount = null;
BigDecimal weightedRate = null;
for (ArCommissionResult item : items)
{
if (!"READY".equals(item.getResultStatus())) continue;
if (item.getBillAmount() == null || item.getBillAmount().signum() <= 0
|| item.getGrossProfit() == null || item.getWeightedRate() == null)
throw new IllegalArgumentException("正式提成计算数据不完整");
if (billAmount == null)
{
billAmount = item.getBillAmount();
weightedRate = item.getWeightedRate();
}
else if (billAmount.compareTo(item.getBillAmount()) != 0 || weightedRate.compareTo(item.getWeightedRate()) != 0)
throw new IllegalArgumentException("同一账单的提成计算依据不一致");
cumulativeNumerator = cumulativeNumerator.add(item.getGrossProfit().multiply(item.getWeightedRate()));
BigDecimal cumulativeAmount = cumulativeNumerator.divide(billAmount.multiply(HUNDRED), 2, RoundingMode.HALF_UP);
item.setCommissionAmount(cumulativeAmount.subtract(allocated));
allocated = cumulativeAmount;
}
}
}
@@ -24,6 +24,7 @@ import com.bms.ar.enums.ArLogResult;
import com.bms.ar.mapper.ArBalanceWriteoffMapper;
import com.bms.ar.mapper.ArBillMapper;
import com.bms.ar.security.ArBillScopeResolver;
import com.bms.ar.profit.ArCommissionService;
import com.bms.ar.service.IArBalanceWriteoffService;
import com.bms.ar.service.IArBillLogService;
import com.bms.common.exception.ServiceException;
@@ -49,6 +50,8 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
private ArBillMapper billMapper;
@Autowired
private ArBillScopeResolver billScope;
@Autowired
private ArCommissionService commissionService;
@Autowired
private ArBalanceWriteoffMapper writeoffMapper;
@@ -141,6 +144,7 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
writeoff.setCreateUserId(operatorUserId);
writeoff.setCreateBy(operator);
writeoffMapper.insertArBalanceWriteoff(writeoff);
commissionService.snapshotWriteoff(bill, writeoff);
// 3. 账单核销口径变更(2026-09-23):核销不再变动账户余额与已用额度,
// 仅更新账单已核销/未核销金额与状态,资金变动由收款/计费入口产生。
@@ -153,6 +157,10 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
throw new ServiceException("账单状态已发生变化,请刷新后重试");
}
if (ArBillStatus.WRITTEN_OFF.getCode().equals(nextStatus)) {
commissionService.createFinalResults(bill.getArBillId(), operator);
}
recordLog(bill.getArBillId(), writeoff.getWriteoffId(), ArLogOperationType.BALANCE_WRITEOFF,
"余额核销账单 " + amount.toPlainString() + " " + currency,
fromStatus, nextStatus, operator, requestId);
@@ -207,6 +215,7 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
ArBalanceWriteoffStatus.CANCELLED.getCode(), ArBalanceWriteoffStatus.EFFECTIVE.getCode()) != 1) {
throw new ServiceException("核销记录状态已变化,请刷新后重试");
}
commissionService.reverseFinalResults(bill.getArBillId(), operator);
recordLog(bill.getArBillId(), writeoffId, ArLogOperationType.CANCEL_BALANCE_WRITEOFF,
"反核销取消核销:" + cancelRemark,
fromStatus, nextStatus, operator, requestId);
@@ -73,6 +73,10 @@ import com.bms.ar.mapper.ArBillLogMapper;
import com.bms.ar.mapper.ArBillMapper;
import com.bms.ar.security.ArBillScopeResolver;
import com.bms.customer.customerinfo.domain.BmsCustomerOption;
import com.bms.customer.customerinfo.domain.BmsCustomer;
import com.bms.customer.customerinfo.mapper.BmsCustomerMapper;
import com.bms.common.core.domain.entity.SysUser;
import com.bms.system.mapper.SysUserMapper;
import com.bms.ar.mapper.ArBillGenerateTaskMapper;
import com.bms.ar.mapper.ArBankAccountMapper;
import com.bms.ar.mapper.ArExportTemplateMapper;
@@ -185,6 +189,10 @@ public class ArBillServiceImpl implements IArBillService {
@Autowired
private ArBillMapper billMapper;
@Autowired
private BmsCustomerMapper customerMapper;
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private ArBillScopeResolver billScope;
@Autowired
private ArBillGenerateTaskMapper generateTaskMapper;
@@ -441,6 +449,21 @@ public class ArBillServiceImpl implements IArBillService {
String customerName = StringUtils.trim(request.getCustomerName());
bill.setCustomerCode(customerCode == null ? "" : customerCode);
bill.setCustomerName(customerName == null ? "" : customerName);
bill.setProfitSnapshotSource("NEW");
// 固定账单生成时的客户归属;无法确定的用户保持为空,由财务核对。
BmsCustomer snapshotCustomer = customerMapper.selectBmsCustomerByCustomerId(request.getCustomerId());
if (snapshotCustomer != null) {
bill.setProfitCustomerArea(snapshotCustomer.getCustomerArea());
String salesId = snapshotCustomer.getSalesUserId();
if (salesId != null && salesId.matches("[0-9]{1,18}")) {
SysUser salesUser = sysUserMapper.selectUserById(Long.valueOf(salesId));
if (salesUser != null) {
bill.setProfitSalesUserId(salesUser.getUserId());
bill.setProfitSalesUserCode(salesUser.getUserName());
bill.setProfitSalesUserName(salesUser.getNickName());
}
}
}
bill.setBillPeriodStart(request.getBillPeriodEnd());
bill.setBillPeriodEnd(request.getBillPeriodEnd());
bill.setBillDate(request.getBillDate() == null ? now : request.getBillDate());
@@ -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;
}
@@ -51,11 +51,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;
}
@@ -16,6 +16,11 @@ public enum ProfitAreaRule
this.customerArea = customerArea;
}
public String getCustomerArea()
{
return customerArea;
}
public static ProfitAreaRule fromCustomerArea(String customerArea)
{
if (customerArea != null)
@@ -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);
@@ -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,38 @@ 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);
}
@@ -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);
}
@@ -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);
@@ -28,14 +28,62 @@ public final class 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 +100,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 +141,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 +152,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())
@@ -118,7 +244,7 @@ public final class PayCostCalculator
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 +257,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))
@@ -180,7 +341,18 @@ public final class PayCostCalculator
}
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 +450,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 +492,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]+"))
{
@@ -454,6 +454,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;
}
@@ -1250,6 +1253,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 +1300,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 +1455,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, "价格"));
@@ -4156,6 +4164,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);
}
@@ -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,25 +253,76 @@ 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())
@@ -174,9 +330,28 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
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();
@@ -3324,7 +3324,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;
@@ -141,6 +142,9 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
@Autowired
private IBmsCustomerService bmsCustomerService;
@Autowired
private PrcOrderBillMapper orderBillMapper;
@Override
public PrcPriceSet selectPrcPriceSetById(Long priceSetId)
{
@@ -626,7 +630,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 +638,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);
}
@@ -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)
@@ -388,7 +388,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)
{
@@ -992,16 +996,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,
@@ -11,6 +11,11 @@
<result property="customerId" column="customer_id"/>
<result property="customerCode" column="customer_code"/>
<result property="customerName" column="customer_name"/>
<result property="profitCustomerArea" column="profit_customer_area"/>
<result property="profitSalesUserId" column="profit_sales_user_id"/>
<result property="profitSalesUserCode" column="profit_sales_user_code"/>
<result property="profitSalesUserName" column="profit_sales_user_name"/>
<result property="profitSnapshotSource" column="profit_snapshot_source"/>
<result property="billPeriodStart" column="bill_period_start"/>
<result property="billPeriodEnd" column="bill_period_end"/>
<result property="billDate" column="bill_date"/>
@@ -48,6 +53,11 @@
customer_id,
customer_code,
customer_name,
profit_customer_area,
profit_sales_user_id,
profit_sales_user_code,
profit_sales_user_name,
profit_snapshot_source,
bill_period_start,
bill_period_end,
bill_date,
@@ -169,13 +179,15 @@
</select>
<insert id="insertArBill" parameterType="ArBill" useGeneratedKeys="true" keyProperty="arBillId">
insert into ar_bill (bill_no, bill_name, customer_id, customer_code, customer_name, bill_period_start,
insert into ar_bill (bill_no, bill_name, customer_id, customer_code, customer_name,
profit_customer_area, profit_sales_user_id, profit_sales_user_code, profit_sales_user_name, profit_snapshot_source, bill_period_start,
bill_period_end,
bill_date, currency, order_count, total_amount, written_off_amount, unwritten_amount,
status, generation_status, bill_version, bank_account_name, bank_account_no, bank_name,
remark,
confirmed_by, confirmed_time, create_by, create_user_id, create_time, update_by, update_time)
values (#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName}, #{billPeriodStart},
values (#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName},
#{profitCustomerArea}, #{profitSalesUserId}, #{profitSalesUserCode}, #{profitSalesUserName}, #{profitSnapshotSource}, #{billPeriodStart},
#{billPeriodEnd},
#{billDate}, #{currency}, #{orderCount}, #{totalAmount}, #{writtenOffAmount}, #{unwrittenAmount},
#{status}, #{generationStatus}, #{billVersion}, #{bankAccountName}, #{bankAccountNo}, #{bankName},
@@ -0,0 +1,187 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bms.ar.mapper.ArCommissionMapper">
<resultMap id="rate" type="com.bms.ar.profit.ArCommissionRate">
<id property="rateId" column="rate_id"/><result property="salesUserId" column="sales_user_id"/>
<result property="salesUserCode" column="sales_user_code"/><result property="salesUserName" column="sales_user_name"/>
<result property="rate" column="rate"/><result property="effectiveAt" column="effective_at"/>
<result property="createBy" column="create_by"/><result property="remark" column="remark"/>
</resultMap>
<resultMap id="missingRate" type="com.bms.ar.profit.ArWriteoffRate">
<id property="writeoffId" column="writeoff_id"/><result property="arBillId" column="ar_bill_id"/>
<result property="billNo" column="bill_no"/><result property="customerName" column="customer_name"/>
<result property="salesUserId" column="sales_user_id"/><result property="salesUserName" column="sales_user_name"/>
<result property="writeoffAmount" column="writeoff_amount"/><result property="writeoffDate" column="writeoff_date"/>
<result property="rate" column="rate"/>
<result property="status" column="status"/><result property="confirmedBy" column="confirmed_by"/>
<result property="confirmedTime" column="confirmed_time"/><result property="remark" column="confirm_remark"/>
</resultMap>
<resultMap id="commissionResult" type="com.bms.ar.profit.ArCommissionResult">
<id property="resultId" column="result_id"/><result property="arBillId" column="ar_bill_id"/>
<result property="detailId" column="detail_id"/><result property="billNo" column="bill_no"/>
<result property="orderNo" column="order_no"/><result property="salesUserName" column="sales_user_name"/>
<result property="currency" column="currency"/><result property="grossProfit" column="gross_profit"/>
<result property="commissionAmount" column="commission_amount"/><result property="resultStatus" column="result_status"/>
<result property="createTime" column="create_time"/>
<result property="reversedBy" column="reversed_by"/><result property="reversedTime" column="reversed_time"/>
<result property="salesUserId" column="sales_user_id"/><result property="weightedRate" column="weighted_rate"/>
<result property="billAmount" column="bill_amount"/>
</resultMap>
<resultMap id="commissionSummary" type="com.bms.ar.profit.ArCommissionSummary">
<result property="salesUserId" column="sales_user_id"/><result property="salesUserName" column="sales_user_name"/>
<result property="currency" column="currency"/><result property="orderCount" column="order_count"/>
<result property="pendingCount" column="pending_count"/><result property="commissionAmount" column="commission_amount"/>
</resultMap>
<select id="selectRates" resultMap="rate">
select r.rate_id, r.sales_user_id, u.user_name as sales_user_code, u.nick_name as sales_user_name,
r.rate, r.effective_at, r.create_by, r.remark
from ar_profit_commission_rate r left join sys_user u on u.user_id = r.sales_user_id
order by r.sales_user_id, r.effective_at desc, r.rate_id desc
</select>
<select id="selectEffective" resultMap="rate">
select rate_id, sales_user_id, rate, effective_at
from ar_profit_commission_rate
where sales_user_id = #{salesUserId} and effective_at &lt;= #{at}
order by effective_at desc, rate_id desc limit 1 for update
</select>
<insert id="insertRate" parameterType="com.bms.ar.profit.ArCommissionRate" useGeneratedKeys="true" keyProperty="rateId">
insert into ar_profit_commission_rate(sales_user_id, rate, effective_at, create_by, create_time, remark)
values(#{salesUserId}, #{rate}, #{effectiveAt}, #{createBy}, sysdate(), #{remark})
</insert>
<select id="lockSalesUser" resultType="long">
select user_id from sys_user where user_id = #{salesUserId} for update
</select>
<insert id="insertWriteoffRate">
insert into ar_profit_writeoff_rate(writeoff_id, sales_user_id, rate_id, rate, create_time)
values(#{writeoffId}, #{salesUserId}, #{rateId}, #{rate}, sysdate())
</insert>
<select id="selectMissingRates" resultMap="missingRate">
select w.writeoff_id, b.ar_bill_id, b.bill_no, b.customer_name,
b.profit_sales_user_id as sales_user_id, b.profit_sales_user_name as sales_user_name,
w.writeoff_amount, w.writeoff_date, r.rate
from ar_balance_writeoff w join ar_bill b on b.ar_bill_id = w.ar_bill_id
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
where w.status = 'EFFECTIVE' and (r.rate is null or r.rate &lt; 0 or r.rate > 100)
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF')
and b.generation_status = 'READY'
order by w.writeoff_date desc, w.writeoff_id desc
</select>
<select id="selectWriteoffRates" resultMap="missingRate">
select w.writeoff_id, b.ar_bill_id, b.bill_no, b.customer_name,
b.profit_sales_user_id as sales_user_id, b.profit_sales_user_name as sales_user_name,
w.writeoff_amount, w.writeoff_date, w.status, r.rate, r.confirmed_by, r.confirmed_time, r.confirm_remark
from ar_balance_writeoff w join ar_bill b on b.ar_bill_id = w.ar_bill_id
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
where b.ar_bill_id = #{billId} and b.generation_status = 'READY'
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF')
order by w.create_time, w.writeoff_id
</select>
<select id="selectBillIdByWriteoffId" resultType="long">
select ar_bill_id from ar_balance_writeoff where writeoff_id = #{writeoffId} and status = 'EFFECTIVE'
</select>
<select id="countMissingRates" resultType="int">
select count(*) from ar_balance_writeoff w
left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
where w.ar_bill_id = #{billId} and w.status = 'EFFECTIVE' and (r.rate is null or r.rate &lt; 0 or r.rate > 100)
</select>
<update id="confirmMissingRate">
update ar_profit_writeoff_rate r
join ar_balance_writeoff w on w.writeoff_id = r.writeoff_id and w.status = 'EFFECTIVE'
join ar_bill b on b.ar_bill_id = w.ar_bill_id
set r.sales_user_id = b.profit_sales_user_id, r.rate = #{rate}, r.confirmed_by = #{operator},
r.confirmed_time = sysdate(), r.confirm_remark = #{remark}
where r.writeoff_id = #{writeoffId} and r.rate is null and b.profit_sales_user_id is not null
</update>
<select id="selectResults" resultMap="commissionResult">
select r.result_id, r.ar_bill_id, r.detail_id, b.bill_no, d.order_no,
b.profit_sales_user_name as sales_user_name, r.currency, r.gross_profit,
r.commission_amount, r.result_status, r.create_time, r.reversed_by, r.reversed_time
from ar_profit_commission_result r join ar_bill b on b.ar_bill_id = r.ar_bill_id
join ar_bill_detail d on d.detail_id = r.detail_id
where 1 = 1
<choose>
<when test="includeReversed">and (r.result_status = 'REVERSED' or (b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'))</when>
<otherwise>and r.result_status != 'REVERSED' and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'</otherwise>
</choose>
<if test="billId != null">and r.ar_bill_id = #{billId}</if>
order by r.result_id desc
</select>
<select id="selectCommissionSummary" resultMap="commissionSummary">
select r.sales_user_id, max(b.profit_sales_user_name) as sales_user_name, r.currency,
count(*) as order_count,
sum(case when r.result_status != 'READY' then 1 else 0 end) as pending_count,
<choose>
<when test="billId != null">
case when sum(case when r.result_status != 'READY' then 1 else 0 end) > 0 then null
else sum(case when r.result_status = 'READY' then r.commission_amount else null end) end
</when>
<otherwise>sum(case when r.result_status = 'READY' then r.commission_amount else null end)</otherwise>
</choose> as commission_amount
from ar_profit_commission_result r join ar_bill b on b.ar_bill_id = r.ar_bill_id
where r.result_status != 'REVERSED' and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'
<if test="billId != null">and r.ar_bill_id = #{billId}</if>
group by r.sales_user_id, r.currency
order by sales_user_name, r.currency
</select>
<update id="reverseResults">
update ar_profit_commission_result
set result_status = 'REVERSED', reversed_by = #{operator}, reversed_time = sysdate()
where ar_bill_id = #{billId} and result_status != 'REVERSED'
</update>
<!-- 当且仅当账单全部核销时,以当次费用快照及每笔有效核销的比例生成正式记录。 -->
<select id="selectSettlementInputs" resultMap="commissionResult">
<bind name="shenzhenArea" value="@com.bms.price.enums.ProfitAreaRule@SHENZHEN.getCustomerArea()"/>
<bind name="guangzhouArea" value="@com.bms.price.enums.ProfitAreaRule@GUANGZHOU.getCustomerArea()"/>
select x.ar_bill_id, x.detail_id, x.profit_sales_user_id as sales_user_id, x.currency, x.gross_profit,
x.weighted_rate, x.total_amount as bill_amount, coalesce(x.issue, 'READY') as result_status
from (
select b.ar_bill_id, d.detail_id, b.profit_sales_user_id, d.currency, b.total_amount, w.weighted_rate,
case when f.currency_count = 1 and f.fee_currency = d.currency and d.currency = b.currency and f.sales_amount = d.total_amount and b.profit_customer_area = #{shenzhenArea} and f.product_complete = 1
then f.sales_amount - f.product_amount
when f.currency_count = 1 and f.fee_currency = d.currency and d.currency = b.currency and f.sales_amount = d.total_amount and b.profit_customer_area = #{guangzhouArea} and f.redline_complete = 1
then f.sales_amount - f.redline_amount else null end as gross_profit,
case when b.profit_sales_user_id is null or b.profit_customer_area is null
or b.profit_customer_area not in (#{shenzhenArea},#{guangzhouArea}) then 'MISSING_SNAPSHOT'
when w.bill_id is null or w.written_amount != b.total_amount then 'WRITEOFF_MISMATCH'
when w.missing_rates > 0 then 'MISSING_RATE'
when b.total_amount is null or b.total_amount &lt;= 0 or d.total_amount is null
or d.currency is null or b.currency is null or f.sales_amount is null
or f.currency_count != 1 or f.fee_currency != d.currency or d.currency != b.currency
or f.sales_amount != d.total_amount
or (b.profit_customer_area = #{shenzhenArea} and coalesce(f.product_complete, 0) = 0)
or (b.profit_customer_area = #{guangzhouArea} and coalesce(f.redline_complete, 0) = 0)
then 'MISSING_PRICE'
else null end as issue
from ar_bill b inner join ar_bill_detail d on d.ar_bill_id = b.ar_bill_id
left join (
select fee.detail_id, case when count(fee.amount) = count(*) then sum(fee.amount) else null end as sales_amount,
case when count(fee.currency) = count(*) then count(distinct fee.currency) else 0 end as currency_count, min(fee.currency) as fee_currency,
case when count(fee.product_amount) = count(*) then sum(fee.product_amount) else null end as product_amount,
case when count(fee.redline_amount) = count(*) then sum(fee.redline_amount) else null end as redline_amount,
case when count(fee.product_amount) = count(*) then 1 else 0 end as product_complete,
case when count(fee.redline_amount) = count(*) then 1 else 0 end as redline_complete
from ar_bill_detail_fee fee join ar_bill_detail detail on detail.detail_id = fee.detail_id
where detail.ar_bill_id = #{billId} group by fee.detail_id
) f on f.detail_id = d.detail_id
left join (
select w.ar_bill_id as bill_id, sum(w.writeoff_amount) as written_amount,
sum(case when r.rate is null or r.rate &lt; 0 or r.rate > 100 then 1 else 0 end) as missing_rates,
sum(w.writeoff_amount * r.rate) as weighted_rate
from ar_balance_writeoff w left join ar_profit_writeoff_rate r on r.writeoff_id = w.writeoff_id
where w.status = 'EFFECTIVE' and w.ar_bill_id = #{billId}
group by w.ar_bill_id
) w on w.bill_id = b.ar_bill_id
where b.ar_bill_id = #{billId} and b.status = 'WRITTEN_OFF' and b.generation_status = 'READY'
) x order by x.detail_id
</select>
<insert id="insertResults">
insert into ar_profit_commission_result
(ar_bill_id, detail_id, sales_user_id, currency, gross_profit, commission_amount, result_status, create_by, create_time)
values
<foreach collection="items" item="item" separator=",">
(#{item.arBillId}, #{item.detailId}, #{item.salesUserId}, #{item.currency}, #{item.grossProfit},
#{item.commissionAmount}, #{item.resultStatus}, #{operator}, sysdate())
</foreach>
</insert>
</mapper>
@@ -0,0 +1,158 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bms.ar.mapper.ArProfitMapper">
<resultMap id="row" type="com.bms.ar.profit.ArProfitRow">
<id property="arBillId" column="ar_bill_id"/>
<result property="billNo" column="bill_no"/><result property="billDate" column="bill_date"/>
<result property="customerCode" column="customer_code"/><result property="customerName" column="customer_name"/>
<result property="customerArea" column="customer_area"/><result property="snapshotSource" column="snapshot_source"/>
<result property="salesUserName" column="sales_user_name"/><result property="currency" column="currency"/>
<result property="status" column="status"/><result property="salesAmount" column="sales_amount"/>
<result property="productAmount" column="product_amount"/><result property="salesGrossProfit" column="sales_gross_profit"/>
<result property="salesGrossMarginRate" column="sales_gross_margin_rate"/>
<result property="writtenOffAmount" column="written_off_amount"/><result property="unwrittenAmount" column="unwritten_amount"/>
</resultMap>
<resultMap id="summary" type="com.bms.ar.profit.ArProfitSummary">
<result property="currency" column="currency"/><result property="billCount" column="bill_count"/>
<result property="invalidBillCount" column="invalid_bill_count"/>
<result property="salesAmount" column="sales_amount"/><result property="productAmount" column="product_amount"/>
<result property="salesGrossProfit" column="sales_gross_profit"/><result property="salesGrossMarginRate" column="sales_gross_margin_rate"/>
<result property="writtenOffAmount" column="written_off_amount"/><result property="unwrittenAmount" column="unwritten_amount"/>
</resultMap>
<resultMap id="detail" type="com.bms.ar.domain.ArBillDetail">
<id property="detailId" column="detail_id"/><result property="orderNo" column="order_no"/>
<result property="productName" column="product_name"/><result property="currency" column="currency"/>
<result property="totalAmount" column="total_amount"/>
</resultMap>
<resultMap id="fee" type="com.bms.ar.domain.ArBillDetailFee">
<id property="detailFeeId" column="detail_fee_id"/><result property="detailId" column="detail_id"/>
<result property="feeName" column="fee_name"/><result property="feeType" column="fee_type"/>
<result property="amount" column="amount"/><result property="productAmount" column="product_amount"/>
<result property="redlineAmount" column="redline_amount"/><result property="currency" column="currency"/>
</resultMap>
<sql id="scopeCondition">
<choose>
<when test="scope.all"/>
<when test="scope.self or scope.department">
and (1 = 0
<if test="scope.self">or b.profit_sales_user_id = #{scope.userId}</if>
<if test="scope.department">
or exists (select 1 from sys_user u inner join sys_dept dept on dept.dept_id = u.dept_id
where u.user_id = b.profit_sales_user_id and u.del_flag = '0'
and (dept.dept_id = #{scope.deptId} or find_in_set(#{scope.deptId}, dept.ancestors)))
</if>
)
</when>
<otherwise>and 1 = 0</otherwise>
</choose>
</sql>
<!-- 订单号仅用于筛选账单,不限制该账单内参与计算的明细。 -->
<sql id="billConditions">
where b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
<include refid="scopeCondition"/>
<if test="query.customerId != null">and b.customer_id = #{query.customerId}</if>
<if test="query.billNo != null and query.billNo != ''">and b.bill_no like concat('%', #{query.billNo}, '%')</if>
<if test="query.arBillId != null">and b.ar_bill_id = #{query.arBillId}</if>
<if test="query.orderNo != null and query.orderNo != ''">
and exists (select 1 from ar_bill_detail matched where matched.ar_bill_id = b.ar_bill_id
and matched.order_no like concat('%', #{query.orderNo}, '%'))
</if>
<if test="query.status != null and query.status != ''">and b.status = #{query.status}</if>
<if test="query.salesUserId != null">and b.profit_sales_user_id = #{query.salesUserId}</if>
<if test="query.beginBillDate != null">and b.bill_date &gt;= #{query.beginBillDate}</if>
<if test="query.endBillDate != null">and b.bill_date &lt;= #{query.endBillDate}</if>
</sql>
<!-- 按费用快照先聚合到订单,再聚合到完整账单,避免账单金额及费用重复。 -->
<sql id="billRows">
<bind name="shenzhenArea" value="@com.bms.price.enums.ProfitAreaRule@SHENZHEN.getCustomerArea()"/>
<bind name="guangzhouArea" value="@com.bms.price.enums.ProfitAreaRule@GUANGZHOU.getCustomerArea()"/>
select b.ar_bill_id, b.bill_no, b.bill_date, b.customer_code, b.customer_name,
b.profit_customer_area as customer_area, b.profit_snapshot_source as snapshot_source,
b.profit_sales_user_name as sales_user_name, b.currency, b.status,
b.total_amount as sales_amount, b.written_off_amount, b.unwritten_amount,
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
and a.detail_total = b.total_amount then a.product_total else null end as product_amount,
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
and a.detail_total = b.total_amount then b.total_amount - a.product_total else null end as sales_gross_profit,
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
and a.detail_total = b.total_amount and b.total_amount != 0
then round((b.total_amount - a.product_total) * 100 / b.total_amount, 4) else null end as sales_gross_margin_rate,
case when a.detail_count > 0 and a.invalid_count = 0 and b.total_amount is not null
and a.detail_total = b.total_amount then 0 else 1 end as profit_incomplete
from ar_bill b
left join (
select d.ar_bill_id, count(*) as detail_count, sum(d.total_amount) as detail_total,
sum(case when d.total_amount is not null and d.currency is not null and b.currency is not null
and d.currency = b.currency and f.currency_count = 1 and f.fee_currency = d.currency
and f.sales_amount is not null and f.sales_amount = d.total_amount
and ((b.profit_customer_area = #{shenzhenArea} and f.product_complete = 1)
or (b.profit_customer_area = #{guangzhouArea} and f.redline_complete = 1))
then 0 else 1 end) as invalid_count,
sum(case when b.profit_customer_area = #{shenzhenArea} then f.product_amount
when b.profit_customer_area = #{guangzhouArea} then f.redline_amount else null end) as product_total
from ar_bill_detail d join ar_bill b on b.ar_bill_id = d.ar_bill_id
left join (
select fee.detail_id,
case when count(fee.amount) = count(*) then sum(fee.amount) else null end as sales_amount,
case when count(fee.currency) = count(*) then count(distinct fee.currency) else 0 end as currency_count,
min(fee.currency) as fee_currency,
case when count(fee.product_amount) = count(*) then sum(fee.product_amount) else null end as product_amount,
case when count(fee.redline_amount) = count(*) then sum(fee.redline_amount) else null end as redline_amount,
case when count(fee.product_amount) = count(*) then 1 else 0 end as product_complete,
case when count(fee.redline_amount) = count(*) then 1 else 0 end as redline_complete
from ar_bill_detail_fee fee
join ar_bill_detail d on d.detail_id = fee.detail_id
join ar_bill b on b.ar_bill_id = d.ar_bill_id
<include refid="billConditions"/>
group by fee.detail_id
) f on f.detail_id = d.detail_id
<include refid="billConditions"/>
group by d.ar_bill_id
) a on a.ar_bill_id = b.ar_bill_id
<include refid="billConditions"/>
</sql>
<select id="selectBills" resultMap="row">
<include refid="billRows"/>
order by b.bill_date desc, b.ar_bill_id desc
</select>
<select id="selectSummary" resultMap="summary">
select t.currency, count(*) as bill_count, sum(t.profit_incomplete) as invalid_bill_count,
sum(t.sales_amount) as sales_amount, sum(t.product_amount) as product_amount,
sum(t.sales_gross_profit) as sales_gross_profit,
case when sum(case when t.profit_incomplete = 0 then t.sales_amount else null end) = 0 then null
else round(sum(t.sales_gross_profit) * 100 /
sum(case when t.profit_incomplete = 0 then t.sales_amount else null end), 4) end as sales_gross_margin_rate,
sum(t.written_off_amount) as written_off_amount, sum(t.unwritten_amount) as unwritten_amount
from (<include refid="billRows"/>) t group by t.currency order by t.currency
</select>
<select id="selectSalesOptions" resultType="com.bms.ar.profit.ArProfitSalesOption">
select u.user_id as userId, u.nick_name as name, u.user_name as code
from sys_user u
where u.del_flag = '0' and u.status = '0'
<if test="keyword != null and keyword != ''">
and (u.nick_name like concat('%', #{keyword}, '%')
or u.user_name like concat('%', #{keyword}, '%'))
</if>
order by u.nick_name, u.user_id
limit 50
</select>
<select id="selectBillDetails" resultMap="detail">
select d.detail_id, d.order_no, d.product_name, d.currency, d.total_amount
from ar_bill_detail d join ar_bill b on b.ar_bill_id = d.ar_bill_id
where b.ar_bill_id = #{query.arBillId}
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
<include refid="scopeCondition"/>
order by d.detail_no, d.detail_id
</select>
<select id="selectFees" resultMap="fee">
select f.* from ar_bill_detail_fee f
join ar_bill_detail d on d.detail_id = f.detail_id
join ar_bill b on b.ar_bill_id = d.ar_bill_id
where d.detail_id = #{query.detailId}
and b.status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF', 'WRITTEN_OFF') and b.generation_status = 'READY'
<include refid="scopeCondition"/>
order by f.fee_no, f.detail_fee_id
</select>
</mapper>
@@ -100,6 +100,20 @@
select group_id from pay_postcode_group where file_md5 = #{fileMd5} and sheet_name = #{sheetName}
</select>
<select id="selectGroupsForProduct" resultType="com.bms.price.domain.PayPostcodeGroup">
select group_id as groupId, block_title as blockTitle, channel_name as channelName,
product_name as productName, quote_sheet as quoteSheet, sheet_name as sheetName,
config_kind as configKind, coverage, fee_name as feeName, fee_text as feeText,
country_name as countryName, country_code as countryCode
from pay_postcode_group
where
<foreach collection="names" item="name" separator=" or ">
lower(quote_sheet) = lower(#{name})
or lower(product_name) = lower(#{name})
or lower(sheet_name) = lower(#{name})
</foreach>
</select>
<select id="selectGroupsByTokens" resultType="com.bms.price.domain.PayPostcodeGroup">
select group_id as groupId, block_title as blockTitle, channel_name as channelName,
product_name as productName, quote_sheet as quoteSheet, sheet_name as sheetName,
@@ -250,12 +250,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertSurcharges">
insert into pay_surcharge (
product_id, version_no, section_name, fee_name, zone_name, charge_text, amount, currency, price_unit, fee_desc, period_text,
effective_start, effective_end, charge_timing, calc_rule, calc_param, sort_no
effective_start, effective_end, charge_timing, calc_rule, calc_param, weight_min, weight_max, postcode_param, sort_no
) values
<foreach collection="list" item="row" separator=",">
(#{row.productId}, ifnull(#{row.versionNo}, 1), #{row.sectionName}, #{row.feeName}, #{row.zoneName}, #{row.chargeText}, #{row.amount},
#{row.currency}, #{row.priceUnit}, #{row.feeDesc}, #{row.periodText}, #{row.effectiveStart}, #{row.effectiveEnd},
#{row.chargeTiming}, ifnull(#{row.calcRule}, 'MANUAL'), #{row.calcParam}, #{row.sortNo})
#{row.chargeTiming}, ifnull(#{row.calcRule}, 'MANUAL'), #{row.calcParam}, #{row.weightMin}, #{row.weightMax},
#{row.postcodeParam}, #{row.sortNo})
</foreach>
</insert>
@@ -280,7 +281,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
select surcharge_id as surchargeId, product_id as productId, version_no as versionNo, section_name as sectionName, fee_name as feeName,
zone_name as zoneName, charge_text as chargeText, amount, currency, price_unit as priceUnit, fee_desc as feeDesc,
period_text as periodText, effective_start as effectiveStart, effective_end as effectiveEnd,
charge_timing as chargeTiming, calc_rule as calcRule, calc_param as calcParam, sort_no as sortNo
charge_timing as chargeTiming, calc_rule as calcRule, calc_param as calcParam,
weight_min as weightMin, weight_max as weightMax, postcode_param as postcodeParam, sort_no as sortNo
from pay_surcharge
where product_id in
<foreach collection="productIds" item="id" open="(" separator="," close=")">#{id}</foreach>
@@ -1077,4 +1077,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
update_time = sysdate()
where bill_id = #{billId}
</update>
<select id="countByPsvId" resultType="int">
select count(1) from prc_order_bill where psv_id = #{psvId}
</select>
</mapper>
+339
View File
@@ -0,0 +1,339 @@
-- 应收账单毛利分析:增量结构与历史客户归属快照。
-- MySQL 5.7+;停用后端写入并备份数据库,再执行本文件,最后部署新版本并重新登录。
-- DDL 自动提交;数据与菜单授权使用事务。失败后检查已创建对象并修复结构,再重试完整文件。
-- 历史区域及销售员来自当前客户资料,不代表能还原历史真实归属。
-- 已有快照不会覆盖。账单来源订单销售员与当前客户销售员不一致时不自动回填销售员。
SET NAMES utf8mb4;
DROP PROCEDURE IF EXISTS bms_ar_profit_upgrade_20261105_v1;
DELIMITER $$
CREATE PROCEDURE bms_ar_profit_upgrade_20261105_v1()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE report_id BIGINT DEFAULT NULL;
DECLARE page_id BIGINT DEFAULT NULL;
DECLARE export_id BIGINT DEFAULT NULL;
DECLARE commission_id BIGINT DEFAULT NULL;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
SELECT COUNT(*) INTO n FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name IN ('ar_bill','ar_bill_detail','ar_bill_detail_fee','ar_balance_writeoff','ctr_customer','prc_order_bill','sys_user','sys_dept','sys_role','sys_menu','sys_role_menu');
IF n <> 11 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '应收毛利升级前置表缺失'; END IF;
SELECT COUNT(*) INTO n FROM sys_menu WHERE parent_id = 0 AND menu_type = 'M' AND menu_name = '报表中心';
IF n > 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '报表中心目录不唯一'; END IF;
SELECT COUNT(*) INTO n FROM (SELECT perms FROM sys_menu WHERE perms IN
('report:arProfit:list','report:arProfit:export','report:arProfit:commission') GROUP BY perms HAVING COUNT(*) > 1) conflicts;
IF n > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '应收毛利菜单权限重复'; END IF;
SELECT COUNT(*) INTO n FROM (SELECT role_key FROM sys_role WHERE role_key IN
('ORA_6040','ORA_6041','ORA_6042','ORA_6043') AND del_flag = '0' GROUP BY role_key HAVING COUNT(*) > 1) conflicts;
IF n > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '应收毛利角色标识重复'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'ar_bill' AND column_name = 'profit_customer_area';
IF n = 0 THEN ALTER TABLE ar_bill ADD COLUMN profit_customer_area VARCHAR(50) NULL COMMENT '账单客户区域快照'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'ar_bill' AND column_name = 'profit_sales_user_id';
IF n = 0 THEN ALTER TABLE ar_bill ADD COLUMN profit_sales_user_id BIGINT NULL COMMENT '账单销售员用户ID快照'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'ar_bill' AND column_name = 'profit_sales_user_code';
IF n = 0 THEN ALTER TABLE ar_bill ADD COLUMN profit_sales_user_code VARCHAR(64) NULL COMMENT '账单销售员工号快照'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'ar_bill' AND column_name = 'profit_sales_user_name';
IF n = 0 THEN ALTER TABLE ar_bill ADD COLUMN profit_sales_user_name VARCHAR(64) NULL COMMENT '账单销售员姓名快照'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'ar_bill' AND column_name = 'profit_snapshot_source';
IF n = 0 THEN ALTER TABLE ar_bill ADD COLUMN profit_snapshot_source VARCHAR(16) NULL COMMENT 'NEW生成时快照/BACKFILLED历史补录'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ar_bill'
AND is_nullable = 'YES'
AND ((column_name = 'profit_customer_area' AND data_type = 'varchar' AND character_maximum_length = 50)
OR (column_name = 'profit_sales_user_id' AND data_type = 'bigint')
OR (column_name IN ('profit_sales_user_code','profit_sales_user_name') AND data_type = 'varchar' AND character_maximum_length = 64)
OR (column_name = 'profit_snapshot_source' AND data_type = 'varchar' AND character_maximum_length = 16));
IF n <> 5 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '账单快照字段结构冲突'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE()
AND table_name = 'ar_bill' AND index_name = 'idx_ar_profit_sales_date';
IF n = 0 THEN ALTER TABLE ar_bill ADD INDEX idx_ar_profit_sales_date (profit_sales_user_id, bill_date, ar_bill_id); END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE()
AND table_name = 'ar_bill' AND index_name = 'idx_ar_profit_sales_date'
AND ((seq_in_index = 1 AND column_name = 'profit_sales_user_id')
OR (seq_in_index = 2 AND column_name = 'bill_date')
OR (seq_in_index = 3 AND column_name = 'ar_bill_id'));
IF n <> 3 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '账单毛利索引结构冲突'; END IF;
-- 提成比例版本及每次核销时的比例快照;历史核销未录入比例时保留空值待财务确认。
CREATE TABLE IF NOT EXISTS ar_profit_commission_rate (
rate_id BIGINT NOT NULL AUTO_INCREMENT COMMENT '提成比例记录ID',
sales_user_id BIGINT NOT NULL COMMENT '销售员用户ID',
rate DECIMAL(7,4) NOT NULL COMMENT '提成比例,百分数,例如10表示10%',
effective_at DATETIME NOT NULL COMMENT '比例生效时间',
create_by VARCHAR(64) NOT NULL COMMENT '创建人',
create_time DATETIME NOT NULL COMMENT '创建时间',
remark VARCHAR(500) NULL COMMENT '备注',
PRIMARY KEY (rate_id),
KEY idx_ar_profit_rate_effective (sales_user_id, effective_at, rate_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账单毛利销售员提成比例版本';
CREATE TABLE IF NOT EXISTS ar_profit_writeoff_rate (
writeoff_id BIGINT NOT NULL COMMENT '核销记录ID',
sales_user_id BIGINT NULL COMMENT '销售员用户ID',
rate_id BIGINT NULL COMMENT '提成比例记录ID',
rate DECIMAL(7,4) NULL COMMENT '提成比例,百分数,例如10表示10%',
create_time DATETIME NOT NULL COMMENT '创建时间',
confirmed_by VARCHAR(64) NULL COMMENT '历史比例确认人',
confirmed_time DATETIME NULL COMMENT '历史比例确认时间',
confirm_remark VARCHAR(500) NULL COMMENT '历史比例确认说明',
PRIMARY KEY (writeoff_id),
KEY idx_ar_profit_writeoff_rate_sales (sales_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账单核销时提成比例快照';
CREATE TABLE IF NOT EXISTS ar_profit_commission_result (
result_id BIGINT NOT NULL AUTO_INCREMENT COMMENT '提成结果ID',
ar_bill_id BIGINT NOT NULL COMMENT '应收账单ID',
detail_id BIGINT NOT NULL COMMENT '应收账单明细ID',
sales_user_id BIGINT NULL COMMENT '销售员用户ID',
currency VARCHAR(10) NOT NULL COMMENT '币种',
gross_profit DECIMAL(18,4) NULL COMMENT '销售毛利',
commission_amount DECIMAL(18,2) NULL COMMENT '提成金额',
result_status VARCHAR(24) NOT NULL COMMENT 'READY/MISSING_RATE/MISSING_PRICE/MISSING_SNAPSHOT/WRITEOFF_MISMATCH/REVERSED',
create_by VARCHAR(64) NOT NULL COMMENT '创建人',
create_time DATETIME NOT NULL COMMENT '创建时间',
reversed_by VARCHAR(64) NULL COMMENT '冲回操作人',
reversed_time DATETIME NULL COMMENT '冲回时间',
PRIMARY KEY (result_id),
KEY idx_ar_profit_result_bill (ar_bill_id, result_status, detail_id),
KEY idx_ar_profit_result_sales (sales_user_id, result_status, create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账单完全核销时逐单正式提成及冲回记录';
-- 检查已有表结构,避免 IF NOT EXISTS 掩盖不兼容的旧结构。
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ar_profit_commission_rate'
AND column_name IN ('rate_id','sales_user_id','rate','effective_at','create_by','create_time','remark');
IF n <> 7 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成比例表结构不完整'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ar_profit_writeoff_rate'
AND column_name IN ('writeoff_id','sales_user_id','rate_id','rate','create_time','confirmed_by','confirmed_time','confirm_remark');
IF n <> 8 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '核销比例表结构不完整'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ar_profit_commission_result'
AND column_name IN ('result_id','ar_bill_id','detail_id','sales_user_id','currency','gross_profit','commission_amount','result_status','create_by','create_time','reversed_by','reversed_time');
IF n <> 12 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '逐单提成表结构不完整'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.tables WHERE table_schema = DATABASE()
AND table_name IN ('ar_profit_commission_rate','ar_profit_writeoff_rate','ar_profit_commission_result') AND engine = 'InnoDB';
IF n <> 3 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成相关表必须使用 InnoDB'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE()
AND table_name IN ('ar_profit_commission_rate','ar_profit_writeoff_rate') AND column_name = 'rate' AND column_type = 'decimal(7,4)';
IF n <> 2 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成比例字段类型不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE()
AND ((table_name = 'ar_profit_commission_rate' AND column_name IN ('rate_id','sales_user_id') AND data_type = 'bigint' AND is_nullable = 'NO')
OR (table_name = 'ar_profit_commission_rate' AND column_name = 'effective_at' AND data_type = 'datetime' AND is_nullable = 'NO')
OR (table_name = 'ar_profit_writeoff_rate' AND column_name = 'writeoff_id' AND data_type = 'bigint' AND is_nullable = 'NO')
OR (table_name = 'ar_profit_writeoff_rate' AND column_name IN ('sales_user_id','rate_id') AND data_type = 'bigint' AND is_nullable = 'YES')
OR (table_name = 'ar_profit_writeoff_rate' AND column_name = 'rate' AND is_nullable = 'YES'));
IF n <> 7 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成比例关键字段类型或空值约束不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'ar_profit_commission_result'
AND ((column_name = 'gross_profit' AND column_type = 'decimal(18,4)')
OR (column_name = 'commission_amount' AND column_type = 'decimal(18,2)')
OR (column_name = 'result_status' AND data_type = 'varchar' AND character_maximum_length = 24)
OR (column_name IN ('result_id','ar_bill_id','detail_id','sales_user_id') AND data_type = 'bigint'));
IF n <> 7 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '逐单提成字段类型不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = 'ar_profit_writeoff_rate'
AND index_name = 'PRIMARY' AND column_name = 'writeoff_id' AND seq_in_index = 1;
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '核销比例表主键不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = 'ar_profit_writeoff_rate' AND index_name = 'PRIMARY';
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '核销比例表主键必须仅包含 writeoff_id'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = 'ar_profit_commission_rate'
AND index_name = 'PRIMARY' AND column_name = 'rate_id' AND seq_in_index = 1;
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成比例表主键不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = 'ar_profit_commission_result'
AND index_name = 'PRIMARY' AND column_name = 'result_id' AND seq_in_index = 1;
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '逐单提成表主键不匹配'; END IF;
SELECT COUNT(*) INTO n FROM information_schema.statistics WHERE table_schema = DATABASE()
AND ((table_name = 'ar_profit_commission_rate' AND index_name = 'PRIMARY')
OR (table_name = 'ar_profit_commission_result' AND index_name = 'PRIMARY'));
IF n <> 2 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成表主键结构不匹配'; END IF;
-- 旧版本已经建表时,只补充空注释;按实际元数据保留字段类型、字符集和空值约束。
-- 对无法安全重建的默认值、生成列或其他额外属性先中止,不擅自改写字段定义。
SELECT COUNT(*) INTO n FROM information_schema.columns
WHERE table_schema = DATABASE() AND column_comment = ''
AND ((table_name = 'ar_profit_commission_rate' AND column_name IN ('rate_id','sales_user_id','rate','effective_at','create_by','create_time','remark'))
OR (table_name = 'ar_profit_writeoff_rate' AND column_name IN ('writeoff_id','sales_user_id','rate_id','rate','create_time','confirmed_by','confirmed_time','confirm_remark'))
OR (table_name = 'ar_profit_commission_result' AND column_name IN ('result_id','ar_bill_id','detail_id','sales_user_id','currency','gross_profit','commission_amount','result_status','create_by','create_time','reversed_by','reversed_time')))
AND (column_default IS NOT NULL OR extra NOT IN ('','auto_increment') OR data_type NOT IN ('bigint','decimal','datetime','varchar'));
IF n > 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '提成表待补注释字段存在特殊定义,请检查后再执行'; END IF;
BEGIN
DECLARE v_table VARCHAR(64);
DECLARE v_table_index INT DEFAULT 1;
DECLARE v_old_concat_limit BIGINT UNSIGNED;
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SET SESSION group_concat_max_len = v_old_concat_limit;
RESIGNAL;
END;
SET v_old_concat_limit = @@SESSION.group_concat_max_len;
SET SESSION group_concat_max_len = 65535;
WHILE v_table_index <= 3 DO
SET v_table = CASE v_table_index
WHEN 1 THEN 'ar_profit_commission_rate'
WHEN 2 THEN 'ar_profit_writeoff_rate'
ELSE 'ar_profit_commission_result' END;
SELECT GROUP_CONCAT(CONCAT(
'MODIFY COLUMN `', REPLACE(column_name, '`', '``'), '` ', column_type,
IF(character_set_name IS NULL, '', CONCAT(' CHARACTER SET ', character_set_name, ' COLLATE ', collation_name)),
IF(is_nullable = 'YES', ' NULL DEFAULT NULL', ' NOT NULL'),
IF(extra = 'auto_increment', ' AUTO_INCREMENT', ''),
' COMMENT ', QUOTE(CASE column_name
WHEN 'rate_id' THEN '提成比例记录ID'
WHEN 'sales_user_id' THEN '销售员用户ID'
WHEN 'rate' THEN '提成比例,百分数,例如10表示10%'
WHEN 'effective_at' THEN '比例生效时间'
WHEN 'create_by' THEN '创建人'
WHEN 'create_time' THEN '创建时间'
WHEN 'remark' THEN '备注'
WHEN 'writeoff_id' THEN '核销记录ID'
WHEN 'confirmed_by' THEN '历史比例确认人'
WHEN 'confirmed_time' THEN '历史比例确认时间'
WHEN 'confirm_remark' THEN '历史比例确认说明'
WHEN 'result_id' THEN '提成结果ID'
WHEN 'ar_bill_id' THEN '应收账单ID'
WHEN 'detail_id' THEN '应收账单明细ID'
WHEN 'currency' THEN '币种'
WHEN 'gross_profit' THEN '销售毛利'
WHEN 'commission_amount' THEN '提成金额'
WHEN 'result_status' THEN 'READY/MISSING_RATE/MISSING_PRICE/MISSING_SNAPSHOT/WRITEOFF_MISMATCH/REVERSED'
WHEN 'reversed_by' THEN '冲回操作人'
WHEN 'reversed_time' THEN '冲回时间'
END)) ORDER BY ordinal_position SEPARATOR ', ')
INTO @bms_ar_profit_comment_columns
FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = v_table AND column_comment = ''
AND ((table_name = 'ar_profit_commission_rate' AND column_name IN ('rate_id','sales_user_id','rate','effective_at','create_by','create_time','remark'))
OR (table_name = 'ar_profit_writeoff_rate' AND column_name IN ('writeoff_id','sales_user_id','rate_id','rate','create_time','confirmed_by','confirmed_time','confirm_remark'))
OR (table_name = 'ar_profit_commission_result' AND column_name IN ('result_id','ar_bill_id','detail_id','sales_user_id','currency','gross_profit','commission_amount','result_status','create_by','create_time','reversed_by','reversed_time')));
IF @bms_ar_profit_comment_columns IS NOT NULL THEN
SET @bms_ar_profit_comment_ddl = CONCAT('ALTER TABLE `', REPLACE(v_table, '`', '``'), '` ', @bms_ar_profit_comment_columns);
PREPARE bms_ar_profit_comment_stmt FROM @bms_ar_profit_comment_ddl;
EXECUTE bms_ar_profit_comment_stmt;
DEALLOCATE PREPARE bms_ar_profit_comment_stmt;
END IF;
SET v_table_index = v_table_index + 1;
END WHILE;
SET SESSION group_concat_max_len = v_old_concat_limit;
END;
SELECT MAX(menu_id) INTO report_id FROM sys_menu WHERE parent_id = 0 AND menu_type = 'M' AND menu_name = '报表中心';
SELECT MAX(menu_id) INTO page_id FROM sys_menu WHERE perms = 'report:arProfit:list';
IF page_id IS NOT NULL THEN
SELECT COUNT(*) INTO n FROM sys_menu WHERE menu_id = page_id AND parent_id = report_id AND component = 'report/arProfit/index' AND menu_type = 'C';
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '现有应收毛利菜单与预期不符'; END IF;
END IF;
SELECT MAX(menu_id) INTO export_id FROM sys_menu WHERE perms = 'report:arProfit:export';
IF export_id IS NOT NULL THEN
SELECT COUNT(*) INTO n FROM sys_menu WHERE menu_id = export_id AND parent_id = page_id AND menu_type = 'F';
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '现有应收毛利导出权限与预期不符'; END IF;
END IF;
SELECT MAX(menu_id) INTO commission_id FROM sys_menu WHERE perms = 'report:arProfit:commission';
IF commission_id IS NOT NULL THEN
SELECT COUNT(*) INTO n FROM sys_menu WHERE menu_id = commission_id AND parent_id = page_id AND menu_type = 'F';
IF n <> 1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '现有应收毛利提成权限与预期不符'; END IF;
END IF;
START TRANSACTION;
-- 只读检查:不能关联客户、区域为空或销售员无效的历史账单。
SELECT b.ar_bill_id, b.bill_no, b.customer_id, c.customer_area, c.sales_user_id
FROM ar_bill b LEFT JOIN ctr_customer c ON c.customer_id = b.customer_id
LEFT JOIN sys_user u ON CONVERT(CAST(u.user_id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci = c.sales_user_id AND u.del_flag = '0'
WHERE (b.profit_customer_area IS NULL AND (c.customer_area IS NULL OR TRIM(c.customer_area) = ''))
OR (b.profit_sales_user_id IS NULL AND u.user_id IS NULL);
-- 检查来源订单销售员与当前客户负责人不一致的账单;下方不自动回填这些销售归属。
SELECT DISTINCT b.ar_bill_id, b.bill_no, p.belong_saler_code AS order_saler_code,
u.user_id AS customer_sales_user_id, u.user_name AS customer_sales_code
FROM ar_bill b
JOIN ctr_customer c ON c.customer_id = b.customer_id
JOIN sys_user u ON CONVERT(CAST(u.user_id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci = c.sales_user_id AND u.del_flag = '0'
JOIN ar_bill_detail d ON d.ar_bill_id = b.ar_bill_id
JOIN prc_order_bill p ON p.bill_id = d.prc_order_bill_id
WHERE b.profit_sales_user_id IS NULL AND (b.profit_snapshot_source IS NULL OR b.profit_snapshot_source = 'BACKFILLED')
AND p.belong_saler_code IS NOT NULL
AND TRIM(p.belong_saler_code) <> ''
AND TRIM(p.belong_saler_code) <> u.user_name COLLATE utf8mb4_unicode_ci
AND TRIM(p.belong_saler_code) <> CONVERT(CAST(u.user_id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci;
-- 此处仅补空值。客户区域来自客户当前资料,并非出账时的历史事实。
UPDATE ar_bill b JOIN ctr_customer c ON c.customer_id = b.customer_id
SET b.profit_customer_area = c.customer_area
WHERE b.profit_customer_area IS NULL AND (b.profit_snapshot_source IS NULL OR b.profit_snapshot_source = 'BACKFILLED')
AND c.customer_area IS NOT NULL AND TRIM(c.customer_area) <> '';
UPDATE ar_bill b
JOIN ctr_customer c ON c.customer_id = b.customer_id
JOIN sys_user u ON CONVERT(CAST(u.user_id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci = c.sales_user_id AND u.del_flag = '0'
SET b.profit_sales_user_id = u.user_id,
b.profit_sales_user_code = u.user_name,
b.profit_sales_user_name = u.nick_name
WHERE b.profit_sales_user_id IS NULL AND (b.profit_snapshot_source IS NULL OR b.profit_snapshot_source = 'BACKFILLED')
AND NOT EXISTS (
SELECT 1 FROM ar_bill_detail d JOIN prc_order_bill p ON p.bill_id = d.prc_order_bill_id
WHERE d.ar_bill_id = b.ar_bill_id AND p.belong_saler_code IS NOT NULL
AND TRIM(p.belong_saler_code) <> ''
AND TRIM(p.belong_saler_code) <> u.user_name COLLATE utf8mb4_unicode_ci
AND TRIM(p.belong_saler_code) <> CONVERT(CAST(u.user_id AS CHAR) USING utf8mb4) COLLATE utf8mb4_unicode_ci
);
UPDATE ar_bill SET profit_snapshot_source = 'BACKFILLED'
WHERE profit_snapshot_source IS NULL AND (profit_customer_area IS NOT NULL OR profit_sales_user_id IS NOT NULL);
-- 历史核销比例不可追溯,不能使用当前比例替代。
INSERT INTO ar_profit_writeoff_rate (writeoff_id, sales_user_id, rate_id, rate, create_time)
SELECT w.writeoff_id, b.profit_sales_user_id, NULL, NULL, NOW()
FROM ar_balance_writeoff w JOIN ar_bill b ON b.ar_bill_id = w.ar_bill_id
LEFT JOIN ar_profit_writeoff_rate s ON s.writeoff_id = w.writeoff_id
WHERE s.writeoff_id IS NULL;
IF report_id IS NULL THEN
INSERT INTO sys_menu (menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
VALUES ('报表中心',0,8,'report',NULL,1,0,'M','0','0','','chart','admin',NOW());
SET report_id = LAST_INSERT_ID();
END IF;
IF page_id IS NULL THEN
INSERT INTO sys_menu (menu_name,parent_id,order_num,path,component,route_name,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
VALUES ('应收账单毛利分析',report_id,2,'arProfit','report/arProfit/index','ArProfitReport',1,0,'C','0','0','report:arProfit:list','chart','admin',NOW());
SET page_id = LAST_INSERT_ID();
END IF;
IF export_id IS NULL THEN
INSERT INTO sys_menu (menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
VALUES ('导出',page_id,1,'',NULL,1,0,'F','0','0','report:arProfit:export','#','admin',NOW());
SET export_id = LAST_INSERT_ID();
END IF;
IF commission_id IS NULL THEN
INSERT INTO sys_menu (menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
VALUES ('提成管理',page_id,2,'',NULL,1,0,'F','0','0','report:arProfit:commission','#','admin',NOW());
SET commission_id = LAST_INSERT_ID();
END IF;
INSERT INTO sys_role_menu (role_id,menu_id)
SELECT r.role_id, m.menu_id FROM sys_role r JOIN sys_menu m ON m.menu_id IN (report_id,page_id,export_id)
WHERE r.del_flag = '0' AND r.status = '0' AND (r.role_id = 1 OR r.role_key IN ('ORA_6040','ORA_6041','ORA_6042','ORA_6043'))
AND NOT EXISTS (SELECT 1 FROM sys_role_menu rm WHERE rm.role_id = r.role_id AND rm.menu_id = m.menu_id);
INSERT INTO sys_role_menu (role_id,menu_id)
SELECT r.role_id, commission_id FROM sys_role r
WHERE r.del_flag = '0' AND r.status = '0' AND (r.role_id = 1 OR r.role_key IN ('ORA_6042','ORA_6043'))
AND NOT EXISTS (SELECT 1 FROM sys_role_menu rm WHERE rm.role_id = r.role_id AND rm.menu_id = commission_id);
COMMIT;
SELECT 'AR_PROFIT_UPGRADE_COMPLETED' AS upgrade_status,
(SELECT COUNT(*) FROM ar_bill WHERE profit_customer_area IS NULL) AS missing_area,
(SELECT COUNT(*) FROM ar_bill WHERE profit_sales_user_id IS NULL) AS missing_sales,
(SELECT COUNT(*) FROM ar_bill WHERE generation_status IS NULL AND status IN ('CONFIRMED','PARTIAL_WRITTEN_OFF','WRITTEN_OFF')) AS unknown_generation_status,
(SELECT COUNT(*) FROM ar_profit_writeoff_rate r JOIN ar_balance_writeoff w ON w.writeoff_id = r.writeoff_id
JOIN ar_bill b ON b.ar_bill_id = w.ar_bill_id
WHERE (r.rate IS NULL OR r.rate < 0 OR r.rate > 100) AND w.status = 'EFFECTIVE' AND b.generation_status = 'READY' AND b.status IN ('CONFIRMED','PARTIAL_WRITTEN_OFF','WRITTEN_OFF')) AS missing_writeoff_rates,
(SELECT COUNT(*) FROM ar_bill b WHERE b.status = 'WRITTEN_OFF' AND NOT EXISTS
(SELECT 1 FROM ar_balance_writeoff w WHERE w.ar_bill_id = b.ar_bill_id AND w.status = 'EFFECTIVE')) AS paid_bills_without_writeoffs;
END$$
DELIMITER ;
CALL bms_ar_profit_upgrade_20261105_v1();
DROP PROCEDURE IF EXISTS bms_ar_profit_upgrade_20261105_v1;
+63 -17
View File
@@ -1,29 +1,75 @@
-- Exclusive quote module menus
SET NAMES utf8mb4;
-- Top-level directory
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, route_name, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT 2600, N'专属报价', 0, 55, 'exclusive', NULL, '', '', 1, 0, 'M', '0', '0', '', 'money', 'admin', sysdate(), N'老板客户专属报价'
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2600 OR (path = 'exclusive' AND parent_id = 0 AND menu_type = 'M'));
-- Exclusive package menus under package management (套餐管理).
-- Idempotent: create if missing, rename/reparent if already present, drop obsolete top directory 专属报价.
SET @exParentId := (SELECT menu_id FROM sys_menu WHERE menu_id = 2600 LIMIT 1);
SET @exParentId := IFNULL(@exParentId, (
SELECT menu_id FROM sys_menu WHERE path = 'exclusive' AND menu_type = 'M' AND parent_id = 0 ORDER BY menu_id ASC LIMIT 1
));
SET @pkgParentId := (
SELECT menu_id FROM sys_menu
WHERE menu_id = 2200
OR (menu_name = N'套餐管理' AND parent_id = 0 AND menu_type = 'M')
ORDER BY CASE WHEN menu_id = 2200 THEN 0 ELSE 1 END, menu_id
LIMIT 1
);
-- List page
-- Drop obsolete top-level directory (and role links)
DELETE FROM sys_role_menu WHERE menu_id = 2600;
DELETE FROM sys_menu
WHERE menu_id = 2600
OR (path = 'exclusive' AND parent_id = 0 AND menu_type = 'M' AND menu_name = N'专属报价');
-- List: 专属套餐
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, route_name, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT 2601, N'报价列表', @exParentId, 1, 'quote', 'price/exclusive/exclusiveQuote', '', 'ExclusiveQuote', 1, 0, 'C', '0', '0', 'price:exclusive:list', 'list', 'admin', sysdate(), N'专属报价列表'
FROM DUAL WHERE @exParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2601 OR perms = 'price:exclusive:list');
SELECT 2601, N'专属套餐', @pkgParentId, 2, 'quote', 'price/exclusive/exclusiveQuote', '', 'ExclusiveQuote', 1, 0, 'C', '0', '0', 'price:exclusive:list', 'list', 'admin', sysdate(), N'专属套餐列表'
FROM DUAL WHERE @pkgParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2601 OR perms = 'price:exclusive:list');
UPDATE sys_menu
SET menu_name = N'专属套餐',
parent_id = @pkgParentId,
order_num = 2,
path = 'quote',
component = 'price/exclusive/exclusiveQuote',
route_name = 'ExclusiveQuote',
remark = N'专属套餐列表',
update_by = 'admin',
update_time = sysdate()
WHERE @pkgParentId IS NOT NULL AND (menu_id = 2601 OR perms = 'price:exclusive:list');
-- Hidden create / detail
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, route_name, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT 2609, N'报价新建', @exParentId, 2, 'quoteCreate', 'price/exclusive/create', '', 'ExclusiveQuoteCreate', 1, 0, 'C', '1', '0', 'price:exclusive:add', '#', 'admin', sysdate(), N'专属报价新建/编辑'
FROM DUAL WHERE @exParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2609 OR path = 'quoteCreate');
SELECT 2609, N'专属套餐新建', @pkgParentId, 5, 'quoteCreate', 'price/exclusive/create', '', 'ExclusiveQuoteCreate', 1, 0, 'C', '1', '0', 'price:exclusive:add', '#', 'admin', sysdate(), N'专属套餐新建/编辑'
FROM DUAL WHERE @pkgParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2609 OR path = 'quoteCreate');
UPDATE sys_menu
SET menu_name = N'专属套餐新建',
parent_id = @pkgParentId,
order_num = 5,
path = 'quoteCreate',
component = 'price/exclusive/create',
route_name = 'ExclusiveQuoteCreate',
remark = N'专属套餐新建/编辑',
update_by = 'admin',
update_time = sysdate()
WHERE @pkgParentId IS NOT NULL AND (menu_id = 2609 OR path = 'quoteCreate');
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, query, route_name, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
SELECT 2610, N'报价详情', @exParentId, 3, 'quoteDetail', 'price/exclusive/detail', '', 'ExclusiveQuoteDetail', 1, 0, 'C', '1', '0', 'price:exclusive:query', '#', 'admin', sysdate(), N'专属报价详情'
FROM DUAL WHERE @exParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2610 OR path = 'quoteDetail');
SELECT 2610, N'专属套餐详情', @pkgParentId, 6, 'quoteDetail', 'price/exclusive/detail', '', 'ExclusiveQuoteDetail', 1, 0, 'C', '1', '0', 'price:exclusive:query', '#', 'admin', sysdate(), N'专属套餐详情'
FROM DUAL WHERE @pkgParentId IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2610 OR path = 'quoteDetail');
UPDATE sys_menu
SET menu_name = N'专属套餐详情',
parent_id = @pkgParentId,
order_num = 6,
path = 'quoteDetail',
component = 'price/exclusive/detail',
route_name = 'ExclusiveQuoteDetail',
remark = N'专属套餐详情',
update_by = 'admin',
update_time = sysdate()
WHERE @pkgParentId IS NOT NULL AND (menu_id = 2610 OR path = 'quoteDetail');
-- Keep ordinary set create/detail order after list pages
UPDATE sys_menu SET order_num = 3, update_by = 'admin', update_time = sysdate() WHERE menu_id = 2208;
UPDATE sys_menu SET order_num = 4, update_by = 'admin', update_time = sysdate() WHERE menu_id = 2209;
-- Buttons under list
INSERT INTO sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, remark)
@@ -52,7 +98,7 @@ FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM sys_menu WHERE menu_id = 2607 OR (pare
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT 1, m.menu_id FROM (
SELECT 2600 AS menu_id UNION SELECT 2601 UNION SELECT 2602 UNION SELECT 2603
SELECT 2601 AS menu_id UNION SELECT 2602 UNION SELECT 2603
UNION SELECT 2604 UNION SELECT 2605 UNION SELECT 2606 UNION SELECT 2607
UNION SELECT 2609 UNION SELECT 2610
) m
@@ -0,0 +1,41 @@
-- 偏远附加费按重量区间和邮编命中。已有库可重复执行。
SET NAMES utf8mb4;
SET @sql = (
SELECT IF(
COUNT(*) = 0,
'ALTER TABLE pay_surcharge ADD COLUMN weight_min decimal(12,3) DEFAULT NULL COMMENT ''适用重量下限KG,空表示不限'' AFTER calc_param',
'SELECT 1'
)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pay_surcharge' AND COLUMN_NAME = 'weight_min'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = (
SELECT IF(
COUNT(*) = 0,
'ALTER TABLE pay_surcharge ADD COLUMN weight_max decimal(12,3) DEFAULT NULL COMMENT ''适用重量上限KG,空表示不限'' AFTER weight_min',
'SELECT 1'
)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pay_surcharge' AND COLUMN_NAME = 'weight_max'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @sql = (
SELECT IF(
COUNT(*) = 0,
'ALTER TABLE pay_surcharge ADD COLUMN postcode_param varchar(1000) DEFAULT NULL COMMENT ''偏远邮编规则,如07,35或IV,KA27-28'' AFTER weight_max',
'SELECT 1'
)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'pay_surcharge' AND COLUMN_NAME = 'postcode_param'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
+15
View File
@@ -0,0 +1,15 @@
import request from '@/utils/request'
export const listArProfitBills = params => request({ url: '/report/ar-profit/bills', method: 'get', params })
export const listArProfitBillDetails = (billId, params) => request({ url: `/report/ar-profit/bills/${billId}/details`, method: 'get', params })
export const listArProfitSummary = params => request({ url: '/report/ar-profit/summary', method: 'get', params })
export const listArProfitSalesOptions = params => request({ url: '/report/ar-profit/sales-options', method: 'get', params })
export const listArProfitAreaRules = () => request({ url: '/report/ar-profit/area-rules', method: 'get' })
export const listArProfitFees = detailId => request({ url: `/report/ar-profit/orders/${detailId}/fees`, method: 'get' })
export const listArProfitRates = () => request({ url: '/report/ar-profit/rates', method: 'get' })
export const addArProfitRate = data => request({ url: '/report/ar-profit/rates', method: 'post', data })
export const listArProfitMissingRates = params => request({ url: '/report/ar-profit/writeoffs/missing-rates', method: 'get', params })
export const confirmArProfitMissingRate = data => request({ url: '/report/ar-profit/writeoffs/confirm-rate', method: 'post', data })
export const listArProfitCommissions = params => request({ url: '/report/ar-profit/commissions', method: 'get', params })
export const listArProfitCommissionSummary = params => request({ url: '/report/ar-profit/commissions/summary', method: 'get', params })
export const listArProfitWriteoffRates = billId => request({ url: `/report/ar-profit/commissions/${billId}/writeoffs`, method: 'get' })
@@ -73,8 +73,8 @@
<el-table-column :prop="dateColumnProp" :label="dateColumnLabel" width="170" :formatter="formatDateColumn" />
<el-table-column prop="productName" label="产品" min-width="140" show-overflow-tooltip />
<el-table-column prop="countryName" label="国家/地区" min-width="110" show-overflow-tooltip />
<el-table-column prop="actualWeight" label="实际重(kg)" width="105" align="right" :formatter="formatNumberColumn" />
<el-table-column prop="chargeWeight" label="计费重(kg)" width="105" align="right" :formatter="formatNumberColumn" />
<el-table-column prop="actualWeight" label="实际重(kg)" width="105" align="right" :formatter="formatWeightColumn" />
<el-table-column prop="chargeWeight" label="计费重(kg)" width="105" align="right" :formatter="formatWeightColumn" />
<el-table-column prop="incomeTotal" label="应收金额" width="110" align="right" :formatter="formatNumberColumn" />
<el-table-column prop="currency" label="币种" width="75" />
</el-table>
@@ -541,6 +541,7 @@ function date(value) {
}
function money(value) { const num = Number(value); return Number.isNaN(num) ? '-' : num.toFixed(2) }
function formatDateColumn(_, __, value) { return date(value) }
function formatWeightColumn(_, __, value) { return value == null || value === '' ? '-' : value }
function formatNumberColumn(_, __, value) { return Number(value || 0).toFixed(2) }
function createRequestId() { return globalThis.crypto?.randomUUID?.() || `ar-${Date.now()}-${Math.random().toString(16).slice(2)}` }
</script>
@@ -117,8 +117,11 @@
<span v-else>{{ calcRuleLabel(row.calcRule) }}</span>
</template>
</el-table-column>
<el-table-column prop="calcParam" label="条件参数" min-width="180" show-overflow-tooltip>
<template #default="{ row }"><cell-text v-model="row.calcParam" :edit="editable" /></template>
<el-table-column prop="calcParam" label="条件参数" min-width="220" show-overflow-tooltip>
<template #default="{ row }">
<div>{{ feeCondition(row) }}</div>
<cell-text v-if="editable" v-model="row.calcParam" :edit="editable" />
</template>
</el-table-column>
<el-table-column v-if="editable" label="操作" width="70" align="center">
<template #default="{ row }">
@@ -195,6 +198,8 @@ const CellText = {
const calcRules = [
{ value: 'ALWAYS', label: '每票都收' },
{ value: 'POSTCODE', label: '命中邮编' },
{ value: 'ZONE', label: '命中分区' },
{ value: 'EXTRA_KG', label: '超重续收' },
{ value: 'WEIGHT', label: '超重' },
{ value: 'SIZE', label: '超尺寸' },
{ value: 'RETURN', label: '退件' },
@@ -205,6 +210,22 @@ function calcRuleLabel(value) {
return calcRules.find(item => item.value === value)?.label || '人工确认'
}
function feeCondition(row) {
const parts = []
const hasMin = row.weightMin != null && row.weightMin !== ''
const hasMax = row.weightMax != null && row.weightMax !== ''
if (hasMin || hasMax) {
parts.push(`${hasMin ? row.weightMin : ''}-${hasMax ? row.weightMax : ''}kg`)
}
if (row.postcodeParam) {
parts.push(`邮编 ${row.postcodeParam}`)
}
if (row.calcParam && row.calcParam !== row.postcodeParam) {
parts.push(String(row.calcParam))
}
return parts.join(';') || '-'
}
const pageSize = 20
const panes = ref([])
@@ -229,7 +250,7 @@ function filteredBands(pane) {
}
function filteredFees(pane) {
return filterRows(pane.item.surcharges || [], pane.feeKeyword, ['feeName', 'zoneName', 'chargeText', 'amount', 'currency', 'priceUnit', 'feeDesc', 'calcRule', 'calcParam'])
return filterRows(pane.item.surcharges || [], pane.feeKeyword, ['feeName', 'zoneName', 'chargeText', 'amount', 'currency', 'priceUnit', 'feeDesc', 'calcRule', 'calcParam', 'postcodeParam'])
}
function addBand(pane) {
+14 -16
View File
@@ -182,7 +182,6 @@
<template #col-action="{ row }">
<el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
<el-button link type="primary" icon="Money" v-hasPermi="['price:billing:bill']" @click="handlePayBill(row)">生成应付</el-button>
<el-button
<!-- <el-button
link
type="primary"
@@ -579,8 +578,7 @@ const columns = [
{ label: '销售员', prop: 'belongSaler', minWidth: 100, showOverflowTooltip: true },
{ label: '结算员', prop: 'settlementMan', minWidth: 100, showOverflowTooltip: true },
{ label: '客服员', prop: 'serviceMan', minWidth: 100, showOverflowTooltip: true },
{ label: '操作', prop: 'action', align: 'center', width: 320, fixed: 'right', slot: 'action', showInToolbar: false, showOverflowTooltip: false }
{ label: '操作', prop: 'action', align: 'center', width: 150, fixed: 'right', slot: 'action', showInToolbar: false, showOverflowTooltip: false }
{ label: '操作', prop: 'action', align: 'center', width: 260, fixed: 'right', slot: 'action', showInToolbar: false, showOverflowTooltip: false }
]
const arrearsStatusOptions = [
@@ -626,19 +624,6 @@ const searchColumns = [
collapseTagsTooltip: true
}
},
{
label: '\u8ba1\u8d39\u5931\u8d25',
prop: 'billingFailStatuses',
component: 'select',
options: billingFailStatusOptions,
placeholder: '\u8bf7\u9009\u62e9',
props: {
multiple: true,
clearable: true,
collapseTags: true,
collapseTagsTooltip: true
}
},
{
label: '计费时间',
prop: 'bizDateRange',
@@ -659,6 +644,19 @@ const searchColumns = [
clearable: true,
defaultTime: [new Date(2000, 0, 1, 0, 0, 0), new Date(2000, 0, 1, 23, 59, 59)]
}
},
{
label: '\u8ba1\u8d39\u5931\u8d25',
prop: 'billingFailStatuses',
component: 'select',
options: billingFailStatusOptions,
placeholder: '\u8bf7\u9009\u62e9',
props: {
multiple: true,
clearable: true,
collapseTags: true,
collapseTagsTooltip: true
}
}
]
@@ -212,7 +212,6 @@ import { deleteIncomeBillFee, getBill } from '@/api/price/billing'
import { generatePayBill } from '@/api/price/pay'
import { ElMessage, ElMessageBox } from 'element-plus'
import BillBillingHistoryDrawer from './BillBillingHistoryDrawer.vue'
import { deleteIncomeBillFee } from '@/api/price/billing'
const { proxy } = getCurrentInstance()
@@ -448,8 +448,8 @@ function onCreateVersion() {
function onRemoveVersion(row) {
if (!row || row.psvId == null) return
const msg = isEffectVersion(row)
? "确认软删除已生效版本(生效时间:" + (row.effectiveTime || '未设置') + ")?版本及产品、明细将标记为已删除,上一版将自动恢复生效并清空失效时间。"
: "确认删除" + (isPendingVersion(row) ? "待生效" : "草稿") + "版本(生效时间:" + (row.effectiveTime || '未设置') + ")?其明细与附加费将一并删除。"
? "确认删除该版本(生效时间:" + (row.effectiveTime || '未设置') + ")?若订单已引用该版本则仅软删版本记录;若无订单引用则整版本硬删。产品与明细均会物理删除,且上一版将自动恢复生效。"
: "确认删除" + (isPendingVersion(row) ? "待生效" : "草稿") + "版本(生效时间:" + (row.effectiveTime || '未设置') + ")?若订单已引用该版本则仅软删版本记录;若无订单引用则整版本硬删。产品与明细均会物理删除。"
proxy.$modal.confirm(msg).then(() => {
removingPsvId.value = row.psvId
proxy.$modal.loading("正在删除,请稍候...")
@@ -36,23 +36,23 @@ export function createExclusiveModule(api) {
exclusiveQuote: true,
onlyImportFresh: true,
routes: Object.freeze({
list: '/exclusive/quote',
create: '/exclusive/quoteCreate',
detail: '/exclusive/quoteDetail'
list: '/customer/quote',
create: '/customer/quoteCreate',
detail: '/customer/quoteDetail'
}),
labels: Object.freeze({
entity: '专属报价',
entityCode: '报价编码',
entityName: '报价名称',
createButton: '新建报价',
saveProgressTitle: '正在保存专属报价',
savedSuccess: '专属报价已保存',
noActiveVersion: '该专属报价暂无生效版本',
disableConfirm: '停用后该专属报价不再参与计费命中,确认停用【{name}】?',
enableConfirm: '启用后该专属报价将重新参与计费命中,确认启用【{name}】?',
basicEditTitle: '修改专属报价基本信息',
keywordPlaceholder: '报价编码 / 名称',
detailTitleFallback: '专属报价详情'
entity: '专属套餐',
entityCode: '套餐编码',
entityName: '套餐名称',
createButton: '新建专属套餐',
saveProgressTitle: '正在保存专属套餐',
savedSuccess: '专属套餐已保存',
noActiveVersion: '该专属套餐暂无生效版本',
disableConfirm: '停用后该专属套餐不再参与计费命中,确认停用【{name}】?',
enableConfirm: '启用后该专属套餐将重新参与计费命中,确认启用【{name}】?',
basicEditTitle: '修改专属套餐基本信息',
keywordPlaceholder: '套餐编码 / 名称',
detailTitleFallback: '专属套餐详情'
})
})
}
+2 -2
View File
@@ -465,8 +465,8 @@ function onCreateVersion() {
function onRemoveVersion(row) {
if (!row || row.psvId == null) return
const msg = isEffectVersion(row)
? "确认软删除已生效版本(生效时间:" + (row.effectiveTime || '未设置') + ")?版本及产品、明细将标记为已删除,上一版将自动恢复生效并清空失效时间。"
: "确认删除" + (isPendingVersion(row) ? "待生效" : "草稿") + "版本(生效时间:" + (row.effectiveTime || '未设置') + ")?其明细与附加费将一并删除。"
? "确认删除该版本(生效时间:" + (row.effectiveTime || '未设置') + ")?若订单已引用该版本则仅软删版本记录;若无订单引用则整版本硬删。产品与明细均会物理删除,且上一版将自动恢复生效。"
: "确认删除" + (isPendingVersion(row) ? "待生效" : "草稿") + "版本(生效时间:" + (row.effectiveTime || '未设置') + ")?若订单已引用该版本则仅软删版本记录;若无订单引用则整版本硬删。产品与明细均会物理删除。"
proxy.$modal.confirm(msg).then(() => {
removingPsvId.value = row.psvId
proxy.$modal.loading("正在删除,请稍候...")
@@ -0,0 +1,283 @@
<template>
<div class="app-container ar-profit-report">
<el-card shadow="never">
<el-form :model="query" inline @submit.prevent>
<el-form-item label="账单日期">
<el-date-picker v-model="dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
</el-form-item>
<el-form-item label="客户">
<customer-select v-model="query.customerId" :fetch-options="listArBillCustomerOptions"
placeholder="请输入客户名称或代码搜索" :remote-search="true" :page-size="20" />
</el-form-item>
<el-form-item label="销售员">
<el-select v-model="query.salesUserId" placeholder="姓名或工号搜索" clearable filterable remote
:remote-method="searchSales" :loading="salesLoading" style="width: 180px"
@input="handleSalesInput">
<el-option v-for="person in salesOptions" :key="person.userId" :label="person.name || person.code || String(person.userId)" :value="person.userId">
<span>{{ person.name || person.code || person.userId }}</span>
<span v-if="person.code" class="sales-code">{{ person.code }}</span>
</el-option>
</el-select>
</el-form-item>
<el-form-item label="账单号"><el-input v-model="query.billNo" clearable @keyup.enter="search" /></el-form-item>
<el-form-item label="订单号"><el-input v-model="query.orderNo" clearable @keyup.enter="search" /></el-form-item>
<el-form-item label="状态">
<el-select v-model="query.status" placeholder="全部状态" clearable style="width: 140px">
<el-option label="已确认" value="CONFIRMED" /><el-option label="部分核销" value="PARTIAL_WRITTEN_OFF" /><el-option label="已核销" value="WRITTEN_OFF" />
</el-select>
</el-form-item>
<el-form-item><el-button type="primary" icon="Search" @click="search">搜索</el-button><el-button icon="Refresh" @click="reset">重置</el-button></el-form-item>
</el-form>
</el-card>
<el-card v-for="summary in summaryCards" :key="summary.currency || 'empty'" shadow="never" class="summary-card">
<template #header>{{ summary.currency ? summary.currency + ' 汇总' : '汇总' }}</template>
<div class="metrics">
<div>账单数 <b>{{ summary.billCount ?? '-' }}</b></div>
<div>销售价 <b>{{ money(summary.salesAmount) }}</b></div><div>产品价 <b>{{ money(summary.productAmount) }}</b></div>
<div>销售毛利 <b>{{ money(summary.salesGrossProfit) }}</b></div>
<div>销售毛利率 <b>{{ rate(summary.salesGrossMarginRate) }}</b></div>
<div>账单已核销 <b>{{ money(summary.writtenOffAmount) }}</b></div><div>账单未核销 <b>{{ money(summary.unwrittenAmount) }}</b></div>
<div>毛利待核对账单 <b>{{ summary.invalidBillCount ?? '-' }}</b></div>
</div>
<div class="summary-note">广州产品价按红线价展示,深圳产品价按产品价展示;待核对账单不计入产品价、毛利及毛利率汇总。</div>
<div v-if="query.orderNo" class="summary-note">订单号用于查找账单,金额按完整账单统计。</div>
</el-card>
<el-card shadow="never" class="data-card">
<div class="heading">
<span class="table-title">账单列表</span>
<div>
<el-button v-hasPermi="['report:arProfit:export']" icon="Download" @click="exportRows">导出账单</el-button>
<el-button v-hasPermi="['report:arProfit:commission']" @click="openCommission()">提成管理</el-button>
</div>
</div>
<el-table v-loading="loading" :data="rows" border stripe>
<el-table-column prop="billNo" label="账单号" min-width="170" show-overflow-tooltip />
<el-table-column prop="billDate" label="账单日期" width="115" />
<el-table-column prop="customerCode" label="客户代码" width="110" />
<el-table-column prop="customerName" label="客户名称" min-width="160" show-overflow-tooltip />
<el-table-column prop="salesUserName" label="销售员" width="110" />
<el-table-column label="归属来源" width="110"><template #default="{ row }">{{ row.snapshotSource === 'NEW' ? '生成时快照' : row.snapshotSource === 'BACKFILLED' ? '历史补录' : '-' }}</template></el-table-column>
<el-table-column prop="currency" label="币种" width="80" />
<el-table-column label="销售价" min-width="110" align="right"><template #default="{ row }">{{ money(row.salesAmount) }}</template></el-table-column>
<el-table-column label="产品价" min-width="110" align="right"><template #default="{ row }">{{ money(row.productAmount) }}</template></el-table-column>
<el-table-column label="销售毛利" min-width="110" align="right"><template #default="{ row }">{{ money(row.salesGrossProfit) }}</template></el-table-column>
<el-table-column label="销售毛利率" width="110" align="right"><template #default="{ row }">{{ rate(row.salesGrossMarginRate) }}</template></el-table-column>
<el-table-column label="已核销" min-width="110" align="right"><template #default="{ row }">{{ money(row.writtenOffAmount) }}</template></el-table-column>
<el-table-column label="未核销" min-width="110" align="right"><template #default="{ row }">{{ money(row.unwrittenAmount) }}</template></el-table-column>
<el-table-column label="状态" width="110"><template #default="{ row }">{{ statusLabel(row.status) }}</template></el-table-column>
<el-table-column label="操作" width="220" fixed="right"><template #default="{ row }"><el-button link type="primary" @click="openBillDetails(row)">账单明细</el-button><el-button v-hasPermi="['report:arProfit:commission']" link type="primary" @click="openBillCommission(row)">查看提成</el-button><el-button v-hasPermi="['report:arProfit:commission']" link type="primary" @click="openWriteoffRates(row)">核销比例</el-button></template></el-table-column>
</el-table>
<pagination v-show="total > 0" v-model:page="pageNum" v-model:limit="pageSize" :total="total" @pagination="loadRows" />
</el-card>
<el-dialog v-model="detailsVisible" :title="'账单明细:' + detailBillNo" width="900px" append-to-body>
<el-table :data="details" border v-loading="detailsLoading">
<el-table-column prop="orderNo" label="订单号" min-width="160" />
<el-table-column prop="productName" label="产品名称" min-width="150" />
<el-table-column prop="currency" label="币种" width="80" />
<el-table-column label="销售价" align="right"><template #default="{ row }">{{ money(row.totalAmount) }}</template></el-table-column>
<el-table-column label="操作" width="100"><template #default="{ row }"><el-button link type="primary" @click="openFees(row)">费用明细</el-button></template></el-table-column>
</el-table>
<pagination v-show="detailsTotal > 0" v-model:page="detailsPage" v-model:limit="detailsSize" :total="detailsTotal" @pagination="loadBillDetails" />
</el-dialog>
<el-dialog v-model="feeVisible" title="本次出账费用明细" width="800px" append-to-body>
<el-table :data="fees" border v-loading="feeLoading">
<el-table-column prop="feeName" label="费用名称" min-width="140" /><el-table-column prop="currency" label="币种" width="80" />
<el-table-column label="销售价" align="right"><template #default="{ row }">{{ money(row.amount) }}</template></el-table-column>
<el-table-column label="产品价" align="right"><template #default="{ row }">{{ money(feeProductAmount(row)) }}</template></el-table-column>
</el-table>
</el-dialog>
<el-dialog v-model="commissionVisible" title="提成管理" width="1100px" append-to-body>
<el-tabs v-model="commissionTab" @tab-change="loadCommissionTab">
<el-tab-pane label="正式提成" name="results">
<el-alert v-if="commissionBillId" :title="'当前查看账单:' + commissionBillNo" type="info" :closable="false" show-icon>
<el-button link type="primary" @click="clearCommissionBill">查看全部账单</el-button>
</el-alert>
<div v-if="commissionBillId" class="summary-note">账单全部核销后生成正式提成;存在待处理明细时不展示整单提成合计。</div>
<el-button icon="Download" style="margin-bottom: 12px" @click="exportCommissions">导出提成明细</el-button>
<el-checkbox v-model="includeReversed" style="margin: 0 0 12px 12px" @change="loadCommissionTab">显示已冲回记录</el-checkbox>
<el-table :data="commissionSummary" border size="small" style="margin-bottom: 16px">
<el-table-column prop="salesUserName" label="销售员" /><el-table-column prop="currency" label="币种" width="80" />
<el-table-column prop="orderCount" label="订单明细数" /><el-table-column prop="pendingCount" label="待处理订单数" />
<el-table-column label="正式提成合计" align="right"><template #default="{ row }">{{ money(row.commissionAmount) }}</template></el-table-column>
</el-table>
<el-table :data="results" border size="small" v-loading="commissionLoading">
<el-table-column prop="billNo" label="账单号" min-width="160" /><el-table-column prop="orderNo" label="订单号" min-width="150" />
<el-table-column prop="salesUserName" label="销售员" width="110" /><el-table-column prop="currency" label="币种" width="75" />
<el-table-column label="销售毛利" width="110" align="right"><template #default="{ row }">{{ money(row.grossProfit) }}</template></el-table-column>
<el-table-column label="正式提成" width="110" align="right"><template #default="{ row }">{{ money(row.commissionAmount) }}</template></el-table-column>
<el-table-column label="状态" min-width="120"><template #default="{ row }">{{ resultLabel(row.resultStatus) }}</template></el-table-column>
<el-table-column v-if="includeReversed" prop="reversedBy" label="冲回人" width="110" />
<el-table-column v-if="includeReversed" label="冲回时间" width="170"><template #default="{ row }">{{ row.reversedTime ? parseTime(row.reversedTime) : '-' }}</template></el-table-column>
<el-table-column label="依据" width="100"><template #default="{ row }"><el-button link type="primary" @click="openWriteoffRates(row)">核销比例</el-button></template></el-table-column>
</el-table>
<pagination v-show="commissionTotal > 0" v-model:page="commissionPage" v-model:limit="commissionSize" :total="commissionTotal" @pagination="loadCommissionTab" />
</el-tab-pane>
<el-tab-pane label="提成比例" name="rates">
<el-form inline><el-form-item label="销售员"><user-select v-model="rateForm.salesUserId" placeholder="选择销售员" style="width: 200px" /></el-form-item>
<el-form-item label="比例(%)"><el-input-number v-model="rateForm.rate" :min="0" :max="100" :precision="4" /></el-form-item>
<el-form-item><el-button type="primary" @click="saveRate">立即生效</el-button></el-form-item>
</el-form>
<el-table :data="rates" border size="small" height="400" v-loading="commissionLoading">
<el-table-column prop="salesUserName" label="销售员" /><el-table-column prop="salesUserCode" label="销售员编码" />
<el-table-column prop="rate" label="比例(%)" /><el-table-column prop="effectiveAt" label="生效时间" /><el-table-column prop="createBy" label="操作人" />
</el-table>
</el-tab-pane>
<el-tab-pane label="比例待确认" name="missing">
<el-table :data="missingRates" border size="small" v-loading="commissionLoading">
<el-table-column prop="billNo" label="账单号" min-width="150" /><el-table-column prop="customerName" label="客户" min-width="140" />
<el-table-column prop="salesUserName" label="销售员" width="110" /><el-table-column prop="writeoffAmount" label="核销金额" width="110" />
<el-table-column prop="writeoffDate" label="核销日期" width="165"><template #default="{ row }">{{ parseTime(row.writeoffDate, '{y}-{m}-{d}') }}</template></el-table-column>
<el-table-column label="操作" width="140"><template #default="{ row }"><el-button v-if="row.rate === null || row.rate === undefined" link type="primary" @click="openConfirm(row)">确认比例</el-button><span v-else>比例异常,请核对</span></template></el-table-column>
</el-table>
<pagination v-show="missingTotal > 0" v-model:page="missingPage" v-model:limit="missingSize" :total="missingTotal" @pagination="loadCommissionTab" />
</el-tab-pane>
</el-tabs>
</el-dialog>
<el-dialog v-model="confirmVisible" title="确认历史核销比例" width="480px" append-to-body>
<el-form label-width="100px"><el-form-item label="账单号">{{ confirmForm.billNo }}</el-form-item>
<el-form-item label="比例(%)"><el-input-number v-model="confirmForm.rate" :min="0" :max="100" :precision="4" /></el-form-item>
<el-form-item label="核对说明"><el-input v-model="confirmForm.remark" type="textarea" maxlength="500" /></el-form-item>
</el-form>
<template #footer><el-button @click="confirmVisible = false">取消</el-button><el-button type="primary" @click="confirmRate">确认</el-button></template>
</el-dialog>
<el-dialog v-model="writeoffRatesVisible" title="账单核销与提成比例" width="950px" append-to-body>
<el-table :data="writeoffRates" border size="small" v-loading="writeoffRatesLoading">
<el-table-column prop="writeoffDate" label="核销日期" width="130"><template #default="{ row }">{{ parseTime(row.writeoffDate, '{y}-{m}-{d}') }}</template></el-table-column>
<el-table-column prop="writeoffAmount" label="核销金额" width="120" /><el-table-column prop="rate" label="比例(%)" width="110" />
<el-table-column label="状态" width="100"><template #default="{ row }">{{ row.status === 'EFFECTIVE' ? '有效' : '已反核销' }}</template></el-table-column>
<el-table-column prop="confirmedBy" label="补录人" width="110" /><el-table-column prop="remark" label="核对说明" min-width="180" show-overflow-tooltip />
</el-table>
</el-dialog>
</div>
</template>
<script setup name="ArProfitReport">
import { listArBillCustomerOptions } from '@/api/ar/bill'
import { addArProfitRate, confirmArProfitMissingRate, listArProfitAreaRules, listArProfitBillDetails, listArProfitBills, listArProfitCommissions, listArProfitCommissionSummary, listArProfitFees, listArProfitMissingRates, listArProfitRates, listArProfitSalesOptions, listArProfitSummary, listArProfitWriteoffRates } from '@/api/report/arProfit'
import { parseTime } from '@/utils/bms'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
const query = reactive({ customerId: null, salesUserId: null, billNo: '', orderNo: '', status: '' })
const salesOptions = ref([])
const salesLoading = ref(false)
let salesSearchVersion = 0
const areaRules = ref({})
const dateRange = ref([])
const pageNum = ref(1), pageSize = ref(10), total = ref(0), rows = ref([]), loading = ref(false)
const summaries = ref([]), summaryLoaded = ref(false)
const detailsVisible = ref(false), detailsLoading = ref(false), details = ref([]), detailsTotal = ref(0)
const detailBillId = ref(null), detailBillNo = ref(''), detailsPage = ref(1), detailsSize = ref(10)
let detailsVersion = 0
const feeVisible = ref(false), feeLoading = ref(false), feeArea = ref(''), fees = ref([])
const summaryCards = computed(() => !summaryLoaded.value ? [] : summaries.value.length ? summaries.value : [{}])
let requestVersion = 0
let commissionVersion = 0
const commissionVisible = ref(false), commissionTab = ref('results'), commissionLoading = ref(false)
const commissionBillId = ref(null), commissionBillNo = ref('')
const results = ref([]), commissionTotal = ref(0), commissionPage = ref(1), commissionSize = ref(10)
const commissionSummary = ref([])
const includeReversed = ref(false)
const rates = ref([]), rateForm = reactive({ salesUserId: null, rate: null })
const missingRates = ref([]), missingTotal = ref(0), missingPage = ref(1), missingSize = ref(10)
const confirmVisible = ref(false), confirmForm = reactive({ writeoffId: null, billNo: '', rate: null, remark: '' })
const writeoffRatesVisible = ref(false), writeoffRatesLoading = ref(false), writeoffRates = ref([])
function params() { return { ...query, beginBillDate: dateRange.value?.[0], endBillDate: dateRange.value?.[1] } }
function search() { pageNum.value = 1; loadRows(); loadSummary() }
function reset() { Object.assign(query, { customerId: null, salesUserId: null, billNo: '', orderNo: '', status: '' }); dateRange.value = []; search() }
function handleSalesInput() {
salesSearchVersion++
salesOptions.value = []
salesLoading.value = false
}
async function searchSales(keyword) {
const version = ++salesSearchVersion
salesOptions.value = []
salesLoading.value = true
try {
const res = await listArProfitSalesOptions({ keyword: keyword?.trim() || '' })
if (version !== salesSearchVersion) return
salesOptions.value = res.data || []
} finally {
if (version === salesSearchVersion) salesLoading.value = false
}
}
function loadRows() {
const version = ++requestVersion
loading.value = true
rows.value = []
total.value = 0
listArProfitBills({ ...params(), pageNum: pageNum.value, pageSize: pageSize.value }).then(res => {
if (version === requestVersion) { rows.value = res.rows || []; total.value = res.total || 0 }
}).finally(() => { if (version === requestVersion) loading.value = false })
}
let summaryVersion = 0
function loadSummary() {
const version = ++summaryVersion
summaryLoaded.value = false
listArProfitSummary(params()).then(res => { if (version === summaryVersion) { summaries.value = res.data || []; summaryLoaded.value = true } })
}
function openBillDetails(row) { detailBillId.value = row.arBillId; detailBillNo.value = row.billNo; feeArea.value = row.customerArea; detailsPage.value = 1; detailsVisible.value = true; loadBillDetails() }
async function loadBillDetails() {
const version = ++detailsVersion
detailsLoading.value = true
details.value = []
detailsTotal.value = 0
try { const res = await listArProfitBillDetails(detailBillId.value, { pageNum: detailsPage.value, pageSize: detailsSize.value }); if (version === detailsVersion) { details.value = res.rows || []; detailsTotal.value = res.total || 0 } }
finally { if (version === detailsVersion) detailsLoading.value = false }
}
async function openFees(row) { feeVisible.value = true; feeLoading.value = true; fees.value = []; try { fees.value = (await listArProfitFees(row.detailId)).data || [] } finally { feeLoading.value = false } }
function exportRows() { proxy.download('/report/ar-profit/export', params(), `应收账单毛利分析_${Date.now()}.xlsx`) }
function exportCommissions() { proxy.download('/report/ar-profit/commissions/export', { billId: commissionBillId.value }, `应收账单提成明细_${Date.now()}.xlsx`) }
function money(v) { return v === null || v === undefined || v === '' || !Number.isFinite(Number(v)) ? '-' : Number(v).toFixed(2) }
function rate(v) { return v === null || v === undefined || v === '' || !Number.isFinite(Number(v)) ? '-' : Number(v).toFixed(2) + '%' }
function feeProductAmount(row) {
if (areaRules.value[feeArea.value] === 'GUANGZHOU') return row.redlineAmount
if (areaRules.value[feeArea.value] === 'SHENZHEN') return row.productAmount
return null
}
function statusLabel(v) { return ({ CONFIRMED: '已确认', PARTIAL_WRITTEN_OFF: '部分核销', WRITTEN_OFF: '已核销' })[v] || v || '-' }
function resultLabel(v) { return ({ READY: '已计算', MISSING_RATE: '比例待确认', MISSING_PRICE: '价格缺失', MISSING_SNAPSHOT: '归属或区域缺失', WRITEOFF_MISMATCH: '核销金额不一致', REVERSED: '已冲回' })[v] || v || '-' }
function openCommission() { commissionBillId.value = null; commissionBillNo.value = ''; commissionPage.value = 1; commissionVisible.value = true; loadCommissionTab() }
function openBillCommission(row) { commissionBillId.value = row.arBillId; commissionBillNo.value = row.billNo; commissionPage.value = 1; commissionTab.value = 'results'; commissionVisible.value = true; loadCommissionTab() }
function clearCommissionBill() { commissionBillId.value = null; commissionBillNo.value = ''; commissionPage.value = 1; loadCommissionTab() }
async function loadCommissionTab() {
const version = ++commissionVersion
const tab = commissionTab.value
const billId = commissionBillId.value
commissionLoading.value = true
if (tab === 'results') { results.value = []; commissionSummary.value = []; commissionTotal.value = 0 }
try {
if (tab === 'rates') { const r = await listArProfitRates(); if (version === commissionVersion) rates.value = r.data || [] }
else if (tab === 'missing') { const r = await listArProfitMissingRates({ pageNum: missingPage.value, pageSize: missingSize.value }); if (version === commissionVersion) { missingRates.value = r.rows || []; missingTotal.value = r.total || 0 } }
else { const [r, summary] = await Promise.all([listArProfitCommissions({ billId, pageNum: commissionPage.value, pageSize: commissionSize.value, includeReversed: includeReversed.value }), listArProfitCommissionSummary({ billId })]); if (version === commissionVersion) { results.value = r.rows || []; commissionTotal.value = r.total || 0; commissionSummary.value = summary.data || [] } }
} finally { if (version === commissionVersion) commissionLoading.value = false }
}
async function saveRate() {
if (!rateForm.salesUserId || rateForm.rate === null) return ElMessage.warning('请选择销售员并填写提成比例')
await addArProfitRate(rateForm); ElMessage.success('提成比例已保存'); loadCommissionTab()
}
function openConfirm(row) { Object.assign(confirmForm, { writeoffId: row.writeoffId, billNo: row.billNo, rate: null, remark: '' }); confirmVisible.value = true }
async function openWriteoffRates(row) { writeoffRatesVisible.value = true; writeoffRatesLoading.value = true; writeoffRates.value = []; try { writeoffRates.value = (await listArProfitWriteoffRates(row.arBillId)).data || [] } finally { writeoffRatesLoading.value = false } }
async function confirmRate() {
if (confirmForm.rate === null || !confirmForm.remark.trim()) return ElMessage.warning('请填写比例及核对说明')
await confirmArProfitMissingRate(confirmForm); confirmVisible.value = false; ElMessage.success('已确认提成比例'); loadCommissionTab()
}
listArProfitAreaRules().then(res => { areaRules.value = res.data || {} })
search()
</script>
<style scoped>
.summary-card, .data-card { margin-top: 14px; }
.metrics { display: flex; flex-wrap: wrap; gap: 14px; }
.metrics > div { min-width: 150px; padding: 10px; background: var(--el-fill-color-lighter); color: var(--el-text-color-secondary); }
.metrics b { display: block; margin-top: 5px; color: var(--el-text-color-primary); }
.summary-note { margin-top: 10px; color: var(--el-text-color-secondary); font-size: 12px; }
.heading { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
.table-title { font-size: 16px; font-weight: 500; }
.sales-code { float: right; margin-left: 16px; color: var(--el-text-color-secondary); font-size: 12px; }
</style>