This commit is contained in:
wuweihua
2026-11-20 14:07:21 +08:00
14 changed files with 427 additions and 69 deletions
@@ -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,41 @@ class ArBillTemplateSelectionTest {
assertEquals("应收账单汇总模板", options.get(0).getTemplateName());
}
@Test
void fixedPayeeTemplatesRejectMismatchesBeforeCreatingExportTasks() {
ArExportTemplate fixed = template(3L, ArBillWorkbookWriters.GUANGZHOU_TEMPLATE_CODE);
fixed.setStorageKey("templates/receivable/ar_bill_template_gz.xlsx");
when(templates.selectEnabledById(3L, "AR_BILL", bill.getBillDate())).thenReturn(fixed);
bill.setBankAccountName("威狮国际供应链(深圳)有限公司广州分公司");
bill.setBankAccountNo("44050129162500001250");
bill.setBankName("中国建设银行股份有限公司广州设计之都支行");
assertEquals(3L, service.exportBill(7L, 3L, "admin", "matching").getTemplateId());
bill.setBankAccountNo("1234567890");
ServiceException error = assertThrows(ServiceException.class,
() -> service.exportBill(7L, 3L, "admin", "mismatch"));
assertTrue(error.getMessage().contains("收款信息"));
verify(exports, times(1)).insert(any());
}
@Test
void fixedPayeeTemplateValidationChecksNameAccountAndBankForBothTemplates() {
ArBillWorkbookWriters writers = new ArBillWorkbookWriters(new DefaultArBillWorkbookWriter(), new SummaryArBillWorkbookWriter());
ArExportTemplate fixed = template(3L, ArBillWorkbookWriters.JIYUN_TEMPLATE_CODE);
fixed.setStorageKey("templates/receivable/ar_bill_template_jy.xlsx");
bill.setBankAccountName("威狮国际集运物流(深圳)有限公司");
bill.setBankAccountNo("86021110000892050");
bill.setBankName("宁波银行深圳后海支行");
assertDoesNotThrow(() -> writers.validatePayee(bill, fixed));
bill.setBankName("其他银行");
assertThrows(ServiceException.class, () -> writers.validatePayee(bill, fixed));
bill.setBankName("宁波银行深圳后海支行");
bill.setBankAccountName("其他公司");
assertThrows(ServiceException.class, () -> writers.validatePayee(bill, fixed));
bill.setBankAccountName(null);
assertThrows(ServiceException.class, () -> writers.validatePayee(bill, fixed));
}
@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;
@@ -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 "";
@@ -1,5 +1,8 @@
package com.bms.receivable.export;
import java.io.IOException;
import com.bms.common.exception.ServiceException;
import com.bms.receivable.domain.ArBill;
import com.bms.receivable.domain.ArExportTemplate;
import org.springframework.stereotype.Component;
@@ -24,4 +27,17 @@ public class ArBillWorkbookWriters {
public boolean isSummary(ArExportTemplate template) {
return SUMMARY_TEMPLATE_CODE.equals(template.getTemplateCode());
}
/** 固定收款信息的模板必须与账单快照一致,避免导出错误的收款账户。 */
public void validatePayee(ArBill bill, ArExportTemplate template) {
if (!GUANGZHOU_TEMPLATE_CODE.equals(template.getTemplateCode())
&& !JIYUN_TEMPLATE_CODE.equals(template.getTemplateCode())) return;
try {
if (!defaultWriter.matchesTemplatePayee(bill, template)) {
throw new ServiceException("所选模板的固定收款信息与账单收款账户不一致,请选择匹配的模板");
}
} catch (IOException e) {
throw new ServiceException("无法读取所选模板的收款信息,请检查模板配置");
}
}
}
@@ -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;
@@ -22,8 +19,10 @@ import java.util.zip.ZipOutputStream;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import com.bms.common.utils.StringUtils;
import com.bms.receivable.domain.ArBill;
@@ -74,6 +73,28 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
int formula, int failedFormula) {
}
/** 首表 C7:C9 是固定开户名、账号和开户行;空值不得通过匹配。 */
public boolean matchesTemplatePayee(ArBill bill, ArExportTemplate template) throws IOException {
try (InputStream input = openTemplateStream(template); XSSFWorkbook workbook = new XSSFWorkbook(input)) {
if (workbook.getNumberOfSheets() == 0) return false;
var sheet = workbook.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
String[] expected = {bill.getBankAccountName(), bill.getBankAccountNo(), bill.getBankName()};
for (int i = 0; i < expected.length; i++) {
var row = sheet.getRow(6 + i);
var cell = row == null ? null : row.getCell(2);
String actual = cell == null ? "" : formatter.formatCellValue(cell);
String snapshot = normalizePayeeValue(expected[i]);
if (snapshot.isEmpty() || !snapshot.equals(normalizePayeeValue(actual))) return false;
}
return true;
}
}
private String normalizePayeeValue(String value) {
return value == null ? "" : value.replaceAll("[\\s\\p{Z}]+", "");
}
@Override
public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException {
// 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。
@@ -534,34 +555,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();
@@ -1038,6 +1051,7 @@ public class ArBillServiceImpl implements IArBillService {
bill.getStatus(), templateId == null ? "未配置启用中的应收账单默认导出模板"
: "所选应收账单模板不存在、已停用或不在生效期内,请重新选择", operator, requestId);
}
workbookWriters.validatePayee(bill, template);
ArBillExport processing = exportMapper.selectProcessingByBillAndTemplate(arBillId, template.getTemplateId());
if (processing != null) {
log.info("应收账单导出任务已存在,operator={}, requestId={}, arBillId={}, exportId={}, status={}, costMs={}",
@@ -1115,6 +1129,7 @@ public class ArBillServiceImpl implements IArBillService {
String objectKey = "ar/bill/" + DateUtils.datePath() + "/" + IdUtils.fastSimpleUUID() + ".xlsx";
temp = Files.createTempFile("ar-bill-export-", ".xlsx");
ArExportTemplate template = resolveExportTemplate(export, bill);
workbookWriters.validatePayee(bill, template);
workbookWriters.select(template).write(bill, template, temp);
export.setFileSize(Files.size(temp));
export.setFileHash(sha256(temp));
@@ -1359,7 +1374,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 {