13 Commits

62 changed files with 1756 additions and 1187 deletions
@@ -14,7 +14,6 @@ import org.springframework.web.bind.annotation.RestController;
import com.bms.common.core.controller.BaseController;
import com.bms.common.core.domain.AjaxResult;
import com.bms.common.core.page.TableDataInfo;
import com.bms.price.domain.PayOrderFeeBatch;
import com.bms.price.domain.PayOrderFeeLine;
import com.bms.price.domain.PayOrderQuery;
import com.bms.price.domain.PayOrderRecalcCommand;
@@ -113,19 +112,6 @@ public class PayOrderController extends BaseController
return success(payOrderListService.fees(billId));
}
/**
* 给勾选订单批量增加手工费用。创建人取当前登录用户,来源为手工,并记新增日志。
*
* @param batch 订单和费用行
* @return 写入的费用条数
*/
@PreAuthorize("@ss.hasPermi('price:payOrder:feeBatch')")
@PostMapping("/fees/batch")
public AjaxResult addFees(@RequestBody PayOrderFeeBatch batch)
{
return success(payOrderListService.addManualFees(batch));
}
/**
* 在某一段手工增加一行应付费用。创建人取当前登录用户。
*
@@ -167,6 +167,13 @@ public class ArBillController extends BaseController {
return success(account);
}
/** 生成账单时选择同币种启用账户,账号只返回脱敏值。 */
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
@GetMapping("/bank-account-options")
public AjaxResult bankAccountOptions(@RequestParam(defaultValue = "CNY") String currency) {
return success(billService.selectMaskedBankAccounts(currency));
}
/**
* 查询生成账单前的订单计费结果。
*/
@@ -0,0 +1,116 @@
package com.bms.receivable;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.sql.Date;
import java.util.List;
import com.bms.common.core.domain.model.LoginUser;
import com.bms.common.exception.ServiceException;
import com.bms.customer.customerinfo.domain.BmsCustomerOption;
import com.bms.customer.customerinfo.mapper.BmsCustomerMapper;
import com.bms.receivable.domain.ArBankAccount;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.domain.vo.ArBillGenerateRequest;
import com.bms.receivable.mapper.ArBankAccountMapper;
import com.bms.receivable.mapper.ArBillGenerateTaskMapper;
import com.bms.receivable.mapper.ArBillMapper;
import com.bms.receivable.security.ArBillScopeResolver;
import com.bms.receivable.service.IArBillLogService;
import com.bms.receivable.service.impl.ArBillServiceImpl;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
class ArBillGenerateBankAccountTest {
private final ArBillServiceImpl service = new ArBillServiceImpl();
private final ArBillMapper bills = mock(ArBillMapper.class);
private final ArBankAccountMapper accounts = mock(ArBankAccountMapper.class);
private final ArBillGenerateTaskMapper tasks = mock(ArBillGenerateTaskMapper.class);
private final ArBillScopeResolver scope = mock(ArBillScopeResolver.class);
@BeforeEach
void setUp() {
LoginUser login = new LoginUser();
login.setUserId(1L);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login, null, List.of()));
ReflectionTestUtils.setField(service, "billMapper", bills);
ReflectionTestUtils.setField(service, "bankAccountMapper", accounts);
ReflectionTestUtils.setField(service, "generateTaskMapper", tasks);
ReflectionTestUtils.setField(service, "billScope", scope);
ReflectionTestUtils.setField(service, "customerMapper", mock(BmsCustomerMapper.class));
ReflectionTestUtils.setField(service, "eventPublisher", mock(ApplicationEventPublisher.class));
ReflectionTestUtils.setField(service, "logService", mock(IArBillLogService.class));
BmsCustomerOption customer = new BmsCustomerOption();
customer.setCustomerCode("C1");
customer.setCustomerName("客户");
when(scope.requireCustomerAccessible(1L)).thenReturn(customer);
}
@AfterEach
void clearLogin() { SecurityContextHolder.clearContext(); }
@Test
void selectedAccountIsValidatedAndSavedAsBillSnapshot() {
ArBankAccount account = account("CNY");
when(accounts.selectEnabledById(9L)).thenReturn(account);
ArBillGenerateRequest request = request();
request.setBankAccountId(9L);
request.setBankAccountNo("前端伪造的账号");
service.generateBill(request, "admin", "request-1");
ArgumentCaptor<ArBill> saved = ArgumentCaptor.forClass(ArBill.class);
verify(bills).insertArBill(saved.capture());
assertEquals(account.getAccountName(), saved.getValue().getBankAccountName());
assertEquals(account.getAccountNo(), saved.getValue().getBankAccountNo());
assertEquals(account.getBankName(), saved.getValue().getBankName());
verify(accounts, never()).selectDefaultByCurrency(anyString());
}
@Test
void missingOrWrongCurrencyAccountCannotCreateBillAndOldRequestsUseDefault() {
ArBillGenerateRequest request = request();
request.setBankAccountId(9L);
assertThrows(ServiceException.class, () -> service.generateBill(request, "admin", "missing"));
when(accounts.selectEnabledById(9L)).thenReturn(account("USD"));
assertThrows(ServiceException.class, () -> service.generateBill(request, "admin", "wrong-currency"));
verify(bills, never()).insertArBill(any());
request.setBankAccountId(null);
when(accounts.selectDefaultByCurrency("CNY")).thenReturn(account("CNY"));
assertDoesNotThrow(() -> service.generateBill(request, "admin", "legacy"));
verify(accounts).selectDefaultByCurrency("CNY");
}
@Test
void bankAccountOptionsMaskNumbersWithoutSpaces() {
ArBankAccount account = account("CNY");
when(accounts.selectEnabledList("CNY")).thenReturn(List.of(account));
assertEquals("****2050", service.selectMaskedBankAccounts("CNY").get(0).getAccountNo());
}
private static ArBankAccount account(String currency) {
ArBankAccount account = new ArBankAccount();
account.setAccountName("收款单位");
account.setAccountNo("8602 1110 0008 9205 0");
account.setBankName("开户行");
account.setCurrency(currency);
return account;
}
private static ArBillGenerateRequest request() {
ArBillGenerateRequest request = new ArBillGenerateRequest();
request.setCustomerId(1L);
request.setBillName("测试账单");
request.setBillPeriodEnd(Date.valueOf("2026-10-31"));
request.setSourceBillIds(List.of(1L));
return request;
}
}
@@ -111,6 +111,23 @@ class ArBillTemplateSelectionTest {
assertEquals("应收账单汇总模板", options.get(0).getTemplateName());
}
@Test
void fixedPayeeTemplatesAllowDifferentBillAccountSnapshots() {
bill.setBankAccountName("其他收款单位");
bill.setBankAccountNo("1234567890");
bill.setBankName("其他银行");
ArExportTemplate guangzhou = template(3L, ArBillWorkbookWriters.GUANGZHOU_TEMPLATE_CODE);
guangzhou.setStorageKey("templates/receivable/ar_bill_template_gz.xlsx");
ArExportTemplate jiyun = template(4L, ArBillWorkbookWriters.JIYUN_TEMPLATE_CODE);
jiyun.setStorageKey("templates/receivable/ar_bill_template_jy.xlsx");
when(templates.selectEnabledById(3L, "AR_BILL", bill.getBillDate())).thenReturn(guangzhou);
when(templates.selectEnabledById(4L, "AR_BILL", bill.getBillDate())).thenReturn(jiyun);
assertEquals(3L, service.exportBill(7L, 3L, "admin", "gz-export").getTemplateId());
assertEquals(4L, service.exportBill(7L, 4L, "admin", "jy-export").getTemplateId());
verify(exports, times(2)).insert(any());
}
@Test
void mapperQueriesEnforceBusinessStatusEffectiveDatesAndTaskTemplate() throws Exception {
Configuration configuration = new Configuration();
@@ -11,6 +11,8 @@ import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -24,6 +26,8 @@ import com.bms.receivable.domain.ArExportTemplate;
import com.bms.receivable.mapper.ArBillDetailFeeMapper;
import com.bms.receivable.mapper.ArBillDetailMapper;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFSheet;
@@ -35,12 +39,42 @@ class ArBillWorkbookWriterTest {
@TempDir
Path temporary;
@Test
void summaryDetailsKeepReceiptDateTimeAsExcelDateForNormalAndHighlightedRows() throws Exception {
ArBillDetail normal = detail(1, "P1", "1.00");
normal.setReceiveTime(Timestamp.valueOf("2026-10-01 21:32:51"));
ArBillDetail failed = detail(2, "P1", "1.00");
failed.setReceiveTime(Timestamp.valueOf("2026-10-02 00:01:02"));
failed.setBillingFailStatus(2);
ArBillDetail missing = detail(3, "P1", "1.00");
missing.setReceiveTime(null);
Path target = temporary.resolve("summary-receipt-times.xlsx");
summaryWriter(List.of(normal, failed, missing)).write(bill(3, "3.00", "CNY"), summaryTemplate(), target);
try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) {
XSSFSheet sheet = workbook.getSheetAt(1);
var normalCell = sheet.getRow(4).getCell(1);
var failedCell = sheet.getRow(5).getCell(1);
assertEquals(CellType.NUMERIC, normalCell.getCellType());
assertEquals(CellType.NUMERIC, failedCell.getCellType());
assertTrue(DateUtil.isCellDateFormatted(normalCell));
assertTrue(DateUtil.isCellDateFormatted(failedCell));
assertEquals("yyyy/mm/dd", normalCell.getCellStyle().getDataFormatString());
assertEquals("2026/10/01", new DataFormatter().formatCellValue(normalCell));
assertEquals(LocalDateTime.of(2026, 10, 1, 21, 32, 51), normalCell.getLocalDateTimeCellValue());
assertEquals("2026/10/02", new DataFormatter().formatCellValue(failedCell));
assertEquals(LocalDateTime.of(2026, 10, 2, 0, 1, 2), failedCell.getLocalDateTimeCellValue());
assertEquals(IndexedColors.YELLOW.getIndex(), failedCell.getCellStyle().getFillForegroundColor());
assertEquals("", sheet.getRow(6).getCell(1).getStringCellValue());
}
}
@Test
void summaryAndDetailsReconcileSnapshotAmountsAndKeepFreightFormulaAndBlankFields() throws Exception {
ArBill bill = bill(3, "13.20", "CNY");
List<ArBillDetail> details = List.of(detail(1, "P1", "10.12"), detail(2, "P1", "-2.22"),
detail(3, "P2", "5.30"));
// 相同名称的不同产品仍需分组;收货日期也不能替代账单所属期。
// 相同名称的不同产品仍需分组;日期范围统一按本账单明细的收货日期展示。
details.forEach(row -> row.setProductName("相同产品名"));
Path target = temporary.resolve("summary.xlsx");
SummaryArBillWorkbookWriter writer = summaryWriter(details);
@@ -54,7 +88,7 @@ class ArBillWorkbookWriterTest {
assertEquals("客户 & <测试>", summary.getRow(3).getCell(1).getStringCellValue());
assertEquals("相同产品名", summary.getRow(3).getCell(2).getStringCellValue());
assertEquals("相同产品名", summary.getRow(4).getCell(2).getStringCellValue());
assertEquals("20261001-20261031", summary.getRow(3).getCell(3).getStringCellValue());
assertEquals("20261105-20261105", summary.getRow(3).getCell(3).getStringCellValue());
assertEquals("国际货物运输代理服务费", summary.getRow(4).getCell(6).getStringCellValue());
assertEquals(7.90, summary.getRow(3).getCell(4).getNumericCellValue(), 0.00001);
assertEquals(5.30, summary.getRow(4).getCell(4).getNumericCellValue(), 0.00001);
@@ -65,7 +99,7 @@ class ArBillWorkbookWriterTest {
assertTrue(summary.getMergedRegions().stream().anyMatch(region -> "A11:B11".equals(region.formatAsString())));
assertEquals("客户 & <测试>", freight.getRow(2).getCell(1).getStringCellValue());
assertEquals("20261001-20261031", freight.getRow(2).getCell(18).getStringCellValue());
assertEquals("20261105-20261105", freight.getRow(2).getCell(18).getStringCellValue());
assertEquals("0000123", freight.getRow(4).getCell(0).getStringCellValue());
assertEquals("00000001", freight.getRow(4).getCell(2).getStringCellValue());
assertEquals("001234567890123456789", freight.getRow(4).getCell(3).getStringCellValue());
@@ -206,6 +240,53 @@ class ArBillWorkbookWriterTest {
}
}
@Test
void summaryDatesUseTheWholeBillsReceiveRangeInsteadOfItsStoredPeriod() throws Exception {
ArBill bill = bill(3, "3.00", "CNY");
bill.setBillPeriodStart(Date.valueOf("2026-09-29"));
bill.setBillPeriodEnd(Date.valueOf("2026-10-31"));
ArBillDetail middle = detail(1, "P1", "1.00");
middle.setReceiveTime(Date.valueOf("2026-10-20"));
ArBillDetail earliest = detail(2, "P2", "1.00");
earliest.setReceiveTime(Date.valueOf("2026-10-01"));
ArBillDetail latest = detail(3, "P1", "1.00");
latest.setReceiveTime(Date.valueOf("2026-10-30"));
SummaryArBillWorkbookWriter writer = summaryWriter(List.of(middle, earliest, latest));
when(writer.detailMapper.selectReceiveTimeRangeByBillId(7L)).thenReturn(Map.of(
"minReceiveTime", LocalDateTime.of(2026, 10, 1, 8, 30),
"maxReceiveTime", Timestamp.valueOf("2026-10-30 23:50:00")));
Path target = temporary.resolve("receive-dates.xlsx");
writer.write(bill, summaryTemplate(), target);
try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) {
XSSFSheet summary = workbook.getSheetAt(0);
XSSFSheet freight = workbook.getSheetAt(1);
assertEquals("20261001-20261030", summary.getRow(3).getCell(3).getStringCellValue());
assertEquals("20261001-20261030", summary.getRow(4).getCell(3).getStringCellValue());
assertEquals("20261001-20261030", freight.getRow(2).getCell(18).getStringCellValue());
assertEquals(LocalDateTime.of(2026, 10, 20, 0, 0), freight.getRow(4).getCell(1).getLocalDateTimeCellValue());
assertEquals(LocalDateTime.of(2026, 10, 1, 0, 0), freight.getRow(5).getCell(1).getLocalDateTimeCellValue());
assertEquals(LocalDateTime.of(2026, 10, 30, 0, 0), freight.getRow(6).getCell(1).getLocalDateTimeCellValue());
}
verify(writer.detailMapper, times(1)).selectReceiveTimeRangeByBillId(7L);
assertEquals(Date.valueOf("2026-09-29"), bill.getBillPeriodStart());
assertEquals(Date.valueOf("2026-10-31"), bill.getBillPeriodEnd());
}
@Test
void summaryDatesStayBlankWhenReceiveTimesAreMissing() throws Exception {
ArBillDetail detail = detail(1, "P1", "1.00");
detail.setReceiveTime(null);
SummaryArBillWorkbookWriter writer = summaryWriter(List.of(detail));
when(writer.detailMapper.selectReceiveTimeRangeByBillId(7L)).thenReturn(Map.of());
Path target = temporary.resolve("missing-receive-dates.xlsx");
writer.write(bill(1, "1.00", "CNY"), summaryTemplate(), target);
try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) {
assertEquals("", workbook.getSheetAt(0).getRow(3).getCell(3).getStringCellValue());
assertEquals("", workbook.getSheetAt(1).getRow(2).getCell(18).getStringCellValue());
assertEquals("", workbook.getSheetAt(1).getRow(4).getCell(1).getStringCellValue());
}
}
@Test
void fixedPayeeTemplatesKeepTheirOwnBankDetailsAndSecondSheetWhileFillingOrders() throws Exception {
for (String code : List.of(ArBillWorkbookWriters.GUANGZHOU_TEMPLATE_CODE,
@@ -277,6 +358,8 @@ class ArBillWorkbookWriterTest {
private SummaryArBillWorkbookWriter summaryWriter(List<ArBillDetail> details) {
SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter();
writer.detailMapper = mapper(details);
when(writer.detailMapper.selectReceiveTimeRangeByBillId(7L)).thenReturn(Map.of(
"minReceiveTime", Date.valueOf("2026-11-05"), "maxReceiveTime", Date.valueOf("2026-11-05")));
writer.detailFeeMapper = mock(ArBillDetailFeeMapper.class);
when(writer.detailFeeMapper.selectByDetailIds(anyList())).thenReturn(List.of());
return writer;
@@ -105,8 +105,8 @@ public class LblProduct extends BaseEntity
private List<LblExtraLine> extraLines;
/** 邮编→分区(保存时按产品同步到 prc_zone LABEL,不落产品子表) */
private Map<String, List<String>> zonePostcodes;
/** 邮编→分区(保存时按产品同步到 prc_zone LABEL;元素含 postcode+matchType) */
private Map<String, List<PrcZoneDetail>> zonePostcodes;
/** 编辑保存删除标记(不落库) */
private Boolean deleted;
@@ -1,15 +0,0 @@
package com.bms.price.domain;
import java.util.List;
import lombok.Data;
/** 应付列表勾选订单后,批量写入同一组手工费用。 */
@Data
public class PayOrderFeeBatch
{
/** 勾选的计费订单 ID */
private List<String> billIds;
/** 要加到每一票订单上的费用 */
private List<PayOrderFeeLine> fees;
}
@@ -17,9 +17,6 @@ public class PayOrderRow
private String trackingNo;
/** 客户编码,列表展示用 */
private String customerCode;
private String customerName;
private String productName;
@@ -24,21 +24,9 @@ public class PrcPayBill implements Serializable
private BigDecimal redlineAmount;
/** 成本价合计(当前计费结果) */
private BigDecimal costAmount;
/** 应付合计(当前等于成本价,落库后按全部未删除明细折人民币重算) */
/** 应付合计(当前等于成本价,落库后按全部未删除明细重算) */
private BigDecimal payTotal;
/** A段合计,人民币 */
private BigDecimal amountA;
/** B段合计,人民币 */
private BigDecimal amountB;
/** C段合计,人民币 */
private BigDecimal amountC;
/** D段合计,人民币 */
private BigDecimal amountD;
/** 应付计费状态,字典 bms_pay_calc_status:1计费成功,2计费失败 */
private Integer payCalcStatus;
@@ -2,6 +2,7 @@ package com.bms.price.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.Locale;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@@ -11,11 +12,41 @@ public class PrcZoneDetail implements Serializable
{
private static final long serialVersionUID = 1L;
/** 全匹配邮编 */
public static final String MATCH_FULL = "FULL";
/** 匹配邮编开头 */
public static final String MATCH_PREFIX = "PREFIX";
private Long detailId;
private Long zoneId;
private String postcode;
/** FULL / PREFIX,默认 FULL */
private String matchType;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public static String normalizeMatchType(String raw)
{
if (raw == null || raw.isBlank())
{
return MATCH_FULL;
}
String value = raw.trim().toUpperCase(Locale.ROOT);
if (MATCH_PREFIX.equals(value) || "START".equals(value) || "STARTS".equals(value))
{
return MATCH_PREFIX;
}
return MATCH_FULL;
}
public static PrcZoneDetail of(String postcode, String matchType)
{
PrcZoneDetail detail = new PrcZoneDetail();
detail.setPostcode(postcode);
detail.setMatchType(normalizeMatchType(matchType));
return detail;
}
}
@@ -72,18 +72,6 @@ public class TmsPriceQuoteResult implements Serializable
private BigDecimal incomeTotal;
/** 应付合计(订单账单);也是报价应付 */
private BigDecimal payTotal;
/** 应付 A 段合计,来自 prc_pay_bill.amount_a */
private BigDecimal amountA;
/** 应付 B 段合计,来自 prc_pay_bill.amount_b */
private BigDecimal amountB;
/** 应付 C 段合计,来自 prc_pay_bill.amount_c */
private BigDecimal amountC;
/** 应付 D 段合计,来自 prc_pay_bill.amount_d */
private BigDecimal amountD;
/** 报价 / 历史字段;账单同步时与 incomeTotal 相同 */
private BigDecimal payableTotal;
private String currency = "CNY";
@@ -35,6 +35,13 @@ public final class LblCostCalculator
public static PayOrderCostResult calculate(LblProduct 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, null);
}
public static PayOrderCostResult calculate(LblProduct product, BigDecimal weight, BigDecimal length, BigDecimal width,
BigDecimal height, String postcode, String zoneName, Date bizDate, Integer orderStatus,
String countryCode, String countryName)
{
PayOrderCostResult result = new PayOrderCostResult();
result.setFees(new ArrayList<PayCostLine>());
@@ -52,7 +59,14 @@ public final class LblCostCalculator
return result;
}
List<LblWeightBand> all = product.getWeightBands() == null ? List.of() : product.getWeightBands();
List<LblWeightBand> raw = product.getWeightBands() == null ? List.of() : product.getWeightBands();
List<LblWeightBand> all = filterByCountry(raw, countryCode, countryName);
if (all.isEmpty() && !raw.isEmpty() && hasCountryCode(countryCode, countryName))
{
result.setMessage("产品「" + nz(product.getProductName()) + "」没有命中国家 "
+ nz(countryCode) + (nz(countryName).isEmpty() ? "" : "/" + nz(countryName)) + " 的价卡");
return result;
}
Set<String> zones = zoneNames(all);
if (zones.size() > 1 && (zoneName == null || zoneName.isBlank()))
{
@@ -102,9 +116,21 @@ public final class LblCostCalculator
}
if (!hasFreightLine)
{
result.setMessage(outOfRange(product, all, weight, zoneName));
result.getFees().clear();
return result;
// 价卡仅有处理费/偏远、无派送费段时(如 NL-DHL),允许按已算费用出账;附加费基数用处理费
if (!hasFreightTypeBands(all) && result.getFees() != null && !result.getFees().isEmpty())
{
freight = sumFeeAmounts(result, "REGISTRATION_FEE");
if (freight.compareTo(BigDecimal.ZERO) == 0)
{
freight = sumAllFeeAmounts(result);
}
}
else
{
result.setMessage(outOfRange(product, all, weight, zoneName));
result.getFees().clear();
return result;
}
}
}
@@ -287,11 +313,14 @@ public final class LblCostCalculator
return base;
}
BigDecimal over = weight.subtract(first);
if (over.compareTo(BigDecimal.ZERO) < 0)
if (over.compareTo(BigDecimal.ZERO) <= 0)
{
over = BigDecimal.ZERO;
return base;
}
return base.add(extra.multiply(over));
// 首重+续重:超出部分按「每增加 X Kg」向上取整档数(不按公斤比例)
BigDecimal step = extraStepKg(band, first);
BigDecimal steps = over.divide(step, 0, RoundingMode.CEILING);
return base.add(extra.multiply(steps));
}
if (band.getPrice() == null)
{
@@ -305,6 +334,23 @@ public final class LblCostCalculator
return band.getPrice();
}
/**
* 续重步长:优先解析重量段「每增加 X」;否则用首重;再否则 1kg。
*/
private static BigDecimal extraStepKg(LblWeightBand band, BigDecimal firstKg)
{
BigDecimal fromLabel = LblTexts.extraStepKg(band == null ? null : band.getWeightLabel());
if (fromLabel != null && fromLabel.compareTo(BigDecimal.ZERO) > 0)
{
return fromLabel;
}
if (firstKg != null && firstKg.compareTo(BigDecimal.ZERO) > 0)
{
return firstKg;
}
return BigDecimal.ONE;
}
private static BigDecimal firstKg(LblWeightBand band)
{
if (band.getCalcParam() != null && !band.getCalcParam().isBlank())
@@ -379,6 +425,132 @@ public final class LblCostCalculator
return "基础运费";
}
/** 按订单国家收窄重量段;有国别代码时不允许误用其他国。 */
private static List<LblWeightBand> filterByCountry(List<LblWeightBand> bands, String countryCode, String countryName)
{
if (bands == null || bands.isEmpty() || !hasCountryCode(countryCode, countryName))
{
return bands == null ? List.of() : bands;
}
List<LblWeightBand> matched = new ArrayList<LblWeightBand>();
List<LblWeightBand> blank = new ArrayList<LblWeightBand>();
for (LblWeightBand band : bands)
{
if (band == null)
{
continue;
}
if (bandCountryBlank(band))
{
blank.add(band);
continue;
}
if (bandMatchesCountry(band, countryCode, countryName))
{
matched.add(band);
}
}
return matched.isEmpty() ? blank : matched;
}
private static boolean hasCountryCode(String countryCode, String countryName)
{
return (countryCode != null && !countryCode.isBlank()) || (countryName != null && !countryName.isBlank());
}
private static boolean bandCountryBlank(LblWeightBand band)
{
return nz(band.getCountryCode()).isEmpty() && nz(band.getCountryName()).isEmpty();
}
private static boolean bandMatchesCountry(LblWeightBand band, String countryCode, String countryName)
{
String orderCc = nz(countryCode).toUpperCase(Locale.ROOT);
String bandCc = nz(band.getCountryCode()).toUpperCase(Locale.ROOT);
if (!orderCc.isEmpty() && !bandCc.isEmpty())
{
for (String part : bandCc.split("[,;/\\s]+"))
{
if (part != null && orderCc.equals(part.trim()))
{
return true;
}
}
String bandNameU = nz(band.getCountryName()).toUpperCase(Locale.ROOT).replace(" ", "");
if (bandNameU.contains("(" + orderCc + ")") || bandNameU.endsWith(orderCc))
{
return true;
}
}
String orderName = nz(countryName);
String bandName = nz(band.getCountryName());
if (!orderName.isEmpty() && !bandName.isEmpty())
{
String bare = bandName.replaceAll("\\([^)]*\\)", "").trim();
if (bandName.contains(orderName) || (!bare.isEmpty() && orderName.contains(bare)))
{
return true;
}
}
return false;
}
/** 当前国家收窄后是否存在派送费(FREIGHT)段;空 fee_type 视为 FREIGHT */
private static boolean hasFreightTypeBands(List<LblWeightBand> bands)
{
if (bands == null || bands.isEmpty())
{
return false;
}
for (LblWeightBand band : bands)
{
if (band == null)
{
continue;
}
String ft = nz(band.getFeeType());
if (ft.isEmpty() || LblFeeType.FREIGHT.equals(ft))
{
return true;
}
}
return false;
}
private static BigDecimal sumFeeAmounts(PayOrderCostResult result, String feeType)
{
BigDecimal sum = BigDecimal.ZERO;
if (result == null || result.getFees() == null || feeType == null)
{
return sum;
}
for (PayCostLine fee : result.getFees())
{
if (fee != null && feeType.equals(fee.getFeeType()) && fee.getAmount() != null)
{
sum = sum.add(fee.getAmount());
}
}
return sum;
}
private static BigDecimal sumAllFeeAmounts(PayOrderCostResult result)
{
BigDecimal sum = BigDecimal.ZERO;
if (result == null || result.getFees() == null)
{
return sum;
}
for (PayCostLine fee : result.getFees())
{
if (fee != null && fee.getAmount() != null)
{
sum = sum.add(fee.getAmount());
}
}
return sum;
}
private static Set<String> zoneNames(List<LblWeightBand> bands)
{
Set<String> zones = new LinkedHashSet<String>();
@@ -94,6 +94,23 @@ public final class LblTexts
return bounds;
}
/**
* 从「每增加 X Kg」取续重步长;解不出返 null。
*/
public static BigDecimal extraStepKg(String label)
{
if (label == null || label.isBlank())
{
return null;
}
Matcher step = STEP_WEIGHT.matcher(label);
if (step.find())
{
return decimal(step.group(1));
}
return null;
}
public static boolean looksLikeWeight(String text)
{
if (text == null)
@@ -1611,8 +1611,9 @@ public class LblWorkbookParser
}
else if (remoteHandle)
{
band.setFeeType(com.bms.price.domain.LblFeeType.REMOTE);
band.setChargeName(chargeTitle(parent[col]));
// CTT 等:「偏远附加费」实为派送费(FREIGHT),按邮编前缀命中,不落 REMOTE
band.setFeeType(com.bms.price.domain.LblFeeType.FREIGHT);
band.setChargeName("派送费");
band.setZoneName(zoneName);
applyRemotePostcode(band, rawZone);
band.setPrice(price);
@@ -4378,7 +4379,8 @@ public class LblWorkbookParser
}
/**
* 价表中与派送费并排的偏远列:落重量段 fee_type=REMOTE,不进附加费表。
* 价表中「偏远附加费」列/表头:CTT 等按派送费 FREIGHT+邮编前缀落库;
* Evri 等非首重/续重并排列仍可落 REMOTE。
*/
private static boolean isRemoteHandleHead(String head)
{
@@ -14,10 +14,12 @@ import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.bms.price.domain.LblProduct;
import com.bms.price.domain.LblWeightBand;
import com.bms.price.domain.PrcZoneDetail;
/**
* 打单价卡「邮编分区」表抽取为 zone→postcodes,保存时同步到分区管理 prc_zone。
* 支持 Corres/双列、Colissimo Densite、CTT Density、PosteItaliane 三列、iMile IT/DE。
* 支持 Corres/双列、Colissimo Densite、CTT Density、PosteItaliane 三列、iMile IT/DE;
* 以及「英国附加费」中 EVRI 偏远邮编前缀(挂到 Evri 产品)。
*/
public final class LblZonePostcodeAttach
{
@@ -43,6 +45,11 @@ public final class LblZonePostcodeAttach
continue;
}
String sheetName = sheet.getSheetName() == null ? "" : sheet.getSheetName().trim();
if (isUkSurchargeSheet(sheetName))
{
attachUkEvri(sheet, sheetName, products);
continue;
}
if (!isZonePostcodeSheet(sheetName))
{
continue;
@@ -52,17 +59,32 @@ public final class LblZonePostcodeAttach
attachImile(sheet, sheetName, products);
continue;
}
Map<String, List<String>> zoneMap = parseSheet(sheet);
if (zoneMap.isEmpty())
{
continue;
}
LblProduct target = matchProduct(products, sheetName);
if (target == null)
{
continue;
}
mergeZonePostcodes(target, zoneMap);
Map<String, List<String>> poste = parsePosteItaliane(sheet);
if (!poste.isEmpty())
{
Map<String, List<String>> city = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> rural = new LinkedHashMap<String, List<String>>();
if (poste.get("City") != null) city.put("City", poste.get("City"));
if (poste.get("Province") != null) city.put("Province", poste.get("Province"));
if (poste.get("Rural") != null) rural.put("Rural", poste.get("Rural"));
mergeZonePostcodes(target, city, PrcZoneDetail.MATCH_PREFIX);
mergeZonePostcodes(target, rural, PrcZoneDetail.MATCH_FULL);
linkSheet(target, sheetName);
continue;
}
Map<String, List<String>> zoneMap = parseSheet(sheet);
if (zoneMap.isEmpty())
{
continue;
}
// 表名含「邮编开头」或单元格带 * 时按前缀;否则全匹配
String matchType = sheetName.contains("邮编开头") ? PrcZoneDetail.MATCH_PREFIX : PrcZoneDetail.MATCH_FULL;
mergeZonePostcodes(target, zoneMap, matchType);
linkSheet(target, sheetName);
}
}
@@ -95,9 +117,18 @@ public final class LblZonePostcodeAttach
{
return m.group(1);
}
// IT-iMile / DE-iMile:从表名/产品名推导
String blob = compact(nz(product.getSheetName()) + nz(product.getProductName()) + nz(product.getDictValue()));
if (blob.contains("itimile") || blob.startsWith("itimile") || blob.contains("italyimile"))
{
return "IT";
}
if (blob.contains("deimile") || blob.contains("germanyimile"))
{
return "DE";
}
return "";
}
private static boolean isZonePostcodeSheet(String sheetName)
{
if (sheetName == null || sheetName.isBlank())
@@ -107,6 +138,257 @@ public final class LblZonePostcodeAttach
return sheetName.contains("邮编") && sheetName.contains("分区");
}
/** 英国附加费:Royal Mail / EVRI 偏远邮编前缀表。 */
private static boolean isUkSurchargeSheet(String sheetName)
{
if (sheetName == null || sheetName.isBlank())
{
return false;
}
return sheetName.contains("英国") && sheetName.contains("附加费");
}
/**
* 从「英国附加费」右侧 EVRI 列抽取偏远邮编,映射为 Evri 价表分区名后挂到 Evri 产品。
*/
private static void attachUkEvri(Sheet sheet, String sheetName, List<LblProduct> products)
{
Map<String, List<String>> zoneMap = parseUkEvriZonePostcodes(sheet);
if (zoneMap.isEmpty())
{
return;
}
LblProduct target = matchEvriProduct(products);
if (target == null)
{
return;
}
mergeZonePostcodes(target, zoneMap, PrcZoneDetail.MATCH_PREFIX);
linkSheet(target, sheetName);
}
private static Map<String, List<String>> parseUkEvriZonePostcodes(Sheet sheet)
{
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS);
int headerRow = -1;
int enCol = 4;
int zhCol = 5;
int postcodeCol = 6;
for (int r = 0; r <= Math.min(lastRow, 8); r++)
{
Row row = sheet.getRow(r);
if (row == null)
{
continue;
}
boolean hasEvriTitle = false;
boolean hasPcHead = false;
for (int c = 0; c < row.getLastCellNum(); c++)
{
String val = cellText(row.getCell(c));
String up = val.toUpperCase(Locale.ROOT);
if (up.contains("EVRI"))
{
hasEvriTitle = true;
}
if (val.contains("邮编开头") && c >= 3)
{
hasPcHead = true;
}
}
if (hasEvriTitle && !hasPcHead)
{
Row next = sheet.getRow(r + 1);
if (next != null)
{
int foundEn = -1;
int foundZh = -1;
int foundPc = -1;
for (int c = 0; c < next.getLastCellNum(); c++)
{
String val = cellText(next.getCell(c));
if (c < 3)
{
continue;
}
if (val.contains("偏远地区") && val.contains("英文") && foundEn < 0)
{
foundEn = c;
}
else if (val.contains("偏远地区") && val.contains("中文") && foundZh < 0)
{
foundZh = c;
}
else if (val.contains("邮编开头") && foundPc < 0)
{
foundPc = c;
}
}
if (foundPc >= 0)
{
headerRow = r + 1;
if (foundEn >= 0)
{
enCol = foundEn;
}
if (foundZh >= 0)
{
zhCol = foundZh;
}
postcodeCol = foundPc;
break;
}
}
}
if (hasPcHead)
{
int foundEn = -1;
int foundZh = -1;
int foundPc = -1;
for (int c = 0; c < row.getLastCellNum(); c++)
{
String val = cellText(row.getCell(c));
if (c < 3)
{
continue;
}
if (val.contains("偏远地区") && val.contains("英文") && foundEn < 0)
{
foundEn = c;
}
else if (val.contains("偏远地区") && val.contains("中文") && foundZh < 0)
{
foundZh = c;
}
else if (val.contains("邮编开头") && foundPc < 0)
{
foundPc = c;
}
}
if (foundPc >= 0)
{
headerRow = r;
if (foundEn >= 0)
{
enCol = foundEn;
}
if (foundZh >= 0)
{
zhCol = foundZh;
}
postcodeCol = foundPc;
break;
}
}
}
if (headerRow < 0)
{
headerRow = 1;
enCol = 4;
zhCol = 5;
postcodeCol = 6;
}
String lastEn = "";
String lastZh = "";
for (int r = headerRow + 1; r <= lastRow; r++)
{
Row row = sheet.getRow(r);
if (row == null)
{
continue;
}
String en = normalizeZone(cellText(row.getCell(enCol)));
String zh = normalizeZone(cellText(row.getCell(zhCol)));
if (!en.isEmpty())
{
lastEn = en;
}
if (!zh.isEmpty())
{
lastZh = zh;
}
String postcode = stripTrailingStar(normalizePostcode(cellText(row.getCell(postcodeCol)), 0));
if (postcode.isEmpty() || (lastEn.isEmpty() && lastZh.isEmpty()))
{
continue;
}
String zone = mapEvriZoneName(lastEn, lastZh);
if (zone.isEmpty())
{
continue;
}
List<String> list = map.computeIfAbsent(zone, k -> new ArrayList<String>());
if (!list.contains(postcode))
{
list.add(postcode);
}
}
return map;
}
/** 映射为与 Evri 48H 价表分区列可对上的名称。 */
private static String mapEvriZoneName(String en, String zh)
{
String blob = ((en == null ? "" : en) + " " + (zh == null ? "" : zh)).toLowerCase(Locale.ROOT);
if (blob.contains("bfpo"))
{
return "BFPO";
}
if (blob.contains("isle of man") || blob.contains("马恩"))
{
return "Isle of Man";
}
if (blob.contains("northern ireland") || blob.contains("北爱尔兰"))
{
return "Northern Ireland";
}
if (blob.contains("channel") || blob.contains("scilly") || blob.contains("海峡") || blob.contains("锡利"))
{
return "Channel Islands / Isle of Scilly";
}
if (blob.contains("scottish") || blob.contains("shetland") || blob.contains("highland") || blob.contains("h&i")
|| blob.contains("高地"))
{
return "Highlands & Islands";
}
String fallback = normalizeZone(en);
if (!fallback.isEmpty())
{
return fallback;
}
return normalizeZone(zh);
}
private static LblProduct matchEvriProduct(List<LblProduct> products)
{
LblProduct hit = null;
int count = 0;
for (LblProduct product : products)
{
String blob = compact(nz(product.getProductName()) + nz(product.getSheetName()) + nz(product.getDictValue()));
if (blob.contains("evri"))
{
hit = product;
count++;
}
}
if (count == 1)
{
return hit;
}
return null;
}
private static String stripTrailingStar(String text)
{
if (text == null || text.isEmpty())
{
return "";
}
return text.replaceAll("\\*+\\s*$", "").trim();
}
private static Map<String, List<String>> parseSheet(Sheet sheet)
{
Map<String, List<String>> poste = parsePosteItaliane(sheet);
@@ -209,6 +491,16 @@ public final class LblZonePostcodeAttach
}
}
private static String detectMatchType(String raw, String fallback)
{
String text = raw == null ? "" : raw.trim();
if (text.endsWith("*") || text.contains("邮编开头"))
{
return PrcZoneDetail.MATCH_PREFIX;
}
return PrcZoneDetail.normalizeMatchType(fallback);
}
private static Map<String, List<String>> parseCtt(Sheet sheet)
{
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
@@ -433,7 +725,8 @@ public final class LblZonePostcodeAttach
LblProduct germany = productOf(products, "DE-iMile");
int lastRow = Math.min(sheet.getLastRowNum(), MAX_ROWS);
int header = -1;
for (int r = 0; r <= Math.min(lastRow, 6); r++)
// 不能只认「邮编」:标题行「IT-iMile邮编分区」也含该字,须同时有列名(城市/分区/ZIP)
for (int r = 0; r <= Math.min(lastRow, 8); r++)
{
Row row = sheet.getRow(r);
if (row == null)
@@ -443,11 +736,20 @@ public final class LblZonePostcodeAttach
StringBuilder line = new StringBuilder();
for (int c = 0; c < row.getLastCellNum(); c++)
{
line.append(cellText(row.getCell(c)));
line.append(cellText(row.getCell(c))).append(' ');
}
String text = line.toString();
if (text.contains("邮编") || text.toLowerCase(Locale.ROOT).contains("zip"))
String low = text.toLowerCase(Locale.ROOT);
boolean hasItHead = text.contains("邮编") && (text.contains("分区") || text.contains("城市"));
boolean hasDeHead = low.contains("zip");
if (hasItHead || hasDeHead)
{
// 排除纯标题:仅有「xxx邮编分区」无列名
if (text.contains("邮编分区") && !text.contains("城市") && !low.contains("zip")
&& !text.contains("邮编(") && !text.contains("邮编("))
{
continue;
}
header = r;
break;
}
@@ -520,12 +822,12 @@ public final class LblZonePostcodeAttach
}
if (italy != null && !itMap.isEmpty())
{
mergeZonePostcodes(italy, itMap);
mergeZonePostcodes(italy, itMap, PrcZoneDetail.MATCH_FULL);
linkSheet(italy, sheetName);
}
if (germany != null && !deMap.isEmpty())
{
mergeZonePostcodes(germany, deMap);
mergeZonePostcodes(germany, deMap, PrcZoneDetail.MATCH_FULL);
linkSheet(germany, sheetName);
}
}
@@ -550,6 +852,10 @@ public final class LblZonePostcodeAttach
private static LblProduct productOf(List<LblProduct> products, String name)
{
if (products == null || name == null || name.isBlank())
{
return null;
}
for (LblProduct product : products)
{
if (name.equals(product.getSheetName()) || name.equals(product.getProductName())
@@ -558,6 +864,16 @@ public final class LblZonePostcodeAttach
return product;
}
}
// IT-iMile / DE-iMile:允许 sheet/dict 含同名 token
String key = compact(name);
for (LblProduct product : products)
{
String blob = compact(nz(product.getProductName()) + nz(product.getSheetName()) + nz(product.getDictValue()));
if (!key.isEmpty() && blob.contains(key))
{
return product;
}
}
return null;
}
@@ -615,22 +931,49 @@ public final class LblZonePostcodeAttach
return null;
}
private static void mergeZonePostcodes(LblProduct product, Map<String, List<String>> incoming)
private static void mergeZonePostcodes(LblProduct product, Map<String, List<String>> incoming, String matchType)
{
Map<String, List<String>> current = product.getZonePostcodes();
if (product == null || incoming == null || incoming.isEmpty())
{
return;
}
Map<String, List<PrcZoneDetail>> current = product.getZonePostcodes();
if (current == null)
{
current = new LinkedHashMap<String, List<String>>();
current = new LinkedHashMap<String, List<PrcZoneDetail>>();
product.setZonePostcodes(current);
}
String type = PrcZoneDetail.normalizeMatchType(matchType);
for (Map.Entry<String, List<String>> e : incoming.entrySet())
{
List<String> list = current.computeIfAbsent(e.getKey(), k -> new ArrayList<String>());
List<PrcZoneDetail> list = current.computeIfAbsent(e.getKey(), k -> new ArrayList<PrcZoneDetail>());
for (String pc : e.getValue())
{
if (!list.contains(pc))
if (pc == null || pc.isBlank())
{
list.add(pc);
continue;
}
String postcode = pc.trim();
String rowType = detectMatchType(postcode, type);
// 落库前去掉尾部 *
postcode = stripTrailingStar(postcode);
if (postcode.isEmpty())
{
continue;
}
boolean exists = false;
for (PrcZoneDetail item : list)
{
if (item != null && postcode.equalsIgnoreCase(item.getPostcode()))
{
item.setMatchType(rowType);
exists = true;
break;
}
}
if (!exists)
{
list.add(PrcZoneDetail.of(postcode, rowType));
}
}
}
@@ -1,5 +1,6 @@
package com.bms.price.mapper;
import java.math.BigDecimal;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.bms.price.domain.PrcPayBill;
@@ -63,8 +64,8 @@ public interface PrcPayBillMapper
*/
int refreshPayTotal(@Param("billIds") List<Long> billIds);
/** 把折成人民币后的应付总额和 ABCD 段合计写到主表,明细金额和币种不动。 */
int updateCnyPayTotal(PrcPayBill row);
/** 把折成人民币后的应付汇总写到主表,明细金额和币种不动。 */
int updateCnyPayTotal(@Param("billId") Long billId, @Param("payTotal") BigDecimal payTotal);
/** 订单还没有应付主表时补一行,总额随后按明细重算。单次不超过 1000 个订单。 */
int insertMissingPayBills(@Param("billIds") List<Long> billIds, @Param("operator") String operator);
@@ -16,6 +16,9 @@ public interface PrcSurchargeRelMapper
*/
public List<PrcSurchargeRel> selectPrcSurchargeRelList(PrcSurchargeRel rel);
/** 按套餐版本查销售附加费关联(产品或明细) */
public List<PrcSurchargeRel> selectSalesRelsByPsvId(@Param("psvId") Long psvId);
public List<PrcSurchargeRel> selectByDetailIdsAndPriceType(
@Param("detailIds") List<Long> detailIds,
@Param("priceType") String priceType);
@@ -2,7 +2,6 @@ package com.bms.price.service;
import java.util.List;
import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayOrderFeeBatch;
import com.bms.price.domain.PayOrderFeeBoard;
import com.bms.price.domain.PayOrderFeeLine;
import com.bms.price.domain.PayOrderQuery;
@@ -27,14 +26,6 @@ public interface IPayOrderListService
*/
PayOrderFeeLine addManualFee(String billId, PayOrderFeeLine line);
/**
* 给勾选的订单批量增加同一组手工费用。来源记 MANUAL,创建人是当前登录用户,并记新增日志。
*
* @param batch 订单和费用行
* @return 写入的费用条数
*/
int addManualFees(PayOrderFeeBatch batch);
/**
* 逻辑删除一条应付费用。已经进入应付账单的费用不能删。
*
@@ -10,7 +10,7 @@ public interface IPrcPayBillFeeService
{
/**
* 分批写入应付明细,并回写这些订单的应付总额。
* 明细每批最多 1000 条,金额和币种按原样写入 prc_pay_bill_fee。汇总时外币按汇率折成人民币,ABCD 段分别四舍五入到两位后写入 prc_pay_bill,应付总额取这四段之和。
* 明细每批最多 1000 条,金额和币种按原样写入 prc_pay_bill_fee。汇总时外币按汇率折成人民币,只回写 prc_pay_bill.pay_total。
*
* @param fees 本次新增的应付明细
*/
@@ -84,8 +84,8 @@ public interface IPrcPriceSetService
public List<PrcPriceSetDetail> selectDetailListByVersion(Long psvId);
/**
* 版本明细搜索下拉选项:按版本去重后的 产品/国家/分区 列表。
* 返回 { products: [{code,name}], countries: [{code,name}], zones: [{code,name}] }
* 版本明细搜索下拉选项:按版本去重后的 产品/国家/分区。
* products 项含 surcharges(轻量,供查看详情产品列表)。
*/
public Map<String, Object> selectDetailOptions(Long psvId);
@@ -55,5 +55,5 @@ public interface IPrcZoneService
/**
* 按打单产品同步 LABEL 邮编分区:仅覆盖本次出现的 zone,不碰其他产品/常规分区。
*/
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<String>> zonePostcodes);
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<PrcZoneDetail>> zonePostcodes);
}
@@ -698,7 +698,6 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
scId = fallback++;
}
row.setScId(scId);
row.setFeeLevel("4");
String userId = PayFeeMoney.userId();
row.setAmount(fee.getAmount());
row.setCurrency(fee.getCurrency());
@@ -10,7 +10,6 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -24,7 +23,6 @@ import com.bms.common.utils.uuid.IdUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayOrderFeeBatch;
import com.bms.price.domain.PayOrderFeeBoard;
import com.bms.price.domain.PrcPayBill;
import com.bms.price.domain.PayOrderFeeLine;
@@ -53,10 +51,6 @@ public class PayOrderListServiceImpl implements IPayOrderListService
private static final int MAX_LADING_NOS = 10;
private static final int MAX_BATCH_LINES = 20;
private static final AtomicLong MANUAL_SC_SEQ = new AtomicLong();
private static final Map<String, String> TITLES = new LinkedHashMap<>();
static
@@ -440,12 +434,67 @@ public class PayOrderListServiceImpl implements IPayOrderListService
public PayOrderFeeLine addManualFee(String billId, PayOrderFeeLine line)
{
PayOrderRow order = requireOrder(billId);
PayOrderFeeLine ready = checkedLine(line);
if (line == null)
{
throw new ServiceException("请填写费用");
}
String level = line.getLevel() == null ? "" : line.getLevel().trim();
if (!TITLES.containsKey(level))
{
throw new ServiceException("请选择费用阶段");
}
String feeName = firstText(line.getFeeName(), line.getFeeType());
if (feeName.isEmpty())
{
throw new ServiceException("请填写费用项");
}
if (feeName.length() > 100)
{
feeName = feeName.substring(0, 100);
}
String feeType = firstText(line.getFeeType(), "MANUAL");
if (feeType.length() > 30)
{
feeType = "MANUAL";
}
if (line.getAmount() == null)
{
throw new ServiceException("请填写金额");
}
String currency = firstText(line.getCurrency(), "CNY").toUpperCase();
if (currency.length() > 10)
{
throw new ServiceException("币种过长");
}
BigDecimal amount = line.getAmount().setScale(2, RoundingMode.HALF_UP);
if (amount.abs().compareTo(new BigDecimal("9999999999.99")) > 0)
{
throw new ServiceException("金额超出范围");
}
String remark = line.getRemark() == null ? null : line.getRemark().trim();
if (remark != null && remark.length() > 200)
{
throw new ServiceException("说明不能超过200字");
}
Long orderBillId = Long.valueOf(order.getBillId().trim());
String operator = operator();
String userId = PayFeeMoney.userId();
payBillMapper.insertMissingPayBills(List.of(orderBillId), operator());
payBillMapper.insertMissingPayBills(List.of(orderBillId), operator);
PrcPayBill payBill = payBillMapper.selectByBillId(orderBillId);
PrcPayBillFee fee = newManualFee(orderBillId, payBill == null ? null : payBill.getPayBillId(), ready, userId);
PrcPayBillFee fee = new PrcPayBillFee();
fee.setFeeId(UUID.randomUUID().toString());
fee.setBillId(orderBillId);
fee.setPayBillId(payBill == null ? null : payBill.getPayBillId());
fee.setFeeType(feeType);
fee.setFeeName(feeName);
fee.setScId(manualScId());
fee.setFeeLevel(level);
fee.setAmount(amount);
fee.setCurrency(currency);
fee.setRemark(remark == null || remark.isEmpty() ? null : remark);
fee.setFeeSource("MANUAL");
fee.setCreateBy(userId);
fee.setUpdateBy(userId);
payBillFeeMapper.insertManual(fee);
payBillFeeService.refreshTotals(List.of(orderBillId));
payBillFeeLogService.record(fee, PayBillFeeLogService.ADD);
@@ -453,34 +502,6 @@ public class PayOrderListServiceImpl implements IPayOrderListService
return toLine(saved == null ? fee : saved);
}
/**
* 同一组费用写到每一票勾选订单上。应付总额和 ABCD 段在写入后一起重算。
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int addManualFees(PayOrderFeeBatch batch)
{
List<Long> billIds = batchBillIds(batch);
List<PayOrderFeeLine> lines = batchLines(batch);
List<PayOrderRow> orders = payOrderListMapper.selectByBillIds(billIds);
if (orders == null || orders.size() != billIds.size())
{
throw new ServiceException("有订单不在应付列表中,请重新勾选");
}
String userId = PayFeeMoney.userId();
List<PrcPayBillFee> fees = new ArrayList<>(billIds.size() * lines.size());
for (Long billId : billIds)
{
for (PayOrderFeeLine line : lines)
{
fees.add(newManualFee(billId, null, line, userId));
}
}
payBillFeeService.insertBatchAndRefreshTotals(fees);
payBillFeeLogService.record(fees, PayBillFeeLogService.ADD);
return fees.size();
}
/**
* 逻辑删除一条费用,并按剩余未删除明细重算应付总额。
*
@@ -558,144 +579,10 @@ public class PayOrderListServiceImpl implements IPayOrderListService
return fallback == null ? "" : fallback.trim();
}
/** 校验并收成可落库的一行。金额保留三位,和费用明细的小数位一致。 */
private PayOrderFeeLine checkedLine(PayOrderFeeLine line)
{
if (line == null)
{
throw new ServiceException("请填写费用");
}
String level = line.getLevel() == null ? "" : line.getLevel().trim();
if (!TITLES.containsKey(level))
{
throw new ServiceException("请选择费用阶段");
}
String feeName = firstText(line.getFeeName(), line.getFeeType());
if (feeName.isEmpty())
{
throw new ServiceException("请填写费用项");
}
if (feeName.length() > 100)
{
feeName = feeName.substring(0, 100);
}
String feeType = firstText(line.getFeeType(), "MANUAL");
if (feeType.length() > 30)
{
feeType = "MANUAL";
}
if (line.getAmount() == null)
{
throw new ServiceException("请填写金额");
}
String currency = firstText(line.getCurrency(), "CNY").toUpperCase(Locale.ROOT);
if (currency.length() > 10)
{
throw new ServiceException("币种过长");
}
BigDecimal amount = line.getAmount().setScale(3, RoundingMode.HALF_UP);
if (amount.abs().compareTo(new BigDecimal("9999999999.999")) > 0)
{
throw new ServiceException("金额超出范围");
}
String remark = line.getRemark() == null ? null : line.getRemark().trim();
if (remark != null && remark.length() > 200)
{
throw new ServiceException("说明不能超过200字");
}
PayOrderFeeLine ready = new PayOrderFeeLine();
ready.setLevel(level);
ready.setFeeName(feeName);
ready.setFeeType(feeType);
ready.setAmount(amount);
ready.setCurrency(currency);
ready.setRemark(remark == null || remark.isEmpty() ? null : remark);
return ready;
}
private List<Long> batchBillIds(PayOrderFeeBatch batch)
{
if (batch == null || batch.getBillIds() == null || batch.getBillIds().isEmpty())
{
throw new ServiceException("请勾选订单");
}
LinkedHashSet<Long> ids = new LinkedHashSet<>();
for (String raw : batch.getBillIds())
{
if (raw == null || raw.isBlank())
{
continue;
}
try
{
ids.add(Long.valueOf(raw.trim()));
}
catch (NumberFormatException ex)
{
throw new ServiceException("订单编号不正确");
}
}
if (ids.isEmpty())
{
throw new ServiceException("请勾选订单");
}
if (ids.size() > MAX_ORDER_NOS)
{
throw new ServiceException("一次最多选择" + MAX_ORDER_NOS + "个订单");
}
return new ArrayList<>(ids);
}
private List<PayOrderFeeLine> batchLines(PayOrderFeeBatch batch)
{
if (batch.getFees() == null || batch.getFees().isEmpty())
{
throw new ServiceException("请填写费用");
}
if (batch.getFees().size() > MAX_BATCH_LINES)
{
throw new ServiceException("一次最多增加" + MAX_BATCH_LINES + "条费用");
}
List<PayOrderFeeLine> lines = new ArrayList<>(batch.getFees().size());
for (PayOrderFeeLine line : batch.getFees())
{
if (line != null && (line.getLevel() == null || line.getLevel().isBlank()))
{
line.setLevel("4");
}
lines.add(checkedLine(line));
}
return lines;
}
/** 手工费用。创建人和更新人记当前登录用户主键,来源固定为手工。 */
private static PrcPayBillFee newManualFee(Long billId, String payBillId, PayOrderFeeLine line, String userId)
{
PrcPayBillFee fee = new PrcPayBillFee();
fee.setFeeId(UUID.randomUUID().toString());
fee.setBillId(billId);
fee.setPayBillId(payBillId);
fee.setFeeType(line.getFeeType());
fee.setFeeName(line.getFeeName());
fee.setScId(manualScId());
fee.setFeeLevel(line.getLevel());
fee.setAmount(line.getAmount());
fee.setCurrency(line.getCurrency());
fee.setRemark(line.getRemark());
fee.setFeeSource("MANUAL");
fee.setIsDeleted("0");
fee.setCreateBy(userId);
fee.setUpdateBy(userId);
return fee;
}
/** 手工费用用负数序号,避免和同一费用项的计算费用撞上唯一键。 */
private static long manualScId()
{
long tick = MANUAL_SC_SEQ.updateAndGet(current -> {
long next = System.nanoTime();
return next > current ? next : current + 1L;
});
long tick = System.nanoTime();
if (tick == Long.MIN_VALUE)
{
return -1L;
@@ -493,16 +493,9 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
TmsPriceQuoteResult result = toResult(bill, incomeBillFeeMapper.selectByBillId(bill.getBillId()),
payBillFeeMapper.selectByBillId(bill.getBillId()));
PrcPayBill payBill = payBillMapper.selectByBillId(bill.getBillId());
if (payBill != null)
if (payBill != null && payBill.getPayTotal() != null)
{
if (payBill.getPayTotal() != null)
{
result.setPayTotal(payBill.getPayTotal());
}
result.setAmountA(payBill.getAmountA());
result.setAmountB(payBill.getAmountB());
result.setAmountC(payBill.getAmountC());
result.setAmountD(payBill.getAmountD());
result.setPayTotal(payBill.getPayTotal());
}
return result;
}
@@ -2088,9 +2081,17 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
{
applyProductCodeMapping(bill, request);
}
// 已有真实销售产品名时不覆盖;仅缺失或与编码相同时才用报价结果补全
if (result != null && StringUtils.isNotEmpty(result.getProductName()))
{
bill.setProductName(result.getProductName());
String existing = StringUtils.trim(bill.getProductName());
String code = StringUtils.trim(bill.getProductCode());
boolean missingOrCodeOnly = StringUtils.isEmpty(existing)
|| (StringUtils.isNotEmpty(code) && existing.equalsIgnoreCase(code));
if (missingOrCodeOnly)
{
bill.setProductName(result.getProductName());
}
}
if (StringUtils.isEmpty(bill.getCountryCode()) && result != null)
{
@@ -10,7 +10,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bms.common.utils.SecurityUtils;
import com.bms.price.domain.PrcPayBill;
import com.bms.price.domain.PrcPayBillFee;
import com.bms.price.mapper.PrcPayBillFeeMapper;
import com.bms.price.mapper.PrcPayBillMapper;
@@ -84,13 +83,13 @@ public class PrcPayBillFeeServiceImpl implements IPrcPayBillFeeService
}
}
/** 不改 prc_pay_bill_fee。按计费日汇率把明细折成人民币后,ABCD 段分别四舍五入到两位,应付总额取这四段之和,写入 prc_pay_bill。 */
/** 不改 prc_pay_bill_fee。按计费日汇率把明细折成人民币后相加,四舍五入到两位,只写入 prc_pay_bill.pay_total。 */
private void writeCnyTotals(List<Long> billIds)
{
Map<Long, BigDecimal[]> sums = new LinkedHashMap<>();
Map<Long, BigDecimal> sums = new LinkedHashMap<>();
for (Long billId : billIds)
{
sums.put(billId, new BigDecimal[] { BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO });
sums.put(billId, BigDecimal.ZERO);
}
List<PrcPayBillFee> fees = payBillFeeMapper.selectOpenFees(billIds);
if (fees != null)
@@ -101,52 +100,20 @@ public class PrcPayBillFeeServiceImpl implements IPrcPayBillFeeService
{
continue;
}
BigDecimal[] bucket = sums.get(fee.getBillId());
if (bucket == null)
{
continue;
}
BigDecimal cny = payFeeMoney.toCny(fee.getAmount(), fee.getCurrency(), fee.getBizDate());
if (cny == null)
{
continue;
}
int segment = segmentIndex(fee.getFeeLevel());
bucket[segment] = bucket[segment].add(cny);
sums.merge(fee.getBillId(), cny, BigDecimal::add);
}
}
for (Map.Entry<Long, BigDecimal[]> entry : sums.entrySet())
for (Map.Entry<Long, BigDecimal> entry : sums.entrySet())
{
BigDecimal[] bucket = entry.getValue();
PrcPayBill row = new PrcPayBill();
row.setBillId(entry.getKey());
row.setAmountA(PayFeeMoney.total(bucket[0]));
row.setAmountB(PayFeeMoney.total(bucket[1]));
row.setAmountC(PayFeeMoney.total(bucket[2]));
row.setAmountD(PayFeeMoney.total(bucket[3]));
row.setPayTotal(row.getAmountA().add(row.getAmountB()).add(row.getAmountC()).add(row.getAmountD()));
payBillMapper.updateCnyPayTotal(row);
payBillMapper.updateCnyPayTotal(entry.getKey(), PayFeeMoney.total(entry.getValue()));
}
}
/** 0A 1B 2C,其余含未标阶段的尾程计算费用归到 D。 */
private static int segmentIndex(String feeLevel)
{
if ("1".equals(feeLevel))
{
return 0;
}
if ("2".equals(feeLevel))
{
return 1;
}
if ("3".equals(feeLevel))
{
return 2;
}
return 3;
}
private static String currentOperator()
{
try
@@ -994,13 +994,87 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
zones.putIfAbsent(zoneCode != null ? zoneCode : zoneName, item);
}
}
// 补全套餐产品表(无明细时也能展示)
PrcPriceSetProduct pq = new PrcPriceSetProduct();
pq.setPsvId(psvId);
List<PrcPriceSetProduct> setProducts = setProductMapper.selectPrcPriceSetProductList(pq);
if (setProducts != null)
{
for (PrcPriceSetProduct sp : setProducts)
{
if (sp == null || StringUtils.isBlank(sp.getProductCode()))
{
continue;
}
Map<String, String> item = new LinkedHashMap<String, String>();
item.put("code", sp.getProductCode());
item.put("name", StringUtils.isNotBlank(sp.getProductName()) ? sp.getProductName() : sp.getProductCode());
products.putIfAbsent(sp.getProductCode(), item);
}
}
// 产品列表轻量挂附加费,避免查看详情拉整版明细
Map<String, List<PrcSurchargeRel>> scByProduct = loadSalesSurchargesByProduct(psvId);
List<Map<String, Object>> productRows = new ArrayList<Map<String, Object>>();
for (Map<String, String> p : products.values())
{
Map<String, Object> row = new LinkedHashMap<String, Object>();
row.put("code", p.get("code"));
row.put("name", p.get("name"));
String code = p.get("code");
List<PrcSurchargeRel> sc = code == null ? null : scByProduct.get(code);
row.put("surcharges", sc != null ? sc : new ArrayList<PrcSurchargeRel>());
productRows.add(row);
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("products", new ArrayList<Map<String, String>>(products.values()));
result.put("products", productRows);
result.put("countries", new ArrayList<Map<String, String>>(countries.values()));
result.put("zones", new ArrayList<Map<String, String>>(zones.values()));
return result;
}
/** 按产品代码汇总版本销售附加费(scId 去重) */
private Map<String, List<PrcSurchargeRel>> loadSalesSurchargesByProduct(Long psvId)
{
Map<String, List<PrcSurchargeRel>> out = new LinkedHashMap<String, List<PrcSurchargeRel>>();
if (psvId == null)
{
return out;
}
List<PrcSurchargeRel> rels = surchargeRelMapper.selectSalesRelsByPsvId(psvId);
if (rels == null || rels.isEmpty())
{
return out;
}
Map<String, Map<Long, PrcSurchargeRel>> dedupe = new LinkedHashMap<String, Map<Long, PrcSurchargeRel>>();
for (PrcSurchargeRel rel : rels)
{
if (rel == null || rel.getScId() == null)
{
continue;
}
String code = StringUtils.trim(rel.getProductCode());
if (StringUtils.isEmpty(code))
{
continue;
}
Map<Long, PrcSurchargeRel> bySc = dedupe.get(code);
if (bySc == null)
{
bySc = new LinkedHashMap<Long, PrcSurchargeRel>();
dedupe.put(code, bySc);
}
if (!bySc.containsKey(rel.getScId()))
{
bySc.put(rel.getScId(), rel);
}
}
for (Map.Entry<String, Map<Long, PrcSurchargeRel>> e : dedupe.entrySet())
{
out.put(e.getKey(), new ArrayList<PrcSurchargeRel>(e.getValue().values()));
}
return out;
}
/** 为一页明细挂载 SALES 附加费关联(detail_id=psd_id)。 */
private void fillDetailSurcharges(List<PrcPriceSetDetail> details)
{
@@ -3670,6 +3744,7 @@ public class PrcPriceSetServiceImpl implements IPrcPriceSetService
version.setProducts(products == null ? new ArrayList<PrcPriceSetProduct>() : products);
// 明细 + SALES 附加费关联按需加载(编辑价格/明细抽屉)
version.setDetails(new ArrayList<PrcPriceSetDetail>());
version.setDetailCount(Integer.valueOf(detailMapper.countByPsvId(version.getPsvId())));
}
private PrcPriceSetVersion pickCurrentVersion(List<PrcPriceSetVersion> versions)
@@ -219,12 +219,20 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override
public int insertPrcZoneDetail(PrcZoneDetail detail)
{
if (detail != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.insertPrcZoneDetail(detail);
}
@Override
public int updatePrcZoneDetail(PrcZoneDetail detail)
{
if (detail != null && detail.getMatchType() != null)
{
detail.setMatchType(PrcZoneDetail.normalizeMatchType(detail.getMatchType()));
}
return detailMapper.updatePrcZoneDetail(detail);
}
@@ -281,7 +289,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
unmatched.add(item.countryHint + "(" + item.sheetName + ")");
continue;
}
int[] counts = replaceRegionZones(region, zonePostcodes);
int[] counts = replaceRegionZones(region, zonePostcodes, item.matchType);
countryCount += 1;
zoneCount += counts[0];
detailCount += counts[1];
@@ -398,6 +406,10 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode.trim());
if (detail.getMatchType() == null || detail.getMatchType().isBlank())
{
detail.setMatchType(PrcZoneDetail.MATCH_FULL);
}
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -418,7 +430,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
@Override
@Transactional(rollbackFor = Exception.class)
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<String>> zonePostcodes)
public String syncLabelProductZones(Long productId, String countryCode2, Map<String, List<PrcZoneDetail>> zonePostcodes)
{
if (productId == null)
{
@@ -456,9 +468,9 @@ public class PrcZoneServiceImpl implements IPrcZoneService
}
int zoneUpsert = 0;
int detailInserted = 0;
List<Map.Entry<String, List<String>>> entries = new ArrayList<>(zonePostcodes.entrySet());
List<Map.Entry<String, List<PrcZoneDetail>>> entries = new ArrayList<>(zonePostcodes.entrySet());
entries.sort(Comparator.comparingInt(e -> extractZoneSort(e.getKey())));
for (Map.Entry<String, List<String>> entry : entries)
for (Map.Entry<String, List<PrcZoneDetail>> entry : entries)
{
String label = StringUtils.trim(entry.getKey());
if (StringUtils.isEmpty(label))
@@ -501,21 +513,26 @@ public class PrcZoneServiceImpl implements IPrcZoneService
detailMapper.deletePrcZoneDetailByZoneId(zone.getZoneId());
}
zoneUpsert++;
Set<String> uniquePostcodes = new LinkedHashSet<String>();
Map<String, PrcZoneDetail> unique = new LinkedHashMap<String, PrcZoneDetail>();
if (entry.getValue() != null)
{
uniquePostcodes.addAll(entry.getValue());
for (PrcZoneDetail item : entry.getValue())
{
if (item == null || StringUtils.isEmpty(item.getPostcode()))
{
continue;
}
String pc = item.getPostcode().trim();
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(pc);
detail.setMatchType(PrcZoneDetail.normalizeMatchType(item.getMatchType()));
unique.put(pc.toUpperCase(Locale.ROOT), detail);
}
}
List<PrcZoneDetail> batch = new ArrayList<>(BATCH_SIZE);
for (String postcode : uniquePostcodes)
for (PrcZoneDetail detail : unique.values())
{
if (StringUtils.isEmpty(postcode))
{
continue;
}
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode.trim());
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -534,11 +551,17 @@ public class PrcZoneServiceImpl implements IPrcZoneService
}
private int[] replaceRegionZones(BmsRegion region, Map<String, List<String>> zonePostcodes)
{
return replaceRegionZones(region, zonePostcodes, PrcZoneDetail.MATCH_FULL);
}
private int[] replaceRegionZones(BmsRegion region, Map<String, List<String>> zonePostcodes, String matchType)
{
if (StringUtils.isEmpty(region.getCountryCode2()))
{
throw new ServiceException(MessageUtils.message("price.zone.countryCode.empty"));
}
matchType = PrcZoneDetail.normalizeMatchType(matchType);
Long regionId = region.getRegionId();
detailMapper.deletePrcZoneDetailByRegionId(regionId);
zoneMapper.deletePrcZoneByRegionId(regionId);
@@ -570,6 +593,7 @@ public class PrcZoneServiceImpl implements IPrcZoneService
PrcZoneDetail detail = new PrcZoneDetail();
detail.setZoneId(zone.getZoneId());
detail.setPostcode(postcode);
detail.setMatchType(matchType);
batch.add(detail);
if (batch.size() >= BATCH_SIZE)
{
@@ -592,12 +616,19 @@ public class PrcZoneServiceImpl implements IPrcZoneService
private final String sheetName;
private final String countryHint;
private final Map<String, List<String>> zonePostcodes;
private final String matchType;
private SheetImport(String sheetName, String countryHint, Map<String, List<String>> zonePostcodes)
{
this(sheetName, countryHint, zonePostcodes, PrcZoneDetail.MATCH_FULL);
}
private SheetImport(String sheetName, String countryHint, Map<String, List<String>> zonePostcodes, String matchType)
{
this.sheetName = sheetName;
this.countryHint = countryHint;
this.zonePostcodes = zonePostcodes;
this.matchType = PrcZoneDetail.normalizeMatchType(matchType);
}
}
@@ -646,7 +677,11 @@ public class PrcZoneServiceImpl implements IPrcZoneService
{
countryHint = sheetName;
}
list.add(new SheetImport(sheetName, countryHint, parsed));
// 英国/偏远/邮编开头类表才落 PREFIX;其余默认 FULL
String matchType = (sheetName.contains("英国") || sheetName.contains("邮编开头")
|| sheetName.contains("偏远") || sheetName.contains("加拿大"))
? PrcZoneDetail.MATCH_PREFIX : PrcZoneDetail.MATCH_FULL;
list.add(new SheetImport(sheetName, countryHint, parsed, matchType));
}
return list;
}
@@ -73,6 +73,7 @@ import com.bms.price.search.IBillSearchStore;
import com.bms.price.service.ILblProductService;
import com.bms.price.service.IPayProductService;
import com.bms.price.label.LblCostCalculator;
import com.bms.price.label.LblSurchargeRules;
import com.bms.price.label.LblProductPayAdapter;
import com.bms.price.domain.LblFeeType;
import com.bms.price.domain.LblProduct;
@@ -739,7 +740,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
throw ex;
}
PayOrderCostResult cost = LblCostCalculator.calculate(lblProduct, weight, length, width, height,
request.getDestPostcode(), freightZone, bizDate, orderStatus);
request.getDestPostcode(), freightZone, bizDate, orderStatus, countryCode, countryName);
if (cost == null || cost.getFees() == null || cost.getFees().isEmpty())
{
if (request instanceof TmsPriceBillRequest)
@@ -779,6 +780,12 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return countryFreight.get(0);
}
List<String> candidates = countryFreight.isEmpty() ? zoneNames : countryFreight;
// 优先:派送费重量段上的邮编前缀(如 CTT 加那利 35/38)
String byParam = labelFreightZoneByPostcodeParam(product, cc, destPostcode, candidates);
if (byParam != null)
{
return byParam;
}
if (product == null || product.getProductId() == null)
{
throw new ServiceException("邮编未匹配到产品分区");
@@ -787,6 +794,13 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
product.getProductId(), normalizePostcode(destPostcode));
if (resolved == null)
{
// 未命中偏远前缀时,若价卡有大陆列则走大陆(Evri UK Mainland)
PayZoneMatcher.Decision mainland = PayZoneMatcher.resolve(candidates, java.util.Collections.emptyList(),
destPostcode);
if (mainland != null && mainland.getZoneName() != null)
{
return mainland.getZoneName();
}
throw new ServiceException("邮编未匹配到产品分区");
}
String mapped = PayZoneMatcher.mapRegion(candidates, resolved.getZoneCode());
@@ -803,6 +817,69 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return mapped;
}
/**
* 按派送费重量段 postcodeParam(如 35,38)命中分区名。
*/
private static String labelFreightZoneByPostcodeParam(LblProduct product, String countryCode, String postcode,
List<String> candidates)
{
if (product == null || product.getWeightBands() == null || StringUtils.isEmpty(postcode))
{
return null;
}
String best = null;
int bestScore = -1;
for (LblWeightBand band : product.getWeightBands())
{
if (band == null)
{
continue;
}
String ft = band.getFeeType();
if (ft != null && !ft.isEmpty() && !LblFeeType.FREIGHT.equals(ft))
{
continue;
}
if (StringUtils.isNotEmpty(countryCode) && !bandCountryMatches(band.getCountryCode(), countryCode))
{
continue;
}
String param = band.getPostcodeParam();
if (StringUtils.isEmpty(param))
{
continue;
}
if (!LblSurchargeRules.matchesPostcode(param, postcode) && !PaySurchargeRules.matchesPostcode(param, postcode))
{
continue;
}
String zone = band.getZoneName();
if (zone == null || zone.isBlank())
{
continue;
}
zone = zone.trim();
if (candidates != null && !candidates.isEmpty())
{
for (String c : candidates)
{
if (zone.equals(c) || PayZoneMatcher.sameZone(c, zone))
{
zone = c;
break;
}
}
}
int score = param.replace(",", "").length();
if (score > bestScore)
{
bestScore = score;
best = zone;
}
}
return best;
}
private static List<String> labelBandZoneNames(LblProduct product)
{
LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -825,7 +902,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
return new ArrayList<String>(names);
}
/** 该国家下运费(FREIGHT)分区列名;偏远行不算入。 */
/** 该国家下运费(FREIGHT)分区列名(含带邮编前缀的岛屿派送费)。 */
private static List<String> labelFreightZonesForCountry(LblProduct product, String countryCode)
{
LinkedHashSet<String> names = new LinkedHashSet<String>();
@@ -980,8 +1057,8 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
{
incomeTotal = freightAmount.add(registrationFee).add(surchargeAmount).setScale(2, rm);
}
String labelProductName = StringUtils.isNotEmpty(product.getProductName())
? product.getProductName() : productName;
// 保留订单/上游销售产品名,不用打单价卡产品名覆盖(含义不同)
String keepProductName = StringUtils.isNotEmpty(productName) ? productName : product.getProductName();
TmsPriceQuoteResult r = new TmsPriceQuoteResult();
r.setMatchSource(SRC_LABEL);
r.setMatchMessage("hit label package pay card V"
@@ -990,7 +1067,7 @@ public class TmsPriceQuoteServiceImpl implements ITmsPriceQuoteService
r.setVersionNo(product.getVersionNo() == null ? null : ("V" + product.getVersionNo()));
r.setCustomerId(bind.getCustomerId());
r.setProductCode(productCode);
r.setProductName(labelProductName);
r.setProductName(keepProductName);
r.setCountryCode(countryCode);
r.setCountryName(countryName);
r.setWeight(weight);
@@ -40,6 +40,8 @@ public class ArBillGenerateRequest
@JsonDeserialize(using = StrictDateDeserializer.class)
private Date billDate;
private String currency = "CNY";
/** 收款账户配置 ID;旧调用方未传时沿用币种默认账户。 */
private Long bankAccountId;
/** 订单号、运单号或转单号原始输入,生成时会拆分并再次校验筛选条件。 */
private String orderOrTrackingNo;
private String bankAccountName;
@@ -7,7 +7,12 @@ import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -351,6 +356,40 @@ public abstract class ArBillWorkbookSupport implements ArBillWorkbookWriter {
return detail == null ? null : detail.getRegistrationFee();
}
protected String exportReceiveTimeRange(Map<String, Object> receiveTimeRange) {
return exportReceiveTimeRange(receiveTimeRange, "yyyy-MM-dd", " 至 ");
}
/** 所有账单模板使用当前账单明细的收货日期范围,缺失时留空。 */
protected String exportReceiveTimeRange(Map<String, Object> receiveTimeRange, String pattern, String separator) {
if (receiveTimeRange == null) {
return "";
}
String start = formatReceiveDate(receiveTimeRange.get("minReceiveTime"), pattern);
String end = formatReceiveDate(receiveTimeRange.get("maxReceiveTime"), pattern);
return StringUtils.isEmpty(start) || StringUtils.isEmpty(end) ? "" : start + separator + end;
}
private String formatReceiveDate(Object value, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
if (value instanceof LocalDateTime) {
return ((LocalDateTime) value).toLocalDate().format(formatter);
}
if (value instanceof LocalDate) {
return ((LocalDate) value).format(formatter);
}
if (value instanceof java.sql.Date) {
return ((java.sql.Date) value).toLocalDate().format(formatter);
}
if (value instanceof Date) {
return new SimpleDateFormat(pattern).format((Date) value);
}
if (value == null) {
return "";
}
throw new IllegalArgumentException("不支持的收货时间类型: " + value.getClass().getName());
}
protected String exportBankAccountNo(String value) {
if (StringUtils.isEmpty(value)) {
return "";
@@ -24,4 +24,5 @@ public class ArBillWorkbookWriters {
public boolean isSummary(ArExportTemplate template) {
return SUMMARY_TEMPLATE_CODE.equals(template.getTemplateCode());
}
}
@@ -8,9 +8,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -534,34 +531,6 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
return result.toString();
}
private String exportReceiveTimeRange(Map<String, Object> receiveTimeRange) {
if (receiveTimeRange == null) {
return "";
}
String start = formatReceiveDate(receiveTimeRange.get("minReceiveTime"));
String end = formatReceiveDate(receiveTimeRange.get("maxReceiveTime"));
return StringUtils.isEmpty(start) || StringUtils.isEmpty(end) ? "" : start + " 至 " + end;
}
private String formatReceiveDate(Object value) {
if (value instanceof LocalDateTime) {
return ((LocalDateTime) value).toLocalDate().toString();
}
if (value instanceof LocalDate) {
return value.toString();
}
if (value instanceof java.sql.Date) {
return ((java.sql.Date) value).toLocalDate().toString();
}
if (value instanceof Date) {
return new SimpleDateFormat("yyyy-MM-dd").format((Date) value);
}
if (value == null) {
return "";
}
throw new IllegalArgumentException("不支持的收货时间类型: " + value.getClass().getName());
}
private String exportFormula(ArBillDetail detail) {
String formula = joinFeeText(detail.getFees(), true);
if (!StringUtils.isEmpty(formula)) {
@@ -9,7 +9,6 @@ import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -26,6 +25,8 @@ import com.bms.receivable.domain.ArBillDetail;
import com.bms.receivable.domain.ArBillDetailFee;
import com.bms.receivable.domain.ArExportTemplate;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
@@ -55,7 +56,10 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
Path detailXml = Files.createTempFile("ar-bill-summary-details-", ".xml");
try (InputStream input = openTemplateStream(template); XSSFWorkbook workbook = new XSSFWorkbook(input)) {
validateTemplate(workbook);
prepareTemplate(workbook, bill);
String receiveTimePeriod = exportReceiveTimeRange(
detailMapper.selectReceiveTimeRangeByBillId(bill.getArBillId()), "yyyyMMdd", "-");
prepareTemplate(workbook, bill, receiveTimePeriod);
SummaryStyles summaryStyles = createSummaryStyles(workbook);
DetailStyles detailStyles = createDetailStyles(workbook);
byte[] skeleton = serialize(workbook);
String summaryPath = partPath(workbook.getSheetAt(0));
@@ -92,7 +96,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) {
output.putNextEntry(new ZipEntry(entry.getName()));
if (summaryPath.equals(entry.getName())) {
writeSummary(summary, bill, groups, result.amount(), output);
writeSummary(summary, bill, groups, result.amount(), receiveTimePeriod, summaryStyles, output);
} else if (detailPath.equals(entry.getName())) {
Files.copy(detailXml, output);
} else {
@@ -133,7 +137,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
return row;
}
private void prepareTemplate(XSSFWorkbook workbook, ArBill bill) throws IOException {
private void prepareTemplate(XSSFWorkbook workbook, ArBill bill, String receiveTimePeriod) throws IOException {
String currency = StringUtils.isEmpty(bill.getCurrency()) ? "CNY" : bill.getCurrency();
String company = StringUtils.isEmpty(bill.getBankAccountName())
? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName();
@@ -146,7 +150,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
textCell(summary, 11, 1, exportBankAccountNo(bill.getBankAccountNo()));
textCell(summary, 12, 1, bill.getBankName());
textCell(detail, 2, 1, bill.getCustomerName());
textCell(detail, 2, 18, billPeriod(bill));
textCell(detail, 2, 18, receiveTimePeriod);
for (int column : new int[]{11, 12, 13, 15, 16}) {
XSSFCell header = detail.getRow(3).getCell(column);
header.setCellValue(header.getStringCellValue().replace("CNY", currency));
@@ -155,10 +159,11 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
XSSFCell cell = detail.getRow(4).getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK);
boolean identifier = column == 0 || column == 2 || column == 3 || column == 6;
boolean money = column == 10 || column == 13 || column == 14 || column == 15 || column == 16;
if (!identifier && !money) continue;
boolean receiveDate = column == 1;
if (!identifier && !money && !receiveDate) continue;
XSSFCellStyle style = workbook.createCellStyle();
style.cloneStyleFrom(cell.getCellStyle());
String format = identifier ? "@" : "0.00";
String format = receiveDate ? "yyyy/mm/dd" : identifier ? "@" : "0.00";
style.setDataFormat(workbook.createDataFormat().getFormat(format));
cell.setCellStyle(style);
}
@@ -190,7 +195,28 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
failed[column] = Short.toUnsignedInt(style.getIndex());
}
return new DetailStyles(normal, failed, workbook.getSheetAt(1).getRow(4).getHeightInPoints());
return new DetailStyles(normal, failed, workbook.getSheetAt(1).getRow(4).getHeightInPoints(), workbook.isDate1904());
}
/** 产品行之间不画网格线;最后一行沿用模板底边,组成完整外框。 */
private SummaryStyles createSummaryStyles(XSSFWorkbook workbook) throws IOException {
XSSFRow source = requireRow(workbook.getSheetAt(0), SUMMARY_START_ROW - 1);
int[] normal = new int[7];
int[] last = new int[7];
for (int column = 0; column < normal.length; column++) {
XSSFCellStyle original = source.getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellStyle();
XSSFCellStyle lastStyle = workbook.createCellStyle();
lastStyle.cloneStyleFrom(original);
lastStyle.setBorderTop(BorderStyle.NONE);
if (column > 0) lastStyle.setBorderLeft(BorderStyle.NONE);
if (column < normal.length - 1) lastStyle.setBorderRight(BorderStyle.NONE);
last[column] = Short.toUnsignedInt(lastStyle.getIndex());
XSSFCellStyle normalStyle = workbook.createCellStyle();
normalStyle.cloneStyleFrom(lastStyle);
normalStyle.setBorderBottom(BorderStyle.NONE);
normal[column] = Short.toUnsignedInt(normalStyle.getIndex());
}
return new SummaryStyles(normal, last);
}
private DetailResult writeDetails(SheetXml sheet, ArBill bill, OutputStream output,
@@ -235,11 +261,16 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
}
private String detailRow(int rowNumber, ArBill bill, ArBillDetail detail,
DetailAmounts amounts, DetailStyles styles) {
DetailAmounts amounts, DetailStyles styles) throws IOException {
String failure = exportBillingFailDescription(detail.getBillingFailStatus());
Double receiveTime = detail.getReceiveTime() == null ? null
: DateUtil.getExcelDate(detail.getReceiveTime(), styles.use1904());
if (receiveTime != null && !DateUtil.isValidExcelDate(receiveTime)) {
throw new IOException("账单明细收货时间超出 Excel 日期范围,请检查账单");
}
Object[] values = {
bill.getCustomerCode(),
detail.getReceiveTime() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(detail.getReceiveTime()),
receiveTime,
detail.getTransferNo(), detail.getTrackingNo(),
StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(),
StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(),
@@ -305,17 +336,19 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
}
private void writeSummary(SheetXml sheet, ArBill bill, Map<String, ProductSummary> groups,
BigDecimal total, OutputStream output) throws IOException {
BigDecimal total, String receiveTimePeriod, SummaryStyles styles,
OutputStream output) throws IOException {
writeUtf8(output, sheet.prefix());
for (int row = 1; row <= 3; row++) writeUtf8(output, sheet.rows().get(row));
int rowNumber = SUMMARY_START_ROW;
for (ProductSummary product : groups.values()) {
String row = shiftRowXml(sheet.rows().get(4), rowNumber);
Object[] values = {rowNumber - 3, bill.getCustomerName(), product.name, billPeriod(bill),
int[] rowStyles = rowNumber == SUMMARY_START_ROW + groups.size() - 1 ? styles.last() : styles.normal();
Object[] values = {rowNumber - 3, bill.getCustomerName(), product.name, receiveTimePeriod,
product.amount, bill.getCurrency(), SUMMARY_REMARK};
for (int index = 0; index < values.length; index++) {
row = replaceCellXml(row, (char) ('A' + index) + String.valueOf(rowNumber),
values[index], values[index] instanceof Number);
values[index], values[index] instanceof Number, rowStyles[index]);
}
writeUtf8(output, row);
rowNumber++;
@@ -356,12 +389,6 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
return FILTER.matcher(suffix).replaceAll("$1" + range + "$2");
}
private String billPeriod(ArBill bill) {
if (bill.getBillPeriodStart() == null || bill.getBillPeriodEnd() == null) return "";
SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
return date.format(bill.getBillPeriodStart()) + "-" + date.format(bill.getBillPeriodEnd());
}
private String partPath(XSSFSheet sheet) {
return sheet.getPackagePart().getPartName().getName().substring(1);
}
@@ -390,7 +417,8 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
private record SheetXml(String prefix, Map<Integer, String> rows, String suffix) { }
private record DetailResult(int count, int lastRow, BigDecimal amount) { }
private record DetailStyles(int[] normal, int[] failed, float rowHeight) { }
private record SummaryStyles(int[] normal, int[] last) { }
private record DetailStyles(int[] normal, int[] failed, float rowHeight, boolean use1904) { }
private record DetailAmounts(BigDecimal freight, BigDecimal processing, BigDecimal remote,
BigDecimal surcharge, BigDecimal romania, BigDecimal total) { }
@@ -42,6 +42,8 @@ public interface IArBillService
List<ArBankAccount> selectEnabledBankAccounts(String currency);
List<ArBankAccount> selectMaskedBankAccounts(String currency);
List<PrcOrderBill> previewBill(ArBillGenerateQuery query);
List<PrcOrderBill> previewBill(ArBillGenerateQuery query, ArBillRowScope scope);
@@ -261,6 +261,13 @@ public class ArBillServiceImpl implements IArBillService {
return accounts;
}
@Override
public List<ArBankAccount> selectMaskedBankAccounts(String currency) {
List<ArBankAccount> accounts = selectEnabledBankAccounts(currency);
accounts.forEach(account -> account.setAccountNo(maskAccount(account.getAccountNo())));
return accounts;
}
/**
* 分页预览可生成订单;多个订单号、运单号或转单号按 OR 条件精确匹配。
*/
@@ -383,10 +390,16 @@ public class ArBillServiceImpl implements IArBillService {
if (generatingBill != null) {
throw new ServiceException("该客户当前账期已有账单正在生成,请稍后再试");
}
ArBankAccount bankAccount = bankAccountMapper.selectDefaultByCurrency(currency);
ArBankAccount bankAccount = request.getBankAccountId() == null
? bankAccountMapper.selectDefaultByCurrency(currency)
: bankAccountMapper.selectEnabledById(request.getBankAccountId());
if (bankAccount == null) {
throw failure(null, ArLogObjectType.BILL, "", ArLogOperationType.GENERATE, null,
"未配置 " + currency + " 币种的公司默认收款账户,请先完成收款账户配置", operator, requestId);
request.getBankAccountId() == null ? "未配置 " + currency + " 币种的公司默认收款账户,请先完成收款账户配置"
: "所选收款账户不存在或已停用,请重新选择", operator, requestId);
}
if (!currency.equalsIgnoreCase(bankAccount.getCurrency())) {
throw new ServiceException("所选收款账户币种与账单币种不一致,请重新选择");
}
Date now = new Date();
@@ -1359,7 +1372,8 @@ public class ArBillServiceImpl implements IArBillService {
private String maskAccount(String value) {
if (StringUtils.isEmpty(value)) return "";
return value.length() <= 4 ? "****" : "****" + value.substring(value.length() - 4);
String normalized = value.replaceAll("[\\s\\p{Z}]+", "");
return normalized.length() <= 4 ? "****" : "****" + normalized.substring(normalized.length() - 4);
}
private String sha256(Path file) throws IOException, NoSuchAlgorithmException {
@@ -70,7 +70,7 @@
left join srv_bill_air_fee air on f.fee_source = 'LADING' and air.id = f.sc_id
left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id
left join prc_surcharge item_sc on ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value COLLATE utf8mb4_general_ci = f.fee_type COLLATE utf8mb4_general_ci
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
where f.bill_id = o.bill_id and f.is_deleted = '0') as feeText,
(select count(*) from prc_pay_bill_fee f
where f.bill_id = o.bill_id and ifnull(f.is_deleted, '0') = '0') as feeCount,
@@ -130,7 +130,7 @@
left join srv_bill_air_fee air on f.fee_source = 'LADING' and air.id = f.sc_id
left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id
left join prc_surcharge item_sc on ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value COLLATE utf8mb4_general_ci = f.fee_type COLLATE utf8mb4_general_ci
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
where f.is_deleted = '0'
and f.bill_id in
<foreach collection="billIds" item="id" open="(" separator="," close=")">#{id}</foreach>
@@ -262,7 +262,7 @@
left join srv_bill_air_fee air on f.fee_source = 'LADING' and air.id = f.sc_id
left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id
left join prc_surcharge item_sc on ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value COLLATE utf8mb4_general_ci = f.fee_type COLLATE utf8mb4_general_ci
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
where ifnull(f.is_deleted, '0') = '0'
and f.statement_line_id is null
and f.bill_id in
@@ -7,7 +7,6 @@
p.order_no as orderNo,
nullif(trim(e.air_no_old), '') as ladingNo,
p.tracking_no as trackingNo,
p.customer_code as customerCode,
p.customer_name as customerName,
p.product_name as productName,
p.country_name as countryName,
@@ -44,7 +44,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id
left join pay_surcharge pay_sc on f.fee_type = 'SURCHARGE' and ifnull(f.fee_source, '') &lt;&gt; 'LADING' and pay_sc.surcharge_id = f.sc_id
left join prc_surcharge item_sc on f.fee_type = 'SURCHARGE' and ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value COLLATE utf8mb4_general_ci = f.fee_type COLLATE utf8mb4_general_ci
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
</sql>
<sql id="feeActorName">
@@ -59,7 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where u.del_flag = '0'
and (
(${column} regexp '^[0-9]+$' and u.user_id = cast(${column} as unsigned))
or (ifnull(${column}, '') not regexp '^[0-9]+$' and u.user_name COLLATE utf8mb4_general_ci = ${column} COLLATE utf8mb4_general_ci)
or (ifnull(${column}, '') not regexp '^[0-9]+$' and u.user_name = ${column} COLLATE utf8mb4_general_ci)
)
limit 1
), ${column})
@@ -197,7 +197,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="selectOpenFees" resultMap="PrcPayBillFeeResult">
select f.fee_id, f.bill_id, f.fee_level, f.amount, f.currency, b.biz_date
select f.fee_id, f.bill_id, f.amount, f.currency, b.biz_date
from prc_pay_bill_fee f
left join prc_order_bill b on b.bill_id = f.bill_id
where ifnull(f.is_deleted, '0') = '0'
@@ -12,10 +12,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="redlineAmount" column="redline_amount" />
<result property="costAmount" column="cost_amount" />
<result property="payTotal" column="pay_total" />
<result property="amountA" column="amount_a" />
<result property="amountB" column="amount_b" />
<result property="amountC" column="amount_c" />
<result property="amountD" column="amount_d" />
<result property="belongSaler" column="belong_saler" />
<result property="belongSalerCode" column="belong_saler_code" />
<result property="settlementMan" column="settlement_man" />
@@ -28,7 +24,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<sql id="selectPrcPayBillVo">
select pay_bill_id, bill_id, currency, product_amount, redline_amount,
cost_amount, pay_total, amount_a, amount_b, amount_c, amount_d,
cost_amount, pay_total,
belong_saler, belong_saler_code, settlement_man, settlement_man_code,
create_by, create_time, update_by, update_time
from prc_pay_bill
@@ -142,13 +138,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<foreach collection="billIds" item="billId" open="(" separator="," close=")">#{billId}</foreach>
</update>
<update id="updateCnyPayTotal" parameterType="PrcPayBill">
<update id="updateCnyPayTotal">
update prc_pay_bill
set pay_total = #{payTotal},
amount_a = #{amountA},
amount_b = #{amountB},
amount_c = #{amountC},
amount_d = #{amountD},
currency = 'CNY',
update_time = sysdate()
where bill_id = #{billId}
@@ -71,19 +71,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
bp.fv_registration_fee as base_registration_fee,
d.discount_value, d.round_mode, d.pr_id, d.effective_date, d.expire_date, d.is_del, d.create_time, d.update_time
from prc_price_set_detail d
left join prc_price_set_detail bp
on bp.price_type = 'PRODUCT'
and bp.product_code = d.product_code
and ifnull(bp.country_code,'') = ifnull(d.country_code,'')
and ifnull(bp.zone_code,'') = ifnull(d.zone_code,'')
and ifnull(bp.weight_min,-1) = ifnull(d.weight_min,-1)
and ifnull(bp.weight_max,-1) = ifnull(d.weight_max,-1)
and ifnull(bp.is_del, '0') = '0'
and bp.psv_id = (
select v.psv_id from prc_price_set_version v
where v.price_type = 'PRODUCT' and v.price_set_id is null and v.status = '1'
order by v.version_seq desc limit 1
)
left join (
select bp0.psd_id, bp0.product_code, bp0.country_code, bp0.zone_code,
bp0.weight_min, bp0.weight_max, bp0.fv_value, bp0.fv_registration_fee
from prc_price_set_detail bp0
where bp0.price_type = 'PRODUCT'
and ifnull(bp0.is_del, '0') = '0'
and bp0.psv_id = (
select v.psv_id from prc_price_set_version v
where v.price_type = 'PRODUCT' and v.price_set_id is null and v.status = '1'
order by v.version_seq desc limit 1
)
) bp
on bp.product_code = d.product_code
and bp.country_code &lt;=&gt; d.country_code
and bp.zone_code &lt;=&gt; d.zone_code
and bp.weight_min &lt;=&gt; d.weight_min
and bp.weight_max &lt;=&gt; d.weight_max
<where>
and ifnull(d.is_del, '0') = '0'
@@ -80,6 +80,27 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
order by r.detail_id is not null, r.rel_id asc
</select>
<!-- 按套餐版本轻量查销售附加费(产品/明细关联),供查看详情产品列表 -->
<select id="selectSalesRelsByPsvId" resultMap="PrcSurchargeRelResult">
select r.rel_id, r.sc_id, r.product_id,
coalesce(nullif(trim(r.product_code), ''), p.product_code, d.product_code) as product_code,
r.detail_id, r.price_type, r.country_code, r.is_del,
r.created_by, r.create_time, r.updated_by, r.update_time,
s.sc_name, s.fee_type, s.charge_type, s.charge_value, s.currency,
s.round_mode, s.ss_code, s.sc_note,
s.postcode_text, s.length_cm, s.width_cm, s.height_cm, s.size_type, s.volume_m3,
s.over_weight_kg, s.extra_weight_kg, s.block_title,
null as country_name, null as weight_min, null as weight_max
from prc_surcharge_rel r
join prc_surcharge s on s.sc_id = r.sc_id and ifnull(s.is_del, '0') = '0'
left join prc_price_set_product p on p.psp_id = r.product_id and p.psv_id = #{psvId}
left join prc_price_set_detail d on d.psd_id = r.detail_id and d.psv_id = #{psvId} and ifnull(d.is_del, '0') = '0'
where ifnull(r.is_del, '0') = '0'
and r.price_type = 'SALES'
and (p.psp_id is not null or d.psd_id is not null)
order by r.rel_id asc
</select>
<select id="selectByDetailIdsAndPriceType" resultMap="PrcSurchargeRelResult">
<include refid="selectPrcSurchargeRelVo"/>
where ifnull(r.is_del, '0') = '0'
@@ -8,12 +8,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<id property="detailId" column="detail_id" />
<result property="zoneId" column="zone_id" />
<result property="postcode" column="postcode" />
<result property="matchType" column="match_type" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
</resultMap>
<sql id="selectPrcZoneDetailVo">
select detail_id, zone_id, postcode, create_time, update_time
select detail_id, zone_id, postcode, match_type, create_time, update_time
from prc_zone_detail
</sql>
@@ -51,18 +52,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
insert into prc_zone_detail (
<if test="zoneId != null">zone_id,</if>
<if test="postcode != null and postcode != ''">postcode,</if>
match_type,
create_time
) values (
<if test="zoneId != null">#{zoneId},</if>
<if test="postcode != null and postcode != ''">#{postcode},</if>
#{matchType},
sysdate()
)
</insert>
<insert id="insertPrcZoneDetailBatch">
insert into prc_zone_detail (zone_id, postcode, create_time) values
insert into prc_zone_detail (zone_id, postcode, match_type, create_time) values
<foreach collection="list" item="item" separator=",">
(#{item.zoneId}, #{item.postcode}, sysdate())
(#{item.zoneId}, #{item.postcode}, #{item.matchType}, sysdate())
</foreach>
</insert>
@@ -71,6 +74,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<set>
<if test="zoneId != null">zone_id = #{zoneId},</if>
<if test="postcode != null and postcode != ''">postcode = #{postcode},</if>
<if test="matchType != null and matchType != ''">match_type = #{matchType},</if>
update_time = sysdate()
</set>
where detail_id = #{detailId}
@@ -120,8 +124,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and z.product_id is null
and upper(ifnull(z.country_code,'')) = upper(#{countryCode})
and (
replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
or replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
(
upper(ifnull(d.match_type, 'FULL')) = 'FULL'
and replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
)
or
(
upper(ifnull(d.match_type, 'FULL')) = 'PREFIX'
and replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
)
)
order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end,
@@ -147,8 +158,15 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where z.zone_type = 'LABEL'
and z.product_id = #{productId}
and (
replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
or replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
(
upper(ifnull(d.match_type, 'FULL')) = 'FULL'
and replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '')
)
or
(
upper(ifnull(d.match_type, 'FULL')) = 'PREFIX'
and replace(upper(#{postcode}), ' ', '') like concat(replace(upper(ifnull(d.postcode,'')), ' ', ''), '%')
)
)
order by
case when replace(upper(ifnull(d.postcode,'')), ' ', '') = replace(upper(#{postcode}), ' ', '') then 0 else 1 end,
@@ -0,0 +1,78 @@
-- 众升 2026-11-19 渠道变更:prc_order_bill 同步修改产品名称+产品代码(66 单)
-- 守卫带旧产品代码,防误改;执行后核对查询应看到 6 组新值、无旧值残留
-- 备份(回滚用,可不执行)
-- CREATE TABLE bak_prc_order_bill_20261119 AS
-- SELECT * FROM prc_order_bill WHERE order_no IN (
-- 'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
-- 'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
-- 'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
-- 'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
-- 'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
-- 'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
-- 'MS20261103235057005', 'JH20261107111V', 'YDM11071749901S', 'MMP43', 'I020261104550165010176YYYYYY', 'OA23201B', '1327110118498773', 'T210---1',
-- 'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'YWLT11091749882', 'OA23332', 'YWLT11111549923',
-- 'XM2GRX3010155', 'MS20261105040758061'
-- );
-- 1. 标快服装-包税(限定)(WSP117) -> 标快普货-包税(限定)(WSP118),49 单
UPDATE prc_order_bill
SET product_name = '标快普货-包税(限定)', product_code = 'WSP118'
WHERE product_code = 'WSP117' AND order_no IN (
'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
'MS20261103235057005'
);
-- 2. 标快球衣-包税(WSP037) -> 球衣服装-包税(WSP099),2 单
UPDATE prc_order_bill
SET product_name = '球衣服装-包税', product_code = 'WSP099'
WHERE product_code = 'WSP037' AND order_no IN (
'JH20261107111V', 'YDM11071749901S'
);
-- 3. 全球标快-球衣(WSP020) -> 标快服装-球衣(WSP098),2 单
UPDATE prc_order_bill
SET product_name = '标快服装-球衣', product_code = 'WSP098'
WHERE product_code = 'WSP020' AND order_no IN (
'MMP43', 'I020261104550165010176YYYYYY'
);
-- 4. 标快鞋盒-硬包(WSP067) -> 全球标快-球衣(WSP020),4 单
UPDATE prc_order_bill
SET product_name = '全球标快-球衣', product_code = 'WSP020'
WHERE product_code = 'WSP067' AND order_no IN (
'OA23201B', 'YWLT11091749882', 'YWLT11111549923', 'XM2GRX3010155'
);
-- 5. 标快鞋盒-包税(WSP066) -> 标快球衣-包税(WSP037),8 单
UPDATE prc_order_bill
SET product_name = '标快球衣-包税', product_code = 'WSP037'
WHERE product_code = 'WSP066' AND order_no IN (
'1327110118498773', 'T210---1', 'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'OA23332'
);
-- 6. 标快服装-包税(限定)(WSP117) -> 标快鞋盒-包税(WSP066),1 单
UPDATE prc_order_bill
SET product_name = '标快鞋盒-包税', product_code = 'WSP066'
WHERE product_code = 'WSP117' AND order_no IN (
'MS20261105040758061'
);
-- 核对:应只剩 6 组新值,总 66 单
SELECT product_name, product_code, COUNT(*) AS 单数
FROM prc_order_bill WHERE order_no IN (
'MS20261102015630106', 'MS20261101223958075', 'MS20261102075714101', 'MS20261102021718025', 'MS20261101112835035', 'MS20261101212721049', 'MS20261101000937086', 'MS20261101190713149',
'MS20261101190906090', 'MS20261102073516088', 'MS20261101184605072', 'MS20261101084234113', 'MS20261102062854044', 'MS20261102070753089', 'MS20261102022047060', 'MS20261101201529093',
'MS20261101062807057', 'MS20261103032420038', 'MS20261101083746056', 'MS20261104070523067', 'MS20261101183120126', 'MS20261103234634123', 'MS20261103184219061', 'MS20261103051434104',
'MS20261102190537107', 'MS20261104223025045', 'MS20261104063437075', 'MS20261104021501015', 'MS20261104163029097', 'MS20261104014232104', 'MS20261102154710079', 'MS20261103063337074',
'MS20261101223348059', 'MS20261103083612118', 'MS20261103204057080', 'MS20261103154351089', 'MS20261102210531170', 'MS20261106090329054', 'MS20261104161112109', 'MS20261105052635095',
'MS20261104024953018', 'MS20261105062540026', 'MS20261104164434132', 'MS20261105201758004', 'MS20261106042152030', 'MS20261105234213114', 'MS20261104020640145', 'MS20261105174957139',
'MS20261103235057005', 'JH20261107111V', 'YDM11071749901S', 'MMP43', 'I020261104550165010176YYYYYY', 'OA23201B', '1327110118498773', 'T210---1',
'AA23336', 'YDM11071749901A', 'T210---1A', 'S967110911499386', '1327110912499482', 'YWLT11091749882', 'OA23332', 'YWLT11111549923',
'XM2GRX3010155', 'MS20261105040758061'
) GROUP BY product_name, product_code ORDER BY 单数 DESC;
+1
View File
@@ -1596,6 +1596,7 @@ CREATE TABLE `prc_zone_detail` (
`detail_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'detail id',
`zone_id` bigint(20) NOT NULL COMMENT 'zone id',
`postcode` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'postcode',
`match_type` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'FULL' COMMENT 'FULL exact / PREFIX starts with',
`create_time` datetime DEFAULT NULL COMMENT 'created at',
`update_time` datetime DEFAULT NULL COMMENT 'updated at',
PRIMARY KEY (`detail_id`),
@@ -1,23 +0,0 @@
-- 应付列表增加批量新增费用按钮
INSERT INTO `bms`.`sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`)
SELECT (SELECT IFNULL(MAX(`t`.`menu_id`), 0) + 1 FROM (SELECT `menu_id` FROM `bms`.`sys_menu`) `t`), '批量新增费用', `p`.`menu_id`, (SELECT IFNULL(MAX(`c`.`order_num`), 0) + 1 FROM (SELECT `parent_id`, `order_num` FROM `bms`.`sys_menu`) `c` WHERE `c`.`parent_id` = `p`.`menu_id`), '', '', 1, 0, 'F', '0', '0', 'price:payOrder:feeBatch', '#', 'admin', sysdate()
FROM `bms`.`sys_menu` `p`
WHERE `p`.`perms` = 'price:payOrder:list' AND `p`.`menu_type` = 'C'
AND NOT EXISTS (SELECT 1 FROM `bms`.`sys_menu` `e` WHERE `e`.`perms` = 'price:payOrder:feeBatch')
ORDER BY `p`.`menu_id`
LIMIT 1;
-- 管理员拥有批量新增费用按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT 1, `m`.`menu_id`
FROM `bms`.`sys_menu` `m`
WHERE `m`.`perms` = 'price:payOrder:feeBatch'
AND NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` `rm` WHERE `rm`.`role_id` = 1 AND `rm`.`menu_id` = `m`.`menu_id`);
-- 能看应付列表的角色同时拥有批量新增费用按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT DISTINCT `rm`.`role_id`, `btn`.`menu_id`
FROM `bms`.`sys_role_menu` `rm`
INNER JOIN `bms`.`sys_menu` `parent` ON `parent`.`menu_id` = `rm`.`menu_id` AND `parent`.`perms` = 'price:payOrder:list' AND `parent`.`menu_type` = 'C'
INNER JOIN `bms`.`sys_menu` `btn` ON `btn`.`perms` = 'price:payOrder:feeBatch'
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` `x` WHERE `x`.`role_id` = `rm`.`role_id` AND `x`.`menu_id` = `btn`.`menu_id`);
@@ -0,0 +1,13 @@
-- prc_zone_detail.match_type: FULL exact / PREFIX starts-with
-- Idempotent. Column default is FULL. No bulk rewrite of existing rows.
SET @db := DATABASE();
SELECT COUNT(*) INTO @col_match_type
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'prc_zone_detail' AND COLUMN_NAME = 'match_type';
SET @sql := IF(@col_match_type = 0,
'ALTER TABLE prc_zone_detail ADD COLUMN match_type varchar(16) NOT NULL DEFAULT ''FULL'' COMMENT ''FULL exact match / PREFIX starts with'' AFTER postcode',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
@@ -0,0 +1,7 @@
-- One-shot: undo earlier mistaken "all rows = PREFIX" migration.
-- Default display/billing type becomes FULL.
-- After running, re-import Evri / UK / Canada remote sheets if those need PREFIX.
UPDATE prc_zone_detail
SET match_type = 'FULL'
WHERE match_type IS NULL OR match_type = '' OR UPPER(match_type) = 'PREFIX';
+4
View File
@@ -29,6 +29,10 @@ export function getDefaultArBankAccount(currency = 'CNY') {
return request({ url: '/ar/bill/default-bank-account', method: 'get', params: { currency } })
}
export function listArBillBankAccountOptions(currency = 'CNY') {
return request({ url: '/ar/bill/bank-account-options', method: 'get', params: { currency } })
}
export function generateArBill(data) {
return request({ url: '/ar/bill/generate', method: 'post', data, timeout: 30000 })
}
-8
View File
@@ -38,14 +38,6 @@ export function addPayOrderFee(billId, data) {
})
}
export function addPayOrderFees(data) {
return request({
url: '/price/payOrder/fees/batch',
method: 'post',
data
})
}
export function removePayOrderFee(feeId) {
return request({
url: '/price/payOrder/fees/' + feeId,
@@ -60,6 +60,7 @@
<el-table-column prop="totalAmount" label="订单金额" width="120" align="right"><template #default="{ row }">{{ money(row.totalAmount) }}</template></el-table-column>
<el-table-column prop="productAmount" label="整单产品价" width="130" align="right"><template #default="{ row }">{{ amount4(row.productAmount) }}</template></el-table-column>
<el-table-column prop="redlineAmount" label="整单红线价" width="130" align="right"><template #default="{ row }">{{ amount4(row.redlineAmount) }}</template></el-table-column>
<el-table-column prop="receiveTime" label="收货时间" width="170"><template #default="{ row }">{{ row.receiveTime || '-' }}</template></el-table-column>
</el-table>
<el-pagination
v-if="detailTotal > 0 || appliedDetailQuery.orderKeyword || appliedDetailQuery.productKeyword"
@@ -32,13 +32,16 @@
</el-row>
</el-form>
<div class="payee-card" v-loading="bankAccountLoading">
<div class="payee-title">收款方信息(按币种自动匹配)</div>
<div class="payee-title">收款方信息</div>
<el-select v-model="selectedBankAccountId" class="payee-select" placeholder="请选择收款账户" :disabled="bankAccountLoading || generateLoading" @change="handleBankAccountChange">
<el-option v-for="account in bankAccounts" :key="account.bankAccountId" :value="String(account.bankAccountId)" :label="`${account.accountName}(${account.accountNo})`" />
</el-select>
<template v-if="bankAccount">
<span><b>开户名:</b>{{ bankAccount.accountName }}</span>
<span><b>开户行:</b>{{ bankAccount.bankName }}</span>
<span><b>账号:</b>{{ bankAccount.accountNo }}</span>
</template>
<span v-else class="payee-empty">当前币种尚未配置公司默认收款账户</span>
<span v-else-if="!bankAccountLoading" class="payee-empty">当前币种尚未配置启用的收款账户</span>
</div>
<div class="preview-toolbar">
<span v-if="previewSearched" class="preview-summary">
@@ -177,7 +180,7 @@
</template>
<script setup name="GenerateBillDialog">
import { listArBillGenerateCustomerOptions, getDefaultArBankAccount, previewArBill, getArBillPreviewAmount, previewExcludedArBill, generateArBill } from '@/api/ar/bill'
import { listArBillGenerateCustomerOptions, listArBillBankAccountOptions, previewArBill, getArBillPreviewAmount, previewExcludedArBill, generateArBill } from '@/api/ar/bill'
import { Download, Refresh, Search, Select } from '@element-plus/icons-vue'
import { AR_BILL_SELECTION_MODE } from '@/constants/ar/enums'
import { exportAsync } from '@/utils/excelExport'
@@ -255,7 +258,10 @@ let excludeRequestSeq = 0
const previewQuery = ref(null)
let syncingPageSelection = false
const bankAccountLoading = ref(false)
const bankAccount = ref(null)
const bankAccounts = ref([])
const selectedBankAccountId = ref('')
const bankAccount = computed(() => bankAccounts.value.find(account => String(account.bankAccountId) === selectedBankAccountId.value) || null)
let bankAccountRequestSeq = 0
const generateRequestId = ref('')
const generateFormRef = ref()
const billNameFormRef = ref()
@@ -288,8 +294,7 @@ function openGenerate() {
Object.assign(billNameForm, { billName: '' })
billNameOpen.value = false
resetPreview()
bankAccount.value = null
loadDefaultBankAccount()
loadBankAccounts()
nextTick(() => generateFormRef.value?.clearValidate())
}
@@ -301,7 +306,7 @@ function handleCustomerChange(_, item) {
function handleCurrencyChange() {
resetPreview()
loadDefaultBankAccount()
loadBankAccounts()
}
// 只清空输入内容,不自动刷新预览;用户点击“查询”后再按新条件查询。
@@ -315,16 +320,25 @@ function clearExcludeIdentifiers() {
invalidateExcludeSearch()
}
function loadDefaultBankAccount() {
function loadBankAccounts() {
const requestSeq = ++bankAccountRequestSeq
bankAccountLoading.value = true
bankAccount.value = null
getDefaultArBankAccount(generateForm.currency).then(res => {
bankAccount.value = res.data || null
bankAccounts.value = []
selectedBankAccountId.value = ''
listArBillBankAccountOptions(generateForm.currency).then(res => {
if (requestSeq !== bankAccountRequestSeq) return
bankAccounts.value = res.data || []
const defaultAccount = bankAccounts.value.find(account => String(account.isDefault) === '1') || bankAccounts.value[0]
selectedBankAccountId.value = defaultAccount ? String(defaultAccount.bankAccountId) : ''
}).finally(() => {
bankAccountLoading.value = false
if (requestSeq === bankAccountRequestSeq) bankAccountLoading.value = false
})
}
function handleBankAccountChange() {
if (!generateLoading.value) generateRequestId.value = ''
}
// 条件变化后清理预览和跨页选中状态;用户点击查询时重新加载第一页。
function resetPreview() {
previewRows.value = []
@@ -363,6 +377,7 @@ function buildGenerateRequest(requestId) {
return {
...(previewQuery.value || buildGenerateQuery()),
billName: billNameForm.billName.trim(),
bankAccountId: selectedBankAccountId.value,
selectionMode: selectionMode.value,
sourceBillIds: selectionMode.value === AR_BILL_SELECTION_MODE.ALL_MATCHED ? [] : selectedRows.value.map(row => String(row.billId)),
excludedSourceBillIds: [],
@@ -673,6 +688,7 @@ function createRequestId() { return globalThis.crypto?.randomUUID?.() || `ar-${D
.order-identifier-clear { position: absolute; top: 4px; right: 6px; z-index: 1; padding: 2px 4px; }
.payee-card { display: flex; align-items: center; flex-wrap: wrap; gap: 16px; min-height: 42px; margin: 4px 0 12px; padding: 9px 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 4px; background: var(--el-fill-color-light); color: var(--el-text-color-regular); font-size: 13px; }
.payee-title { color: var(--el-text-color-primary); font-weight: 600; }
.payee-select { width: 340px; max-width: 100%; }
.payee-empty { color: var(--el-color-danger); }
.preview-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin: 18px 0 10px; padding: 10px 14px; border-radius: 6px; background: var(--el-fill-color-light); color: var(--el-text-color-regular); }
.preview-summary { flex: 1; font-size: 14px; }
@@ -171,13 +171,20 @@ function scheduleAutoCollapse() {
}
function open(filterQuery, autoStart) {
// Already running / finished: just reopen progress view (same as order-list rebill).
if (loading.value || finished.value) {
// Still running: only reopen progress (do not start another task).
if (loading.value) {
visible.value = true
return
}
// Finished + reopen only (float click): show last result.
if (finished.value && !autoStart && filterQuery == null) {
visible.value = true
return
}
// New sync: clear previous result first.
query.value = { ...(filterQuery || {}) }
asyncTaskIdRef.value = ''
pollGeneration.value += 1
progress.value = {
percent: 0,
message: '',
@@ -357,7 +364,11 @@ onBeforeUnmount(() => {
pollGeneration.value += 1
})
defineExpose({ open })
function reopen() {
visible.value = true
}
defineExpose({ open, reopen })
</script>
<style scoped>
@@ -2,7 +2,7 @@
<div class="app-container order-source-page">
<div v-if="syncFloatVisible" class="retry-status-float">
<el-tooltip :content="syncFloatTooltip" placement="bottom">
<el-button class="retry-status-button" type="primary" plain size="small" @click="openFilterSync()">
<el-button class="retry-status-button" type="primary" plain size="small" @click="reopenSyncProgress()">
<span class="retry-progress-ring" :style="{ '--retry-progress': syncProgressDegree + 'deg' }" aria-hidden="true">
<span class="retry-progress-value">{{ syncProgressText }}</span>
</span>
@@ -458,12 +458,28 @@ function onCompareFillSearch(payload) {
tableRef.value?.handleQuery?.()
}
function reopenSyncProgress() {
const dlg = syncDialogRef.value
if (dlg && typeof dlg.reopen === 'function') {
dlg.reopen()
} else {
dlg?.open(null, false)
}
}
function openFilterSync() {
// Running / just finished: reopen progress dialog (same as order-list float click).
if (syncFloat.value && (syncFloat.value.loading || syncFloat.value.finished)) {
syncDialogRef.value?.open(null, false)
// Running: reopen progress; finished result must not block a new sync.
if (syncFloat.value?.loading) {
reopenSyncProgress()
return
}
if (syncFloat.value?.finished) {
if (syncFloatHideTimer) {
clearTimeout(syncFloatHideTimer)
syncFloatHideTimer = null
}
syncFloat.value = null
}
const q = buildFilterQuery()
const identifierCount = (q.orderIdentifiers || []).length
const hasIdentifier = identifierCount > 0
@@ -10,8 +10,8 @@
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="价卡名称" required>
<el-input v-model="form.productName" maxlength="80" placeholder="价卡名称" />
<el-form-item label="产品名称" required>
<el-input v-model="form.productName" maxlength="80" placeholder="渠道或产品名称" />
</el-form-item>
</el-col>
<el-col :span="8">
@@ -25,6 +25,11 @@
<el-table v-loading="loading" :data="list" border row-key="detailId" empty-text="暂无邮编">
<el-table-column label="ID" prop="detailId" align="center" width="90" />
<el-table-column label="邮编" prop="postcode" align="center" min-width="140" />
<el-table-column label="匹配类型" prop="matchType" align="center" min-width="140">
<template #default="{ row }">
{{ matchTypeText(row.matchType) }}
</template>
</el-table-column>
<el-table-column label="操作" align="center" width="160">
<template #default="{ row }">
<el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['price:zone:edit']">编辑</el-button>
@@ -96,6 +101,11 @@ function loadList() {
})
}
function matchTypeText(type) {
if (String(type || '').toUpperCase() === 'PREFIX') return '匹配邮编开头'
return '全匹配'
}
function handleAdd() {
postcodeFormRef.value.open(selectedZone.value)
}
@@ -1,9 +1,15 @@
<template>
<el-dialog :title="title" v-model="visible" width="420px" append-to-body>
<el-form ref="postcodeFormRef" :model="form" :rules="rules" label-width="80px">
<el-dialog :title="title" v-model="visible" width="480px" append-to-body>
<el-form ref="postcodeFormRef" :model="form" :rules="rules" label-width="100px">
<el-form-item label="邮编" prop="postcode">
<el-input v-model="form.postcode" placeholder="请输入邮编" maxlength="32" />
</el-form-item>
<el-form-item label="匹配类型" prop="matchType">
<el-radio-group v-model="form.matchType">
<el-radio label="FULL">全匹配</el-radio>
<el-radio label="PREFIX">匹配邮编开头</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
@@ -26,17 +32,19 @@ const title = ref('')
const postcodeFormRef = ref()
const form = ref({})
const rules = {
postcode: [{ required: true, message: '邮编不能为空', trigger: 'blur' }]
postcode: [{ required: true, message: '邮编不能为空', trigger: 'blur' }],
matchType: [{ required: true, message: '请选择匹配类型', trigger: 'change' }]
}
/** zone 为所属分区;row 传空为新增,传邮编行为编辑 */
function open(zone, row) {
form.value = row
? { ...row }
? { ...row, matchType: row.matchType || 'FULL' }
: {
detailId: undefined,
zoneId: zone?.zoneId,
postcode: undefined
postcode: undefined,
matchType: 'FULL'
}
title.value = row ? '编辑邮编' : '新增邮编'
visible.value = true
@@ -48,7 +56,8 @@ function submitForm() {
if (!valid) return
const payload = {
...form.value,
postcode: String(form.value.postcode || '').trim()
postcode: String(form.value.postcode || '').trim(),
matchType: form.value.matchType || 'FULL'
}
const req = payload.detailId != null ? updateDetail(payload) : addDetail(payload)
req.then(() => {
@@ -1,375 +0,0 @@
<template>
<el-drawer
:model-value="modelValue"
:title="title"
size="840px"
append-to-body
destroy-on-close
class="bill-detail-drawer"
@update:model-value="$emit('update:modelValue', $event)"
>
<div v-loading="loading" class="bill-detail-wrap">
<el-empty v-if="!detail" description="暂无详情" />
<div v-else class="bill-detail">
<section class="detail-block">
<div class="sec-title">订单信息</div>
<el-descriptions class="detail-desc" :column="2" border size="small">
<el-descriptions-item label="订单号">{{ detail.orderNo || '-' }}</el-descriptions-item>
<el-descriptions-item label="运单号">{{ detail.trackingNo || '-' }}</el-descriptions-item>
<el-descriptions-item label="转单号">{{ detail.transferNo || '-' }}</el-descriptions-item>
<el-descriptions-item label="销售员">{{ detail.belongSaler || '-' }}</el-descriptions-item>
<el-descriptions-item label="结算员">{{ detail.settlementMan || '-' }}</el-descriptions-item>
<el-descriptions-item label="客服员">{{ detail.serviceMan || '-' }}</el-descriptions-item>
<el-descriptions-item label="客户">{{ displayCustomer(detail) }}</el-descriptions-item>
<el-descriptions-item label="客户状态">{{ customerActiveLabel(detail.customerActiveStatus) }}</el-descriptions-item>
<el-descriptions-item label="额度欠费">{{ creditArrearsLabel(detail.creditArrearsStatus) }}</el-descriptions-item>
<el-descriptions-item label="退费状态">{{ refundLabel(detail.refundStatus) }}</el-descriptions-item>
<el-descriptions-item label="仓库">{{ detail.warehouseCode || '-' }}</el-descriptions-item>
<el-descriptions-item label="发件人">{{ detail.shipperName || '-' }}</el-descriptions-item>
<el-descriptions-item label="收件人">{{ detail.consigneeName || '-' }}</el-descriptions-item>
<el-descriptions-item label="目的国/地区">{{ countryLabel(detail) }}</el-descriptions-item>
<el-descriptions-item label="目的邮编">{{ detail.destPostcode || '-' }}</el-descriptions-item>
<el-descriptions-item label="件数">{{ detail.pieces != null ? detail.pieces : '-' }}</el-descriptions-item>
<el-descriptions-item label="尺寸(cm)">{{ dimLabel(detail) }}</el-descriptions-item>
<el-descriptions-item label="实重(kg)">{{ formatWeight(detail.actualWeight) }}</el-descriptions-item>
<el-descriptions-item label="收货重(kg)">{{ formatWeight(detail.receiveWeight) }}</el-descriptions-item>
<el-descriptions-item label="材积重(kg)">{{ formatWeight(detail.volumeWeight) }}</el-descriptions-item>
<el-descriptions-item label="体积(m³)">{{ formatMoney(detail.volume) }}</el-descriptions-item>
<el-descriptions-item label="下单时间">{{ formatDateTime(detail.orderTime) }}</el-descriptions-item>
<el-descriptions-item label="订单备注" :span="2">{{ detail.orderRemark || '-' }}</el-descriptions-item>
</el-descriptions>
</section>
<section class="detail-block">
<div class="sec-title">计费信息</div>
<div class="amount-summary">
<div class="amount-card">
<div class="amount-label">A段</div>
<div class="amount-value">{{ formatMoney(detail.amountA) }}</div>
</div>
<div class="amount-card">
<div class="amount-label">B段</div>
<div class="amount-value">{{ formatMoney(detail.amountB) }}</div>
</div>
<div class="amount-card">
<div class="amount-label">C段</div>
<div class="amount-value">{{ formatMoney(detail.amountC) }}</div>
</div>
<div class="amount-card">
<div class="amount-label">D段</div>
<div class="amount-value">{{ formatMoney(detail.amountD) }}</div>
</div>
<div class="amount-card is-total">
<div class="amount-label">应付总额</div>
<div class="amount-value">{{ formatMoney(detail.payTotal) }}</div>
</div>
</div>
<el-descriptions class="detail-desc" :column="2" border size="small">
<el-descriptions-item label="产品">{{ productLabel(detail) }}</el-descriptions-item>
<el-descriptions-item label="客户确认重(kg)">{{ formatWeight(detail.chargeWeight) }}</el-descriptions-item>
<el-descriptions-item label="计费重量(kg)">{{ formatWeight(detail.chargeWeight ?? detail.weight) }}</el-descriptions-item>
<el-descriptions-item label="重量段">{{ detail.weightLabel || '-' }}</el-descriptions-item>
<el-descriptions-item label="计费时间">{{ detail.bizDate || '-' }}</el-descriptions-item>
<el-descriptions-item label="渠道编码">{{ detail.productFloorCode || '-' }}</el-descriptions-item>
<el-descriptions-item label="渠道名称">{{ detail.productFloor || '-' }}</el-descriptions-item>
<el-descriptions-item label="计费状态">
<el-tag size="small" :type="billingFailTagType(detail.billingFailStatus)">{{ billingFailLabel(detail.billingFailStatus) }}</el-tag>
</el-descriptions-item>
<el-descriptions-item label="套餐">{{ priceSetLabel(detail) }}</el-descriptions-item>
<el-descriptions-item label="币种">
<dict-tag :options="bms_currency" :value="displayCurrency(detail.currency)" />
</el-descriptions-item>
<el-descriptions-item label="取值方式">{{ roundModeLabel(detail.roundMode) }}</el-descriptions-item>
<el-descriptions-item label="运费单价">{{ formatRate(detail.freightRate) }}</el-descriptions-item>
<el-descriptions-item label="挂号费">{{ formatMoney(detail.registrationFee) }}</el-descriptions-item>
</el-descriptions>
</section>
<section class="detail-block">
<div class="sec-title">费用明细</div>
<div v-if="!readonly" class="pay-generate">
<el-button type="primary" plain size="small" v-hasPermi="['price:billing:bill']" @click="handlePayBill">生成应付</el-button>
</div>
<el-table v-if="payFees.length" :data="payFees" border size="small" class="fee-table">
<el-table-column label="费用名称" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ displayFeeName(row) }}</template>
</el-table-column>
<el-table-column label="费用类型" min-width="140" align="center" show-overflow-tooltip>
<template #default="{ row }">
<el-tag size="small" :type="feeTypeTag(row.feeType)" effect="plain">
{{ payFeeTypeLabel(row) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="金额" min-width="120" align="right">
<template #default="{ row }">
<span class="fee-amount">{{ formatFeeAmount(row.amount) }}</span>
</template>
</el-table-column>
<el-table-column label="币种" width="90" align="center">
<template #default="{ row }">
<dict-tag :options="bms_currency" :value="displayCurrency(row.currency)" />
</template>
</el-table-column>
<el-table-column label="说明" min-width="160" show-overflow-tooltip>
<template #default="{ row }">{{ row.remark || '-' }}</template>
</el-table-column>
</el-table>
<el-empty v-else description="暂无应付明细" :image-size="64" />
</section>
</div>
</div>
</el-drawer>
</template>
<script setup>
import { generatePayBill } from '@/api/price/pay'
import { getPayOrder } from '@/api/price/payOrder'
import { ElMessage, ElMessageBox } from 'element-plus'
const props = defineProps({
modelValue: { type: Boolean, default: false },
title: { type: String, default: '订单详情' },
loading: { type: Boolean, default: false },
detail: { type: Object, default: null },
readonly: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'updated'])
const { bms_fee_type, bms_currency } = useDict('bms_fee_type', 'bms_currency')
const payFees = computed(() => {
const d = props.detail
if (!d) return []
return d.payFeeDetails || []
})
function handlePayBill() {
const billId = props.detail?.billId
if (!billId) return
ElMessageBox.confirm('确认生成应付?', '生成应付', { type: 'warning' })
.then(() => generatePayBill(billId))
.then(() => {
ElMessage.success('操作成功')
return getPayOrder(billId)
})
.then(res => {
if (res && res.data) emit('updated', res.data)
})
.catch(err => {
if (err === 'cancel' || err === 'close') return
})
}
function customerActiveLabel(status) {
const map = { ACTIVE: '正常', MISSING: '不存在', DISABLED: '停用' }
return map[status] || status || '-'
}
function creditArrearsLabel(status) {
const map = { NORMAL: '正常', ARREARS: '欠费' }
return map[status] || status || '-'
}
function displayCustomer(row) {
if (row.customerName && row.customerCode) return row.customerName + ' (' + row.customerCode + ')'
return row.customerName || row.customerCode || row.customerId || '-'
}
function countryLabel(row) {
return (row.countryName || '-') + ' (' + (row.countryCode || '-') + ')'
}
function productLabel(row) {
return (row.productName || '-') + ' (' + (row.productCode || '-') + ')'
}
function priceSetLabel(row) {
const name = row.priceSetName || '-'
return row.priceSetCode ? name + ' (' + row.priceSetCode + ')' : name
}
function dimLabel(row) {
if (row.pkgLength == null && row.pkgWidth == null && row.pkgHeight == null) return '-'
return [row.pkgLength, row.pkgWidth, row.pkgHeight].map(v => v == null ? '-' : v).join(' × ')
}
function formatMoney(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
if (Number.isNaN(num)) return val
return num.toFixed(2)
}
function formatFeeAmount(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
if (Number.isNaN(num)) return val
return num.toFixed(3)
}
function formatWeight(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
if (Number.isNaN(num)) return val
return num.toFixed(3)
}
function formatRate(val) {
if (val === null || val === undefined || val === '') return '-'
const num = Number(val)
if (Number.isNaN(num)) return val
return num.toFixed(2)
}
function formatDateTime(val) {
if (!val) return '-'
const d = new Date(val)
if (Number.isNaN(d.getTime())) return val
const pad = n => String(n).padStart(2, '0')
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds())
}
const billingFailStatusOptions = [
{ label: '计费成功', value: 0 },
{ label: '销售价未匹配产品', value: 1 },
{ label: '销售价未匹配国家', value: 2 },
{ label: '销售价未匹配重量段', value: 3 },
{ label: '产品价未匹配产品', value: 23 },
{ label: '产品价未匹配国家', value: 24 },
{ label: '产品价未匹配重量段', value: 25 },
{ label: '未绑定套餐', value: 4 },
{ label: '套餐未启用/无生效版本', value: 5 },
{ label: '已生成应收账单', value: 6 },
{ label: '产品档案缺失', value: 7 },
{ label: '未命中价格', value: 8 },
{ label: '分区无价格', value: 9 },
{ label: '邮编必填', value: 10 },
{ label: '邮编未匹配分区', value: 11 },
{ label: '上游订单不存在', value: 12 },
{ label: '上游订单号为空', value: 13 },
{ label: '上游客户为空', value: 14 },
{ label: '上游产品为空', value: 15 },
{ label: '上游重量无效', value: 16 },
{ label: '计费时间为空', value: 17 },
{ label: '退费订单无法解析', value: 18 },
{ label: '客户代码为空', value: 19 },
{ label: '客户已停用', value: 20 },
{ label: '运费为空', value: 21 },
{ label: '未知失败', value: 22 },
{ label: '未计费', value: 26 }
]
function billingFailLabel(status) {
const code = status == null ? 0 : Number(status)
const hit = billingFailStatusOptions.find(item => item.value === code)
return hit ? hit.label : '未知失败'
}
function billingFailTagType(status) {
const code = status == null ? 0 : Number(status)
if (code === 26) return 'info'
if (code > 0) return 'danger'
return 'success'
}
function roundModeLabel(mode) {
const map = { UP: '向上取值', DOWN: '向下取整', HALF_UP: '四舍五入' }
return map[mode] || mode || '四舍五入'
}
function payFeeTypeLabel(row) {
const name = String(row?.feeName || row?.fee_name || '').trim()
if (row?.feeType === 'LADING' || row?.feeSource === 'LADING') return name || '提单费用'
return feeTypeLabel(row?.feeType) || row?.feeType || '-'
}
function feeTypeLabel(type) {
const found = (bms_fee_type.value || []).find(d => d.value === type)
return found ? found.label : ''
}
function feeTypeTag(type) {
if (type === 'FREIGHT') return ''
if (type === 'REGISTRATION') return 'warning'
if (type === 'SURCHARGE') return 'danger'
return 'info'
}
function displayCurrency(v) {
if (!v || v === 'RMB' || v === 'rmb') return 'CNY'
return v
}
function displayFeeName(row) {
const typeLabel = feeTypeLabel(row.feeType)
const name = String(row.feeName || row.fee_name || '').trim()
const isSurcharge = row.feeType === 'SURCHARGE' || row.feeType === '附加费'
if (isSurcharge && name && name !== typeLabel && name !== 'SURCHARGE' && name !== '附加费') {
return name
}
return name || typeLabel || row.feeType || '-'
}
function refundLabel(status) {
const map = { NONE: '未退费', REFUNDED: '已退费' }
return map[status] || status || '未退费'
}
</script>
<style scoped>
.bill-detail-wrap { min-height: 240px; }
.pay-generate { margin-bottom: 8px; }
.bill-detail { padding-bottom: 8px; }
.detail-block { margin-bottom: 20px; }
.detail-block:last-child { margin-bottom: 0; }
.sec-title {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 12px;
font-size: 14px;
font-weight: 600;
color: #303133;
line-height: 1;
}
.sec-title::before {
content: '';
width: 3px;
height: 14px;
border-radius: 2px;
background: var(--el-color-primary);
}
.amount-summary {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 10px;
margin-bottom: 12px;
}
.amount-card {
padding: 12px 14px;
background: #f7f8fa;
border-radius: 6px;
}
.amount-card.is-total { background: #fff1f0; }
.amount-label { font-size: 12px; color: #909399; line-height: 1.2; }
.amount-value {
margin-top: 6px;
font-size: 16px;
font-weight: 600;
color: #303133;
font-variant-numeric: tabular-nums;
line-height: 1.2;
}
.amount-card.is-total .amount-value { color: #f56c6c; }
.detail-desc :deep(.el-descriptions__label) {
width: 108px;
color: #909399;
font-weight: 400;
background: #fafbfc;
}
.detail-desc :deep(.el-descriptions__content) { color: #303133; }
.detail-desc :deep(.el-descriptions__cell) { padding: 9px 12px; }
.fee-amount { font-variant-numeric: tabular-nums; font-weight: 500; }
</style>
@@ -29,22 +29,18 @@
</el-form-item>
</el-form>
<el-row class="mb8" align="middle">
<el-row class="mb8">
<el-button type="primary" plain icon="RefreshRight" :loading="recalcRunning" v-hasPermi="['price:payOrder:recalc']" @click="openRecalc">费用重算</el-button>
<el-button type="primary" plain icon="Plus" v-hasPermi="['price:payOrder:feeBatch']" @click="openBatch">新增费用</el-button>
<span v-if="selectedOrders.length" class="picked-count">已选 {{ selectedOrders.length }} 个订单</span>
</el-row>
<el-table ref="orderTableRef" v-loading="loading" :data="rows" row-key="billId" border @selection-change="onSelectionChange">
<el-table-column type="selection" width="48" reserve-selection fixed="left" />
<el-table v-loading="loading" :data="rows" border>
<el-table-column prop="orderNo" label="订单号" min-width="160" fixed="left" show-overflow-tooltip />
<el-table-column prop="ladingNo" label="提单号" min-width="150" fixed="left" show-overflow-tooltip>
<template #default="{ row }">{{ row.ladingNo || '-' }}</template>
</el-table-column>
<el-table-column prop="trackingNo" label="运单号" min-width="150" show-overflow-tooltip />
<el-table-column prop="customerCode" label="客户编码" min-width="140" show-overflow-tooltip>
<template #default="{ row }">{{ row.customerCode || '-' }}</template>
</el-table-column>
<el-table-column prop="customerName" label="客户" min-width="140" show-overflow-tooltip />
<el-table-column prop="productName" label="产品" min-width="160" show-overflow-tooltip />
<el-table-column prop="countryName" label="目的国" width="110" show-overflow-tooltip />
<el-table-column prop="destPostcode" label="邮编" width="120" show-overflow-tooltip>
<template #default="{ row }">{{ row.destPostcode || '-' }}</template>
@@ -81,7 +77,7 @@
</el-table>
<pagination v-show="total > 0" :total="total" v-model:page="query.pageNum" v-model:limit="query.pageSize" @pagination="loadList" />
<pay-order-detail v-model="detailOpen" title="订单详情" :loading="detailLoading" :detail="detail" @updated="onDetailUpdated" />
<bill-detail v-model="detailOpen" title="订单详情" :loading="detailLoading" :detail="detail" :show-income="false" />
<el-dialog v-model="feeOpen" :title="feeTitle" width="1280px" append-to-body destroy-on-close>
<div v-loading="feeLoading" class="fee-board">
@@ -176,63 +172,6 @@
<pagination v-show="logTotal > 0" :total="logTotal" v-model:page="logQuery.pageNum" v-model:limit="logQuery.pageSize" @pagination="loadLogs" />
</el-dialog>
<el-dialog v-model="batchOpen" title="批量新增费用" width="1080px" append-to-body destroy-on-close :close-on-click-modal="false">
<div class="batch-block batch-orders">
<div class="fee-head">已选订单({{ batchOrders.length }})</div>
<div class="batch-order-list">
<el-tag
v-for="row in batchOrders"
:key="row.billId"
closable
effect="plain"
@close="removeBatchOrder(row)"
>{{ row.orderNo || '-' }}</el-tag>
<span v-if="!batchOrders.length" class="batch-order-empty">没有订单</span>
</div>
</div>
<div class="batch-block">
<div class="fee-head">新增费用</div>
<div class="fee-tools">
<el-button type="primary" plain size="small" @click="addBatchFee">增加一行</el-button>
</div>
<el-table class="fee-table" :data="batchFees" border empty-text="请增加费用">
<el-table-column label="费用项" min-width="160" header-align="center">
<template #default="{ row }">
<el-select v-model="row.feeType" filterable placeholder="选择费用项">
<el-option v-for="item in (bms_fee_type || [])" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</template>
</el-table-column>
<el-table-column label="金额" min-width="120" header-align="center">
<template #default="{ row }">
<el-input-number v-model="row.amount" :precision="3" :controls="false" />
</template>
</el-table-column>
<el-table-column label="币种" min-width="120" header-align="center">
<template #default="{ row }">
<el-select v-model="row.currency" filterable placeholder="选择币种">
<el-option v-for="item in (bms_currency || [])" :key="item.value" :label="item.label" :value="item.value" />
</el-select>
</template>
</el-table-column>
<el-table-column label="说明" min-width="180" header-align="center">
<template #default="{ row }">
<el-input v-model="row.remark" maxlength="200" placeholder="选填" />
</template>
</el-table-column>
<el-table-column label="操作" width="80" align="center" class-name="fee-op">
<template #default="{ row }">
<el-button link type="danger" @click="removeBatchFee(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<template #footer>
<el-button @click="batchOpen = false">取消</el-button>
<el-button type="primary" :loading="batchSaving" @click="submitBatch">确认</el-button>
</template>
</el-dialog>
<el-dialog v-model="recalcOpen" title="费用重算" width="720px" append-to-body :close-on-click-modal="false">
<el-form label-width="90px">
<el-form-item label="重算方式">
@@ -313,9 +252,9 @@
</template>
<script setup name="PayOrderList">
import { addPayOrderFee, addPayOrderFees, cancelPayOrderRecalc, getPayOrder, getPayOrderRecalcTask, listPayOrder, listPayOrderFeeLogs, listPayOrderFees, pollPayOrderRecalc, removePayOrderFee, submitPayOrderRecalc } from '@/api/price/payOrder'
import { addPayOrderFee, cancelPayOrderRecalc, getPayOrder, getPayOrderRecalcTask, listPayOrder, listPayOrderFeeLogs, listPayOrderFees, pollPayOrderRecalc, removePayOrderFee, submitPayOrderRecalc } from '@/api/price/payOrder'
import { ElMessage, ElMessageBox } from 'element-plus'
import PayOrderDetail from './PayOrderDetail.vue'
import BillDetail from '../components/BillDetail.vue'
const { proxy } = getCurrentInstance()
const { bms_pay_calc_status, bms_fee_type, bms_currency, bms_pay_fee_log_type } = useDict('bms_pay_calc_status', 'bms_fee_type', 'bms_currency', 'bms_pay_fee_log_type')
@@ -324,14 +263,6 @@ const loading = ref(false)
const rows = ref([])
const total = ref(0)
const query = reactive({ orderNo: '', ladingNo: '', customerName: '', pageNum: 1, pageSize: 20 })
const orderTableRef = ref()
const selectedMap = ref(new Map())
const selectedOrders = computed(() => Array.from(selectedMap.value.values()))
const batchOpen = ref(false)
const batchSaving = ref(false)
const batchOrders = ref([])
const batchFees = ref([])
let batchFeeSeed = 1
const detailOpen = ref(false)
const detailLoading = ref(false)
@@ -466,30 +397,6 @@ function reset() {
search()
}
function snapshotOrder(row) {
return {
billId: row.billId,
orderNo: row.orderNo,
ladingNo: row.ladingNo,
customerName: row.customerName,
productName: row.productName
}
}
function onSelectionChange(selection) {
if (loading.value) return
const pageIds = new Set((rows.value || []).map(row => String(row.billId)))
const next = new Map(selectedMap.value)
for (const id of pageIds) next.delete(id)
for (const row of selection || []) next.set(String(row.billId), snapshotOrder(row))
selectedMap.value = next
}
function syncSelection() {
const selection = orderTableRef.value?.getSelectionRows?.() || []
onSelectionChange(selection)
}
function loadList() {
loading.value = true
listPayOrder(query).then(res => {
@@ -497,98 +404,6 @@ function loadList() {
total.value = res.total || 0
}).finally(() => {
loading.value = false
nextTick(syncSelection)
})
}
function emptyBatchFee() {
batchFeeSeed += 1
return { key: batchFeeSeed, level: '4', feeType: '', amount: null, currency: 'CNY', remark: '' }
}
function openBatch() {
if (!selectedOrders.value.length) {
proxy.$modal.msgWarning('请先勾选订单')
return
}
batchOrders.value = selectedOrders.value.map(row => ({ ...row }))
batchFees.value = [emptyBatchFee()]
batchOpen.value = true
}
function removeBatchOrder(row) {
const id = String(row.billId)
batchOrders.value = batchOrders.value.filter(item => String(item.billId) !== id)
const stored = selectedMap.value.get(id)
const current = (rows.value || []).find(item => String(item.billId) === id)
orderTableRef.value?.toggleRowSelection(current || stored || row, false)
const next = new Map(selectedMap.value)
next.delete(id)
selectedMap.value = next
}
function addBatchFee() {
if (batchFees.value.length >= 20) {
proxy.$modal.msgWarning('一次最多增加20条费用')
return
}
batchFees.value.push(emptyBatchFee())
}
function removeBatchFee(row) {
batchFees.value = batchFees.value.filter(item => item !== row)
}
function submitBatch() {
if (!batchOrders.value.length) {
proxy.$modal.msgWarning('请勾选订单')
return
}
if (!batchFees.value.length) {
proxy.$modal.msgWarning('请增加费用')
return
}
const fees = []
for (const row of batchFees.value) {
if (!row.feeType) {
proxy.$modal.msgWarning('请选择费用项')
return
}
if (row.amount === null || row.amount === undefined || row.amount === '') {
proxy.$modal.msgWarning('请填写金额')
return
}
if (!row.currency) {
proxy.$modal.msgWarning('请选择币种')
return
}
const dict = (bms_fee_type.value || []).find(item => item.value === row.feeType)
fees.push({
feeType: row.feeType,
feeName: dict ? dict.label : row.feeType,
level: '4',
amount: row.amount,
currency: row.currency,
remark: row.remark
})
}
const orderCount = batchOrders.value.length
proxy.$modal.confirm('确认为 ' + orderCount + ' 个订单各增加 ' + fees.length + ' 条手工费用?').then(() => {
batchSaving.value = true
return addPayOrderFees({
billIds: batchOrders.value.map(row => String(row.billId)),
fees
})
}).then(() => {
proxy.$modal.msgSuccess('已为 ' + orderCount + ' 个订单增加费用')
batchOpen.value = false
selectedMap.value = new Map()
orderTableRef.value?.clearSelection()
loadList()
}).catch(() => {
/* 取消或接口失败时保留弹框 */
}).finally(() => {
batchSaving.value = false
})
}
@@ -603,12 +418,6 @@ function openDetail(row) {
})
}
function onDetailUpdated(data) {
if (data) {
detail.value = data
}
}
function openFees(row) {
feeTitle.value = (row.orderNo || '订单') + '的应付费用'
feeBillId.value = row.billId
@@ -1022,20 +831,6 @@ loadList()
border: 1px solid var(--el-border-color);
}
.fee-tools { margin-bottom: 8px; text-align: right; }
.picked-count { margin-left: 12px; color: var(--el-text-color-secondary); font-size: 13px; }
.batch-block { margin-bottom: 16px; }
.batch-order-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
max-height: 132px;
overflow: auto;
padding: 10px 12px;
border: 1px solid var(--el-border-color);
border-top: none;
}
.batch-orders .fee-head { margin-bottom: 0; }
.batch-order-empty { color: var(--el-text-color-secondary); font-size: 13px; line-height: 24px; }
.log-change { line-height: 1.6; }
.log-empty { color: var(--el-text-color-secondary); }
.rebill-progress__msg { margin-top: 12px; color: var(--el-text-color-regular); }
@@ -0,0 +1,189 @@
<template>
<el-dialog
v-model="visible"
title="选择渠道"
width="920px"
append-to-body
destroy-on-close
@opened="onOpened"
>
<div class="picker-bar">
<el-input
v-model="keyword"
clearable
placeholder="搜索渠道编码、渠道名称"
class="picker-search"
/>
<span class="picker-meta">共 {{ filteredRows.length }} 项,已选 {{ picked.length }} 项</span>
</div>
<el-table
ref="tableRef"
v-loading="loading"
:data="filteredRows"
row-key="id"
border
size="small"
max-height="420"
empty-text="暂无可选渠道"
@selection-change="onSelectionChange"
>
<el-table-column type="selection" width="46" :selectable="canSelect" />
<el-table-column prop="channelCode" label="渠道编码" min-width="140" show-overflow-tooltip />
<el-table-column prop="channelName" label="渠道名称" min-width="200" show-overflow-tooltip />
<el-table-column label="状态" width="90" align="center">
<template #default="{ row }">
<el-tag v-if="String(row.blOpen) === '1'" size="small" type="success">启用</el-tag>
<el-tag v-else size="small" type="info">停用</el-tag>
</template>
</el-table-column>
</el-table>
<div class="picker-hint">
绑定为收款(AR),落库 srv_channel_product_map;一个渠道同一收付类型仅保留一条产品映射。已绑定渠道不可重复勾选。
</div>
<template #footer>
<el-button @click="visible = false">取 消</el-button>
<el-button type="primary" :disabled="!picked.length" @click="submit">确 定</el-button>
</template>
</el-dialog>
</template>
<script setup name="LabelChannelPickerDialog">
import { listChannelOptions } from '@/api/masterdata/serviceChannel'
const props = defineProps({
modelValue: { type: Boolean, default: false },
/** 已绑定的渠道 id,用于禁用重复勾选 */
excludeChannelIds: { type: Array, default: () => [] }
})
const emit = defineEmits(['update:modelValue', 'confirm'])
const { proxy } = getCurrentInstance()
const tableRef = ref()
const loading = ref(false)
const keyword = ref('')
const rows = ref([])
const pickedIds = ref(new Set())
const syncing = ref(false)
const visible = computed({
get: () => props.modelValue,
set: v => emit('update:modelValue', v)
})
const excludeSet = computed(() => new Set((props.excludeChannelIds || []).map(id => String(id))))
function canSelect(row) {
if (row?.id == null) return false
return !excludeSet.value.has(String(row.id))
}
const filteredRows = computed(() => {
const text = String(keyword.value || '').trim().toLowerCase()
const list = rows.value || []
if (!text) return list
return list.filter(row => {
const bag = [row.channelCode, row.channelName, row.id]
.map(v => String(v ?? '').toLowerCase())
return bag.some(item => item.includes(text))
})
})
const picked = computed(() => {
const ids = pickedIds.value
return (rows.value || []).filter(row => row?.id != null && ids.has(String(row.id)) && canSelect(row))
})
function onSelectionChange(selection) {
if (syncing.value) return
const visibleIds = new Set((filteredRows.value || []).map(row => String(row.id)))
const next = new Set(pickedIds.value)
for (const id of visibleIds) {
next.delete(id)
}
for (const row of selection || []) {
if (row?.id != null && canSelect(row)) next.add(String(row.id))
}
pickedIds.value = next
}
function restoreSelection() {
const table = tableRef.value
if (!table) return
syncing.value = true
table.clearSelection()
for (const row of filteredRows.value || []) {
if (row?.id != null && pickedIds.value.has(String(row.id))) {
table.toggleRowSelection(row, true)
}
}
nextTick(() => {
syncing.value = false
})
}
async function loadRows() {
loading.value = true
try {
const res = await listChannelOptions({ blOpen: '1' })
rows.value = res.data || []
} catch (e) {
rows.value = []
} finally {
loading.value = false
nextTick(() => restoreSelection())
}
}
function onOpened() {
keyword.value = ''
pickedIds.value = new Set()
nextTick(() => {
tableRef.value?.clearSelection?.()
})
loadRows()
}
function submit() {
const list = picked.value
if (!list.length) {
proxy.$modal.msgWarning('请先勾选要添加的渠道')
return
}
emit('confirm', list)
visible.value = false
}
watch(keyword, () => {
nextTick(() => restoreSelection())
})
watch(() => props.modelValue, v => {
if (v && !rows.value.length) loadRows()
})
</script>
<style scoped>
.picker-bar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 10px;
}
.picker-search {
width: 320px;
}
.picker-meta {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.picker-hint {
margin-top: 10px;
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 1.5;
}
</style>
@@ -73,46 +73,11 @@
</template>
</el-drawer>
<el-dialog
<label-channel-picker-dialog
v-model="addVisible"
:title="addTitle"
width="560px"
append-to-body
destroy-on-close
@closed="onAddClosed"
>
<div v-loading="addLoading">
<el-form label-width="88px">
<el-form-item :label="lblProduct">
<span>{{ bindProductName }}</span>
</el-form-item>
<el-form-item :label="lblChannels">
<el-select
v-model="addChannelIds"
multiple
filterable
clearable
collapse-tags
collapse-tags-tooltip
:placeholder="phChannels"
style="width: 100%"
>
<el-option
v-for="item in addableChannelOptions"
:key="item.id"
:label="channelOptionLabel(item)"
:value="String(item.id)"
/>
</el-select>
</el-form-item>
<div class="bind-hint">{{ bindHint }}</div>
</el-form>
</div>
<template #footer>
<el-button @click="addVisible = false">取消</el-button>
<el-button type="primary" :loading="addSaving" @click="submitAddChannels">保存</el-button>
</template>
</el-dialog>
:exclude-channel-ids="currentBoundIds()"
@confirm="onPickerConfirm"
/>
<el-drawer
v-model="detailVisible"
@@ -140,8 +105,8 @@ import {
replaceLabelProductChannels,
getLabelProduct
} from '@/api/price/label'
import { listChannelOptions } from '@/api/masterdata/serviceChannel'
import LabelConfigDetail from './LabelConfigDetail.vue'
import LabelChannelPickerDialog from './LabelChannelPickerDialog.vue'
const props = defineProps({
visible: { type: Boolean, default: false },
@@ -159,12 +124,9 @@ const bindListLoading = ref(false)
const bindProductId = ref(null)
const bindProductName = ref('')
const boundChannels = ref([])
const channelOptions = ref([])
const addVisible = ref(false)
const addLoading = ref(false)
const addSaving = ref(false)
const addChannelIds = ref([])
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailProduct = ref(null)
@@ -186,12 +148,7 @@ const colBoundChannels = '绑定渠道'
const colAction = '操作'
const colChannelCode = '渠道编码'
const colChannelName = '渠道名称'
const lblProduct = '产品'
const lblChannels = '添加渠道'
const phChannels = '请选择要添加的渠道(可多选)'
const bindHint = '绑定为收款(AR),落库 srv_channel_product_map;一个渠道同一收付类型仅保留一条产品映射。'
const emptyBound = '暂无绑定渠道'
const addTitle = '添加渠道'
const title = computed(() => {
const v = props.version || {}
@@ -212,11 +169,6 @@ const filteredRows = computed(() => {
})
})
const addableChannelOptions = computed(() => {
const bound = new Set((boundChannels.value || []).map(item => String(item.channelId)))
return (channelOptions.value || []).filter(item => item && item.id != null && !bound.has(String(item.id)))
})
function formatHour(val) {
if (!val) return ''
const text = String(val).replace('T', ' ')
@@ -269,12 +221,6 @@ async function load() {
}
}
async function ensureChannelOptions() {
if (channelOptions.value.length) return
const res = await listChannelOptions({ blOpen: '1' })
channelOptions.value = res.data || []
}
async function loadBoundChannels() {
if (!bindProductId.value) {
boundChannels.value = []
@@ -323,33 +269,21 @@ function onBindListClosed() {
bindProductName.value = ''
boundChannels.value = []
addVisible.value = false
addChannelIds.value = []
}
async function openAddChannels() {
addChannelIds.value = []
addVisible.value = true
addLoading.value = true
try {
await ensureChannelOptions()
} finally {
addLoading.value = false
}
}
function onAddClosed() {
addChannelIds.value = []
}
function currentBoundIds() {
return (boundChannels.value || []).map(item => String(item.channelId)).filter(Boolean)
}
function submitAddChannels() {
function onPickerConfirm(list) {
if (!bindProductId.value) return
const selected = (addChannelIds.value || []).map(String).filter(Boolean)
const selected = (list || []).map(item => String(item.id)).filter(Boolean)
if (!selected.length) {
proxy.$modal.msgWarning('请先选择要添加的渠道')
proxy.$modal.msgWarning('请先勾选要添加的渠道')
return
}
const merged = Array.from(new Set(currentBoundIds().concat(selected)))
@@ -398,10 +332,4 @@ watch(() => [props.visible, props.priceSetId, props.version?.versionNo], ([vis])
justify-content: flex-end;
margin-bottom: 12px;
}
.bind-hint {
margin: -4px 0 0 88px;
color: #909399;
font-size: 12px;
line-height: 1.5;
}
</style>
+50 -4
View File
@@ -166,7 +166,7 @@ const pageBanner = computed(() => {
return `新建版本:${name}(${code})`
})
const headerTip = computed(() => {
if (editVersionMode.value) return '可重新导入或修改明细;完成后按ID更新/新增/删除,不新增版本号'
if (editVersionMode.value) return '可重新导入或修改明细;再导入按产品合并(同名覆盖、其余保留),完成后按ID更新/新增/删除,不新增版本号'
if (newVersionMode.value) return '导入后生成待生效新版本;生效时间请回详情页设置'
return '打单价卡与应付独立;解析后回填到此表,可删除不需要的产品,编辑明细后点完成保存'
})
@@ -246,6 +246,23 @@ function productKey(row) {
return row?.rowKey || `${row?.sheetName || ''}-${row?.productName || ''}`
}
/** 用于编辑再导入时判断同一产品(dict/名称/表名任一相等即命中) */
function productTokens(row) {
return [row?.dictValue, row?.productName, row?.sheetName]
.map(s => String(s || '').toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]/g, ''))
.filter(Boolean)
}
function productIdentity(row) {
return productTokens(row)[0] || ''
}
function sameProduct(left, right) {
const a = new Set(productTokens(left))
const b = productTokens(right)
return b.some(token => a.has(token))
}
function aliveDetailRows(list) {
return (list || []).filter(row => row && row.deleted !== true)
}
@@ -319,14 +336,43 @@ async function removeSelectedProducts() {
}
function onImportConfirm(payload) {
const incoming = (payload?.products || []).filter(Boolean)
if (editVersionMode.value) {
for (const row of productRows.value || []) {
if (row?.versionId || row?.productId) markProductRemoved(row)
// 编辑再导入:按产品合并,不清空其它产品;同名则用新价卡覆盖
const matched = new Set()
const replaced = []
for (const neu of incoming) {
const key = productIdentity(neu)
if (!key) {
replaced.push(neu)
continue
}
const old = (productRows.value || []).find(row => sameProduct(row, neu))
if (old) {
for (const token of productTokens(old)) matched.add(token)
for (const token of productTokens(neu)) matched.add(token)
if (old.versionId || old.productId) {
markProductRemoved(old)
}
replaced.push({
...neu,
productId: old.productId ?? neu.productId,
versionId: null,
termId: null,
rowKey: `${neu.sheetName || ''}-${neu.productName || ''}-${old.productId || old.versionId || ''}`,
duplicated: true
})
} else {
for (const token of productTokens(neu)) matched.add(token)
replaced.push(neu)
}
}
const kept = (productRows.value || []).filter(row => !productTokens(row).some(token => matched.has(token)))
productRows.value = [...kept, ...replaced]
} else {
removedProducts.value = []
productRows.value = incoming
}
productRows.value = payload?.products || []
selectedProducts.value = []
importMeta.sourceFile = payload?.sourceFile || ''
importMeta.supplierName = payload?.supplierName || ''
@@ -295,26 +295,19 @@ function normalizeProducts(list) {
productCode: p.productCode || p.code,
productName: p.productName || p.name || p.productCode || p.code,
taxMode: p.taxMode,
surcharges: []
surcharges: Array.isArray(p.surcharges) ? p.surcharges : []
}))
}
/** 按产品汇总版本明细上的附加费(scId 去重) */
function attachProductSurcharges(productList, detailRows) {
function mergeProductSurcharges(productList, optionProducts) {
const byCode = new Map()
for (const d of detailRows || []) {
if (!d?.productCode) continue
if (!byCode.has(d.productCode)) byCode.set(d.productCode, new Map())
const map = byCode.get(d.productCode)
for (const s of d.surcharges || []) {
if (!s || s.scId == null) continue
const key = String(s.scId)
if (!map.has(key)) map.set(key, s)
}
for (const p of optionProducts || []) {
if (!p?.productCode) continue
byCode.set(p.productCode, p.surcharges || [])
}
return (productList || []).map(p => ({
...p,
surcharges: [...(byCode.get(p.productCode)?.values() || [])]
surcharges: byCode.get(p.productCode) || p.surcharges || []
}))
}
@@ -327,14 +320,15 @@ async function loadProducts() {
}
loading.value = true
try {
// 轻量:options 带产品+附加费,不再拉整版 byVersion 明细
const res = await api.listSetDetailOptions(psvId)
const optList = normalizeProducts((res.data || {}).products || [])
let list = normalizeProducts(v.products)
if (!list.length) {
const res = await api.listSetDetailOptions(psvId)
const data = res.data || {}
list = normalizeProducts(data.products || [])
products.value = optList
} else {
products.value = mergeProductSurcharges(list, optList)
}
const detailRes = await api.listSetDetailByVersion(psvId)
products.value = attachProductSurcharges(list, detailRes.data || [])
} catch (e) {
products.value = normalizeProducts(v.products)
} finally {