From 69491b07d9ffe1c094862fc9b98eeab9049545a3 Mon Sep 17 00:00:00 2001 From: caojia <1301869380@qq.com> Date: Wed, 18 Nov 2026 15:59:08 +0800 Subject: [PATCH 1/4] =?UTF-8?q?:sparkles:=20=E6=94=AF=E6=8C=81=E5=BA=94?= =?UTF-8?q?=E6=94=B6=E8=B4=A6=E5=8D=95=E9=80=89=E6=8B=A9=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=B9=B6=E5=AF=BC=E5=87=BA=E4=BA=A7=E5=93=81=E6=B1=87=E6=80=BB?= =?UTF-8?q?=E4=B8=8E=E8=BF=90=E8=B4=B9=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../receivable/ArBillController.java | 15 +- .../export/ArBillTemplateSelectionTest.java | 144 +++ .../export/ArBillWorkbookWriterTest.java | 244 +++++ .../domain/vo/ArBillExportRequest.java | 9 + .../domain/vo/ArBillExportTemplateOption.java | 24 + .../export/ArBillWorkbookSupport.java | 372 +++++++ .../export/ArBillWorkbookWriter.java | 11 + .../export/ArBillWorkbookWriters.java | 25 + .../export/DefaultArBillWorkbookWriter.java | 596 +++++++++++ .../export/SummaryArBillWorkbookWriter.java | 352 +++++++ .../receivable/mapper/ArBillExportMapper.java | 3 +- .../mapper/ArExportTemplateMapper.java | 8 + .../receivable/service/IArBillService.java | 5 +- .../service/impl/ArBillServiceImpl.java | 971 +----------------- .../mapper/receivable/ArBillExportMapper.xml | 3 +- .../receivable/ArExportTemplateMapper.xml | 24 +- .../receivable/ar_bill_template_summary.xlsx | Bin 0 -> 14399 bytes bms-front/src/api/ar/bill.js | 8 +- .../views/ar/bill/components/BillDetail.vue | 3 +- .../ar/bill/components/ExportBillDialog.vue | 86 ++ bms-front/src/views/ar/bill/index.vue | 31 +- 21 files changed, 1973 insertions(+), 961 deletions(-) create mode 100644 bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillTemplateSelectionTest.java create mode 100644 bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillWorkbookWriterTest.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportRequest.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportTemplateOption.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookSupport.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriter.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriters.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/export/DefaultArBillWorkbookWriter.java create mode 100644 bms-back/bms-system/src/main/java/com/bms/receivable/export/SummaryArBillWorkbookWriter.java create mode 100644 bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_summary.xlsx create mode 100644 bms-front/src/views/ar/bill/components/ExportBillDialog.vue diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/receivable/ArBillController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/receivable/ArBillController.java index 6998bea7..5d8bb95b 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/receivable/ArBillController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/receivable/ArBillController.java @@ -25,6 +25,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.vo.ArBillExportRequest; import com.bms.receivable.domain.ArBankAccount; import com.bms.receivable.domain.ArBillDetailFee; import com.bms.receivable.domain.ArBillGenerateTask; @@ -311,16 +312,22 @@ public class ArBillController extends BaseController { return success(voidTaskService.get(taskId)); } - /** - * 仅提交导出任务;前端通过导出任务状态接口轮询并在完成后下载。 - */ + @PreAuthorize("@ss.hasPermi('ar:bill:export')") + @GetMapping("/{arBillId}/export-templates") + public AjaxResult exportTemplates(@PathVariable Long arBillId) { + return success(billService.selectExportTemplates(arBillId)); + } + + /** 仅提交导出任务;前端轮询任务状态后下载。 */ @Log(title = "应收账单导出", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('ar:bill:export')") @PostMapping("/{arBillId}/export") public AjaxResult export(@PathVariable Long arBillId, + @RequestBody(required = false) ArBillExportRequest request, @RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) { String requestId = requestId(null, headerRequestId); - return success(billService.exportBill(arBillId, getUsername(), requestId)).put("request_id", requestId); + return success(billService.exportBill(arBillId, request == null ? null : request.getTemplateId(), + getUsername(), requestId)).put("request_id", requestId); } /** diff --git a/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillTemplateSelectionTest.java b/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillTemplateSelectionTest.java new file mode 100644 index 00000000..bc4e278d --- /dev/null +++ b/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillTemplateSelectionTest.java @@ -0,0 +1,144 @@ +package com.bms.receivable.export; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.InputStream; +import java.sql.Date; +import java.util.List; +import java.util.Map; + +import com.bms.common.core.domain.model.LoginUser; +import com.bms.common.exception.ServiceException; +import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.ArBillExport; +import com.bms.receivable.domain.ArExportTemplate; +import com.bms.receivable.event.ArBillExportTaskEvent; +import com.bms.receivable.mapper.ArBillExportMapper; +import com.bms.receivable.mapper.ArBillLogMapper; +import com.bms.receivable.mapper.ArBillMapper; +import com.bms.receivable.mapper.ArExportTemplateMapper; +import com.bms.receivable.security.ArBillScopeResolver; +import com.bms.receivable.service.ArBillVoidTaskService; +import com.bms.receivable.service.IArBillLogService; +import com.bms.receivable.service.impl.ArBillServiceImpl; +import org.apache.ibatis.builder.xml.XMLMapperBuilder; +import org.apache.ibatis.session.Configuration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +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 ArBillTemplateSelectionTest { + private final ArBillServiceImpl service = new ArBillServiceImpl(); + private final ArBillMapper bills = mock(ArBillMapper.class); + private final ArExportTemplateMapper templates = mock(ArExportTemplateMapper.class); + private final ArBillExportMapper exports = mock(ArBillExportMapper.class); + private final ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); + private final ArBill bill = new ArBill(); + + @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, "exportTemplateMapper", templates); + ReflectionTestUtils.setField(service, "exportMapper", exports); + ReflectionTestUtils.setField(service, "billScope", mock(ArBillScopeResolver.class)); + ReflectionTestUtils.setField(service, "voidTaskService", mock(ArBillVoidTaskService.class)); + ReflectionTestUtils.setField(service, "logMapper", mock(ArBillLogMapper.class)); + ReflectionTestUtils.setField(service, "logService", mock(IArBillLogService.class)); + ReflectionTestUtils.setField(service, "eventPublisher", publisher); + ReflectionTestUtils.setField(service, "workbookWriters", new ArBillWorkbookWriters( + new DefaultArBillWorkbookWriter(), new SummaryArBillWorkbookWriter())); + bill.setArBillId(7L); + bill.setGenerationStatus("READY"); + bill.setStatus("CONFIRMED"); + bill.setBillDate(Date.valueOf("2026-10-31")); + bill.setBillPeriodEnd(Date.valueOf("2026-10-31")); + bill.setCustomerName("测试客户"); + bill.setCustomerCode("C1"); + when(bills.selectArBillByIdForUpdate(7L)).thenReturn(bill); + when(bills.selectArBillById(7L)).thenReturn(bill); + when(exports.insert(any())).thenAnswer(invocation -> { + ((ArBillExport) invocation.getArgument(0)).setExportId(99L); + return 1; + }); + } + + @AfterEach + void clearLogin() { SecurityContextHolder.clearContext(); } + + @Test + void bindsSelectedTemplateAndOnlyReusesTasksWithTheSameTemplate() { + ArExportTemplate selected = template(2L, "AR_BILL_SUMMARY"); + when(templates.selectEnabledById(2L, "AR_BILL", bill.getBillDate())).thenReturn(selected); + ArBillExport task = service.exportBill(7L, 2L, "admin", "request-summary"); + assertEquals(2L, task.getTemplateId()); + assertEquals("AR_BILL_SUMMARY", task.getTemplateCode()); + assertEquals("1.0", task.getTemplateVersion()); + assertEquals(selected.getStorageKey(), task.getTemplateStorageKey()); + assertTrue(task.getFileName().endsWith("_汇总.xlsx")); + verify(exports).selectProcessingByBillAndTemplate(7L, 2L); + verify(publisher).publishEvent(any(ArBillExportTaskEvent.class)); + + when(exports.selectProcessingByBillAndTemplate(7L, 2L)).thenReturn(task); + assertSame(task, service.exportBill(7L, 2L, "admin", "request-repeat")); + verify(exports, times(1)).insert(any()); + verify(templates, never()).selectDefaultEnabled(anyString(), any()); + } + + @Test + void omittingTemplateRetainsDefaultBehaviorAndInvalidSelectionCannotQueueAnExport() { + when(templates.selectDefaultEnabled("AR_BILL", bill.getBillDate())).thenReturn(template(1L, "AR_CUSTOMER_BILL")); + ArBillExport task = service.exportBill(7L, null, "admin", "request-default"); + assertEquals(1L, task.getTemplateId()); + assertFalse(task.getFileName().contains("汇总")); + assertThrows(ServiceException.class, () -> service.exportBill(7L, 9L, "admin", "request-invalid")); + verify(exports, times(1)).insert(any()); + } + + @Test + void optionsUseTheBillEffectiveDateAndOnlyExposeChoiceMetadata() { + when(templates.selectEnabledList("AR_BILL", bill.getBillDate())).thenReturn(List.of(template(2L, "AR_BILL_SUMMARY"))); + var options = service.selectExportTemplates(7L); + assertEquals(2L, options.get(0).getTemplateId()); + assertEquals("应收账单汇总模板", options.get(0).getTemplateName()); + } + + @Test + void mapperQueriesEnforceBusinessStatusEffectiveDatesAndTaskTemplate() throws Exception { + Configuration configuration = new Configuration(); + configuration.getTypeAliasRegistry().registerAlias("ArExportTemplate", ArExportTemplate.class); + configuration.getTypeAliasRegistry().registerAlias("ArBillExport", ArBillExport.class); + for (String resource : List.of("mapper/receivable/ArExportTemplateMapper.xml", "mapper/receivable/ArBillExportMapper.xml")) { + try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource)) { + new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse(); + } + } + String sql = configuration.getMappedStatement("com.bms.receivable.mapper.ArExportTemplateMapper.selectEnabledById") + .getBoundSql(Map.of("templateId", 2L, "businessType", "AR_BILL", "effectiveDate", bill.getBillDate())).getSql(); + for (String condition : List.of("business_type = ?", "status = 'ENABLED'", "effective_start <= ?", + "effective_end >= ?", "template_id = ?")) assertTrue(sql.contains(condition), sql); + String taskSql = configuration.getMappedStatement("com.bms.receivable.mapper.ArBillExportMapper.selectProcessingByBillAndTemplate") + .getBoundSql(Map.of("arBillId", 7L, "templateId", 2L)).getSql(); + assertTrue(taskSql.contains("template_id = ?")); + assertTrue(taskSql.contains("export_status = 'PROCESSING'")); + } + + private ArExportTemplate template(Long id, String code) { + ArExportTemplate template = new ArExportTemplate(); + template.setTemplateId(id); + template.setTemplateCode(code); + template.setTemplateName("应收账单汇总模板"); + template.setTemplateVersion("1.0"); + template.setStorageType("CLASSPATH"); + template.setStorageKey("templates/receivable/ar_bill_template_summary.xlsx"); + return template; + } +} diff --git a/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillWorkbookWriterTest.java b/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillWorkbookWriterTest.java new file mode 100644 index 00000000..ecbf1782 --- /dev/null +++ b/bms-back/bms-admin/src/test/java/com/bms/receivable/export/ArBillWorkbookWriterTest.java @@ -0,0 +1,244 @@ +package com.bms.receivable.export; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.file.Path; +import java.sql.Date; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.ArBillDetail; +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.FormulaEvaluator; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ArBillWorkbookWriterTest { + @TempDir + Path temporary; + + @Test + void summaryAndDetailsReconcileSnapshotAmountsAndKeepFreightFormulaAndBlankFields() throws Exception { + ArBill bill = bill(3, "13.20", "CNY"); + List 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); + writer.write(bill, summaryTemplate(), target); + try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) { + assertEquals(2, workbook.getNumberOfSheets()); + assertEquals("账单汇总", workbook.getSheetName(0)); + assertEquals("运费明细", workbook.getSheetName(1)); + XSSFSheet summary = workbook.getSheetAt(0); + XSSFSheet freight = workbook.getSheetAt(1); + 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("国际货物运输代理服务费", 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); + assertEquals("SUMIF(F4:F5,F7,E4:E5)", summary.getRow(6).getCell(4).getCellFormula()); + assertEquals(13.20, summary.getRow(6).getCell(4).getNumericCellValue(), 0.00001); + assertEquals("收款账户快照", summary.getRow(11).getCell(1).getStringCellValue()); + assertEquals("1234 5678 90", summary.getRow(12).getCell(1).getStringCellValue()); + 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(17).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()); + assertEquals("00123", freight.getRow(4).getCell(6).getStringCellValue()); + assertEquals(9.5, freight.getRow(4).getCell(8).getNumericCellValue()); + assertEquals("ROUND(J5*L5,2)", freight.getRow(4).getCell(13).getCellFormula()); + assertEquals(2.81, freight.getRow(4).getCell(13).getNumericCellValue(), 0.00001); + assertEquals(CellType.NUMERIC, freight.getRow(4).getCell(15).getCellType()); + assertEquals(10.12, freight.getRow(4).getCell(15).getNumericCellValue(), 0.00001); + assertEquals(-2.22, freight.getRow(5).getCell(15).getNumericCellValue(), 0.00001); + assertEquals(20, freight.getRow(4).getLastCellNum()); + assertEquals("说明", freight.getRow(3).getCell(19).getStringCellValue()); + assertEquals("备注 & <快照>", freight.getRow(4).getCell(18).getStringCellValue()); + assertEquals("", freight.getRow(4).getCell(19).getStringCellValue()); + for (int column : new int[]{7, 10, 14, 16, 17}) { + assertEquals("", freight.getRow(4).getCell(column).getStringCellValue()); + } + assertEquals("SUM(P5:P7)", freight.getRow(8).getCell(15).getCellFormula()); + assertEquals(13.20, freight.getRow(8).getCell(15).getNumericCellValue(), 0.00001); + FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); + assertEquals(13.20, evaluator.evaluate(summary.getRow(6).getCell(4)).getNumberValue(), 0.00001); + assertEquals(13.20, evaluator.evaluate(freight.getRow(8).getCell(15)).getNumberValue(), 0.00001); + assertEquals(2.81, evaluator.evaluate(freight.getRow(4).getCell(13)).getNumberValue(), 0.00001); + assertFalse(workbook.getPrintArea(0).contains("#REF!")); + assertTrue(workbook.getPrintArea(1).contains("$T$9")); + } + } + + @Test + void readsSeveralCursorBatchesOnceAndExportsAllRowsToTheSameDetailSheet() throws Exception { + int count = 4001; + SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); + writer.detailMapper = mock(ArBillDetailMapper.class); + List cursors = new ArrayList<>(); + when(writer.detailMapper.selectExportPage(eq(7L), anyInt(), eq(2000))).thenAnswer(invocation -> { + int previous = invocation.getArgument(1); + cursors.add(previous); + return IntStream.rangeClosed(previous + 1, Math.min(previous + 2000, count)) + .mapToObj(number -> detail(number, "P" + (number % 3), "1.00")).toList(); + }); + Path target = temporary.resolve("large.xlsx"); + writer.write(bill(count, "4001.00", "CNY"), summaryTemplate(), target); + assertEquals(List.of(0, 2000, 4000, 4001), cursors); + try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) { + assertEquals(2, workbook.getNumberOfSheets()); + XSSFSheet sheet = workbook.getSheetAt(1); + assertEquals("ROUND(J4005*L4005,2)", sheet.getRow(4004).getCell(13).getCellFormula()); + assertEquals("SUM(P5:P4005)", sheet.getRow(4006).getCell(15).getCellFormula()); + assertEquals(4001, sheet.getRow(4006).getCell(15).getNumericCellValue()); + assertEquals(4001, workbook.getSheetAt(0).getRow(7).getCell(4).getNumericCellValue()); + } + } + + @Test + void usesBillCurrencyForHeadersAndKeepsFailedOrderHighlightAndExplanation() throws Exception { + ArBillDetail detail = detail(1, "P1", "1.00"); + detail.setCurrency("USD"); + detail.setBillingFailStatus(2); + ArBillDetail withoutRemark = detail(2, "P1", "1.00"); + withoutRemark.setCurrency("USD"); + withoutRemark.setBillingFailStatus(2); + withoutRemark.setRemark(null); + ArBillDetail success = detail(3, "P1", "1.00"); + success.setCurrency("USD"); + success.setBillingFailStatus(0); + Path target = temporary.resolve("usd.xlsx"); + summaryWriter(List.of(detail, withoutRemark, success)).write(bill(3, "3.00", "USD"), summaryTemplate(), target); + try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) { + XSSFSheet freight = workbook.getSheetAt(1); + for (int column : new int[]{11, 12, 13, 14, 15}) { + String title = freight.getRow(3).getCell(column).getStringCellValue(); + assertTrue(title.contains("USD")); + assertFalse(title.contains("CNY")); + } + assertEquals("USD", workbook.getSheetAt(0).getRow(5).getCell(5).getStringCellValue()); + for (int column = 0; column < 20; column++) { + assertEquals(IndexedColors.YELLOW.getIndex(), freight.getRow(4).getCell(column).getCellStyle().getFillForegroundColor()); + } + assertEquals("备注 & <快照>", freight.getRow(4).getCell(18).getStringCellValue()); + assertEquals("销售价未匹配国家", freight.getRow(4).getCell(19).getStringCellValue()); + assertEquals("", freight.getRow(5).getCell(18).getStringCellValue()); + assertEquals("销售价未匹配国家", freight.getRow(5).getCell(19).getStringCellValue()); + assertEquals("备注 & <快照>", freight.getRow(6).getCell(18).getStringCellValue()); + assertEquals("", freight.getRow(6).getCell(19).getStringCellValue()); + } + } + + @Test + void rejectsAnExportWhoseSnapshotDetailsDoNotReconcileWithTheBill() { + IOException error = assertThrows(IOException.class, () -> summaryWriter(List.of(detail(1, "P1", "1.00"))) + .write(bill(1, "2.00", "CNY"), summaryTemplate(), temporary.resolve("mismatch.xlsx"))); + assertTrue(error.getMessage().contains("应收金额合计与账单总额不一致")); + } + + @Test + void defaultTemplateStillPreservesItsImageAndTheBlankRowBeforeBankFooter() throws Exception { + DefaultArBillWorkbookWriter writer = new DefaultArBillWorkbookWriter(); + writer.detailMapper = mapper(List.of(detail(1, "P1", "1.00"))); + 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()); + ArExportTemplate template = new ArExportTemplate(); + template.setStorageKey("templates/receivable/ar_bill_template.xlsx"); + Path target = temporary.resolve("default.xlsx"); + writer.write(bill(1, "1.00", "CNY"), template, target); + try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) { + assertEquals(1, workbook.getNumberOfSheets()); + assertEquals(1, workbook.getAllPictures().size()); + XSSFSheet sheet = workbook.getSheetAt(0); + assertEquals(21, sheet.getRow(4).getLastCellNum()); + assertEquals(1, sheet.getRow(4).getCell(18).getNumericCellValue()); + assertEquals(0, sheet.getRow(5).getPhysicalNumberOfCells()); + assertEquals("银行信息", sheet.getRow(6).getCell(1).getStringCellValue()); + assertEquals("收款账户快照", sheet.getRow(7).getCell(2).getStringCellValue()); + } + } + + private SummaryArBillWorkbookWriter summaryWriter(List details) { + SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); + writer.detailMapper = mapper(details); + return writer; + } + + private ArBillDetailMapper mapper(List rows) { + ArBillDetailMapper mapper = mock(ArBillDetailMapper.class); + when(mapper.selectExportPage(eq(7L), anyInt(), eq(2000))).thenAnswer(invocation -> { + int previous = invocation.getArgument(1); + return rows.stream().filter(row -> row.getDetailNo() > previous).limit(2000).toList(); + }); + return mapper; + } + + private ArExportTemplate summaryTemplate() { + ArExportTemplate template = new ArExportTemplate(); + template.setTemplateCode("AR_BILL_SUMMARY"); + template.setStorageKey("templates/receivable/ar_bill_template_summary.xlsx"); + return template; + } + + private ArBill bill(int count, String amount, String currency) { + ArBill bill = new ArBill(); + bill.setArBillId(7L); + bill.setCustomerCode("0000123"); + bill.setCustomerName("客户 & <测试>"); + bill.setCurrency(currency); + bill.setBillPeriodStart(Date.valueOf("2026-10-01")); + bill.setBillPeriodEnd(Date.valueOf("2026-10-31")); + bill.setOrderCount(count); + bill.setTotalAmount(new BigDecimal(amount)); + bill.setWrittenOffAmount(BigDecimal.ZERO); + bill.setUnwrittenAmount(new BigDecimal(amount)); + bill.setBankAccountName("收款账户快照"); + bill.setBankAccountNo("1234567890"); + bill.setBankName("开户行快照"); + return bill; + } + + private ArBillDetail detail(int number, String productCode, String amount) { + ArBillDetail detail = new ArBillDetail(); + detail.setDetailId((long) number); + detail.setDetailNo(number); + detail.setOrderNo("ORDER" + number); + detail.setTransferNo(String.format("%08d", number)); + detail.setTrackingNo("001234567890123456789"); + detail.setProductCode(productCode); + detail.setProductName(productCode); + detail.setReceiveTime(Date.valueOf("2026-11-05")); + detail.setCountryName("德国"); + detail.setDestPostcode("00123"); + detail.setReceiveWeight(new BigDecimal("9.5")); + detail.setActualWeight(new BigDecimal("8.5")); + detail.setChargeWeight(new BigDecimal("1.125")); + detail.setFreightRate(new BigDecimal("2.5")); + detail.setRegistrationFee(new BigDecimal("3.25")); + detail.setTotalAmount(new BigDecimal(amount)); + detail.setCurrency("CNY"); + detail.setRemark("备注 & <快照>"); + return detail; + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportRequest.java b/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportRequest.java new file mode 100644 index 00000000..b6a5b922 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportRequest.java @@ -0,0 +1,9 @@ +package com.bms.receivable.domain.vo; + +import lombok.Data; + +/** 不传模板编号时兼容原接口,使用当前生效的默认模板。 */ +@Data +public class ArBillExportRequest { + private Long templateId; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportTemplateOption.java b/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportTemplateOption.java new file mode 100644 index 00000000..f5c5ba57 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/domain/vo/ArBillExportTemplateOption.java @@ -0,0 +1,24 @@ +package com.bms.receivable.domain.vo; + +import com.bms.receivable.domain.ArExportTemplate; +import lombok.Data; + +/** 前端模板选项;不暴露服务器资源路径。 */ +@Data +public class ArBillExportTemplateOption { + private Long templateId; + private String templateCode; + private String templateName; + private String templateVersion; + private String isDefault; + + public static ArBillExportTemplateOption from(ArExportTemplate template) { + ArBillExportTemplateOption option = new ArBillExportTemplateOption(); + option.setTemplateId(template.getTemplateId()); + option.setTemplateCode(template.getTemplateCode()); + option.setTemplateName(template.getTemplateName()); + option.setTemplateVersion(template.getTemplateVersion()); + option.setIsDefault(template.getIsDefault()); + return option; + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookSupport.java b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookSupport.java new file mode 100644 index 00000000..24bd7e62 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookSupport.java @@ -0,0 +1,372 @@ +package com.bms.receivable.export; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import com.bms.common.config.BmsConfig; +import com.bms.common.utils.StringUtils; +import com.bms.common.utils.file.FileUtils; +import com.bms.price.enums.BillBillingFailStatus; +import com.bms.receivable.domain.ArBillDetail; +import com.bms.receivable.domain.ArBillDetailFee; +import com.bms.receivable.domain.ArExportTemplate; +import com.bms.receivable.mapper.ArBillDetailMapper; +import com.bms.receivable.mapper.ArBillDetailFeeMapper; + +/** 两种账单排版共用的模板读取、快照字段和 OOXML 写入工具。 */ +public abstract class ArBillWorkbookSupport implements ArBillWorkbookWriter { + protected static final String EXPORT_TEMPLATE_RESOURCE = "templates/receivable/ar_bill_template.xlsx"; + protected static final int EXPORT_PAGE_SIZE = 2000; + protected static final Pattern TEMPLATE_ROW_PATTERN = Pattern.compile( + "]*\\br=\"(\\d+)\")(?:[^>]*/>|[^>]*>.*?)", Pattern.DOTALL); + protected static final Pattern CELL_PATTERN = Pattern.compile( + "]*?)(?:/\\s*>|>(.*?))", Pattern.DOTALL); + protected static final Pattern CELL_REF_PATTERN = Pattern.compile( + "\\br\\s*=\\s*[\\\"']([A-Z]+\\d+)[\\\"']", Pattern.CASE_INSENSITIVE); + protected static final Pattern CELL_STYLE_PATTERN = Pattern.compile( + "\\bs\\s*=\\s*[\\\"'](\\d+)[\\\"']", Pattern.CASE_INSENSITIVE); + protected static final Pattern CELL_ROW_REF_PATTERN = Pattern.compile( + "(]*\\br=\")([A-Z]+)\\d+(\")"); + protected static final Pattern ROW_REF_PATTERN = Pattern.compile( + "(]*\\br=\")\\d+(\")"); + protected static final Pattern DIMENSION_PATTERN = Pattern.compile("]*/>"); + + @Autowired + protected ArBillDetailMapper detailMapper; + @Autowired + protected ArBillDetailFeeMapper detailFeeMapper; + + protected InputStream openTemplateStream(ArExportTemplate template) throws IOException { + String storageType = StringUtils.isEmpty(template.getStorageType()) ? "CLASSPATH" : template.getStorageType(); + String storageKey = StringUtils.isEmpty(template.getStorageKey()) ? EXPORT_TEMPLATE_RESOURCE : template.getStorageKey(); + if ("CLASSPATH".equalsIgnoreCase(storageType)) { + ClassPathResource resource = new ClassPathResource(storageKey); + if (!resource.exists()) { + throw new IOException("应收账单导出模板不存在: " + storageKey); + } + return resource.getInputStream(); + } + if ("FILE".equalsIgnoreCase(storageType)) { + if (!FileUtils.checkAllowDownload(storageKey)) { + throw new IOException("应收账单模板路径非法"); + } + Path profileRoot = new File(BmsConfig.getProfile()).toPath().toAbsolutePath().normalize(); + Path templatePath = profileRoot.resolve(storageKey).normalize(); + if (!templatePath.startsWith(profileRoot) || !Files.exists(templatePath)) { + throw new IOException("应收账单导出模板不存在: " + storageKey); + } + return Files.newInputStream(templatePath); + } + throw new IOException("不支持的应收账单模板存储类型: " + storageType); + } + + /** 按 Excel 行号提取模板原有行,供不同排版复用样式。 */ + protected Map extractTemplateRows(String sheetData) { + Map rows = new HashMap<>(); + Matcher matcher = TEMPLATE_ROW_PATTERN.matcher(sheetData); + while (matcher.find()) { + rows.put(Integer.valueOf(matcher.group(1)), matcher.group()); + } + return rows; + } + + protected String exportBillingFailDescription(Integer billingFailStatus) { + BillBillingFailStatus status = BillBillingFailStatus.of(billingFailStatus); + if (status == null) { + return ""; + } + return switch (status) { + case SUCCESS -> ""; + case NOT_BILLED -> "未计费"; + case PRODUCT -> "销售价未匹配产品"; + case COUNTRY -> "销售价未匹配国家"; + case WEIGHT -> "销售价未匹配重量段"; + case CATALOG_PRODUCT -> "产品价未匹配产品"; + case CATALOG_COUNTRY -> "产品价未匹配国家"; + case CATALOG_WEIGHT -> "产品价未匹配重量段"; + case NO_CUSTOMER_PACKAGE -> "未绑定套餐"; + case NO_ACTIVE_PACKAGE_VERSION -> "套餐未启用/无生效版本"; + case ALREADY_IN_AR_BILL -> "已生成应收账单"; + case PRODUCT_ARCHIVE_MISSING -> "产品档案缺失"; + case PRICE_NOT_HIT -> "未命中价格"; + case ZONE_PRICE_NOT_HIT -> "分区无价格"; + case POSTCODE_REQUIRED -> "邮编必填"; + case POSTCODE_ZONE_NOT_FOUND -> "邮编未匹配分区"; + case ORACLE_ORDER_NOT_FOUND -> "上游订单不存在"; + case ORACLE_ORDERNO_EMPTY -> "上游订单号为空"; + case ORACLE_CUSTOMER_EMPTY -> "上游客户为空"; + case ORACLE_PRODUCT_EMPTY -> "上游产品为空"; + case ORACLE_WEIGHT_INVALID -> "上游重量无效"; + case BILL_TIME_EMPTY -> "计费时间为空"; + case REFUND_ORDER_UNRESOLVED -> "退费订单无法解析"; + case CUSTOMER_CODE_REQUIRED -> "客户代码为空"; + case CUSTOMER_DISABLED -> "客户已停用"; + case FREIGHT_MISSING -> "运费为空"; + case UNKNOWN -> "未知失败"; + }; + } + + protected void appendOoxmlCell(StringBuilder row, String reference, Object value, int styleIndex) { + row.append("").append(numberText((Number) value)).append(""); + } else { + String text = value == null ? "" : String.valueOf(value); + row.append(" t=\"inlineStr\">").append(xmlEscape(text)).append(""); + } + } + + protected String replaceCellXml(String rowXml, String reference, Object value, boolean numeric) throws IOException { + return replaceCellXml(rowXml, reference, value, numeric, null); + } + + protected String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, int styleIndex) + throws IOException { + return replaceCellXml(rowXml, reference, value, numeric, null, styleIndex); + } + + protected String replaceFormulaCellXml(String rowXml, String reference, String formula, Number cachedValue) + throws IOException { + return replaceCellXml(rowXml, reference, cachedValue, true, formula); + } + + protected String replaceFormulaCellXml(String rowXml, String reference, String formula, Number cachedValue, + Integer styleIndex) throws IOException { + return replaceCellXml(rowXml, reference, cachedValue, true, formula, styleIndex); + } + + protected String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, String formula) + throws IOException { + return replaceCellXml(rowXml, reference, value, numeric, formula, null); + } + + protected String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, String formula, + Integer styleIndex) throws IOException { + if (rowXml == null) { + throw new IOException("应收账单模板缺少行: " + reference); + } + Matcher matcher = CELL_PATTERN.matcher(rowXml); + StringBuffer result = new StringBuffer(); + boolean found = false; + while (matcher.find()) { + String attributes = matcher.group(1); + Matcher referenceMatcher = CELL_REF_PATTERN.matcher(attributes); + if (!referenceMatcher.find() || !reference.equalsIgnoreCase(referenceMatcher.group(1))) { + matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); + continue; + } + found = true; + String normalizedAttributes = attributes.replaceAll("(?i)\\s+t\\s*=\\s*[\\\"'][^\\\"']*[\\\"']", "") + .replaceAll("\\s*/\\s*$", ""); + if (styleIndex != null) { + normalizedAttributes = replaceCellStyle(normalizedAttributes, styleIndex); + } + StringBuilder cell = new StringBuilder(""); + if (numeric) { + if (formula != null) { + cell.append("").append(xmlEscape(formula)).append(""); + } + cell.append("").append(value == null ? "" : numberText((Number) value)).append(""); + } else { + String text = value == null ? "" : String.valueOf(value); + cell.append("").append(xmlEscape(text)).append(""); + } + cell.append(""); + matcher.appendReplacement(result, Matcher.quoteReplacement(cell.toString())); + } + matcher.appendTail(result); + if (!found) { + return insertMissingCellXml(rowXml, reference, value, numeric, formula, styleIndex); + } + return result.toString(); + } + + protected String replaceCellStyle(String attributes, int styleIndex) { + Matcher matcher = CELL_STYLE_PATTERN.matcher(attributes); + if (!matcher.find()) { + return attributes + " s=\"" + styleIndex + "\""; + } + return matcher.replaceFirst(Matcher.quoteReplacement("s=\"" + styleIndex + "\"")); + } + + /** + * 兼容不同 Excel/WPS 版本保存后被省略的空单元格,按列顺序补回动态单元格。 + * 样式由调用方或具体模板的 fallbackCellStyle 提供。 + */ + + protected String insertMissingCellXml(String rowXml, String reference, Object value, boolean numeric, String formula, + Integer styleIndex) throws IOException { + int rowEnd = rowXml.lastIndexOf(""); + if (rowEnd < 0) { + throw new IOException("应收账单模板缺少行结束节点: " + reference); + } + int targetColumn = columnNumber(reference); + int insertAt = rowEnd; + Matcher matcher = CELL_PATTERN.matcher(rowXml); + while (matcher.find()) { + Matcher referenceMatcher = CELL_REF_PATTERN.matcher(matcher.group(1)); + if (referenceMatcher.find() && columnNumber(referenceMatcher.group(1)) > targetColumn) { + insertAt = matcher.start(); + break; + } + } + + String style = styleIndex == null ? fallbackCellStyle(reference) : String.valueOf(styleIndex); + StringBuilder cell = new StringBuilder(""); + if (formula != null) { + cell.append("").append(xmlEscape(formula)).append(""); + } + cell.append("").append(value == null ? "" : numberText((Number) value)).append(""); + } else { + String text = value == null ? "" : String.valueOf(value); + cell.append(" t=\"inlineStr\">").append(xmlEscape(text)).append(""); + } + return rowXml.substring(0, insertAt) + cell + rowXml.substring(insertAt); + } + + protected int columnNumber(String reference) { + int result = 0; + for (int index = 0; index < reference.length() && Character.isLetter(reference.charAt(index)); index++) { + result = result * 26 + Character.toUpperCase(reference.charAt(index)) - 'A' + 1; + } + return result; + } + + protected String shiftRowXml(String rowXml, int targetRowNumber) throws IOException { + if (rowXml == null) { + throw new IOException("应收账单模板缺少合计区域行"); + } + Matcher rowMatcher = ROW_REF_PATTERN.matcher(rowXml); + if (!rowMatcher.find()) { + throw new IOException("应收账单模板行缺少行号"); + } + StringBuffer shifted = new StringBuffer(); + rowMatcher.appendReplacement(shifted, Matcher.quoteReplacement(rowMatcher.group(1) + targetRowNumber + rowMatcher.group(2))); + rowMatcher.appendTail(shifted); + + Matcher cellMatcher = CELL_ROW_REF_PATTERN.matcher(shifted.toString()); + StringBuffer result = new StringBuffer(); + while (cellMatcher.find()) { + cellMatcher.appendReplacement(result, Matcher.quoteReplacement( + cellMatcher.group(1) + cellMatcher.group(2) + targetRowNumber + cellMatcher.group(3))); + } + cellMatcher.appendTail(result); + return result.toString(); + } + + protected String removeSheetDimension(String xml) { + Matcher matcher = DIMENSION_PATTERN.matcher(xml); + StringBuffer result = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(result, ""); + } + matcher.appendTail(result); + return result.toString(); + } + + protected String readUtf8(InputStream input) throws IOException { + StringBuilder result = new StringBuilder(16384); + char[] buffer = new char[8192]; + java.io.Reader reader = new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8); + for (int size; (size = reader.read(buffer)) != -1; ) { + result.append(buffer, 0, size); + } + return result.toString(); + } + + protected void writeUtf8(OutputStream output, String value) throws IOException { + output.write(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + protected String numberText(Number value) { + return value instanceof BigDecimal ? ((BigDecimal) value).toPlainString() : value.toString(); + } + + protected String xmlEscape(String value) { + return value.replace("&", "&").replace("<", "<").replace(">", ">") + .replace("\"", """).replace("'", "'"); + } + + /** + * 只为当前内存中的一批明细查询费用,避免一次加载整张账单的费用数据。 + */ + + protected void attachFees(List details) { + List detailIds = new ArrayList<>(); + Map> feesByDetailId = new HashMap<>(); + for (ArBillDetail detail : details) { + detailIds.add(detail.getDetailId()); + feesByDetailId.put(detail.getDetailId(), new ArrayList<>()); + } + for (ArBillDetailFee fee : detailFeeMapper.selectByDetailIds(detailIds)) { + List fees = feesByDetailId.get(fee.getDetailId()); + if (fees != null) { + fees.add(fee); + } + } + for (ArBillDetail detail : details) { + detail.setFees(feesByDetailId.get(detail.getDetailId())); + } + } + + protected String exportRemark(ArBillDetail detail) { + return StringUtils.isEmpty(detail.getRemark()) ? detail.getGoodsDescription() : detail.getRemark(); + } + + protected BigDecimal exportUnitPrice(ArBillDetail detail) { + return detail == null ? null : detail.getFreightRate(); + } + + protected BigDecimal exportProcessingFee(ArBillDetail detail) { + return detail == null ? null : detail.getRegistrationFee(); + } + + protected String exportBankAccountNo(String value) { + if (StringUtils.isEmpty(value)) { + return ""; + } + String normalized = value.replaceAll("\\s+", ""); + StringBuilder result = new StringBuilder(normalized.length() + normalized.length() / 4); + for (int index = 0; index < normalized.length(); index++) { + if (index > 0 && index % 4 == 0) { + result.append(' '); + } + result.append(normalized.charAt(index)); + } + return result.toString(); + } + + protected String fallbackCellStyle(String reference) { return null; } + + protected BigDecimal nvl(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriter.java b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriter.java new file mode 100644 index 00000000..a166743f --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriter.java @@ -0,0 +1,11 @@ +package com.bms.receivable.export; + +import java.io.IOException; +import java.nio.file.Path; +import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.ArExportTemplate; + +/** 每个写入器只负责一种账单模板的工作表布局。 */ +public interface ArBillWorkbookWriter { + void write(ArBill bill, ArExportTemplate template, Path target) throws IOException; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriters.java b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriters.java new file mode 100644 index 00000000..091ed6c4 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/export/ArBillWorkbookWriters.java @@ -0,0 +1,25 @@ +package com.bms.receivable.export; + +import com.bms.receivable.domain.ArExportTemplate; +import org.springframework.stereotype.Component; + +/** 按持久化的模板编码选择排版,恢复异步任务时使用同一规则。 */ +@Component +public class ArBillWorkbookWriters { + public static final String SUMMARY_TEMPLATE_CODE = "AR_BILL_SUMMARY"; + private final DefaultArBillWorkbookWriter defaultWriter; + private final SummaryArBillWorkbookWriter summaryWriter; + + public ArBillWorkbookWriters(DefaultArBillWorkbookWriter defaultWriter, SummaryArBillWorkbookWriter summaryWriter) { + this.defaultWriter = defaultWriter; + this.summaryWriter = summaryWriter; + } + + public ArBillWorkbookWriter select(ArExportTemplate template) { + return SUMMARY_TEMPLATE_CODE.equals(template.getTemplateCode()) ? summaryWriter : defaultWriter; + } + + public boolean isSummary(ArExportTemplate template) { + return SUMMARY_TEMPLATE_CODE.equals(template.getTemplateCode()); + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/export/DefaultArBillWorkbookWriter.java b/bms-back/bms-system/src/main/java/com/bms/receivable/export/DefaultArBillWorkbookWriter.java new file mode 100644 index 00000000..b0d3f916 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/export/DefaultArBillWorkbookWriter.java @@ -0,0 +1,596 @@ +package com.bms.receivable.export; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +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; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +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.xssf.model.StylesTable; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.springframework.stereotype.Component; +import com.bms.common.utils.StringUtils; +import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.ArBillDetail; +import com.bms.receivable.domain.ArBillDetailFee; +import com.bms.receivable.domain.ArExportTemplate; + +/** 默认应收账单模板的 21 列明细及银行页脚排版。 */ +@Component +public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { + private static final int TEMPLATE_DATA_START_ROW = 5; + private static final int TEMPLATE_LAST_DETAIL_ROW = 5; + private static final int EXPORT_FOOTER_GAP_ROWS = 1; + private static final int TEMPLATE_DRAWING_INSERT_ROW_INDEX = 5; + private static final int TEMPLATE_COLUMN_COUNT = 21; + private static final double EXPORT_DETAIL_ROW_HEIGHT = 20.0; + private static final int CUSTOMER_ORDER_NO_COLUMN_INDEX = 3; + private static final int TRACKING_NO_COLUMN_INDEX = 4; + private static final int FORMULA_COLUMN_INDEX = 16; + private static final int FEE_TYPE_COLUMN_INDEX = 17; + private static final Set GENERAL_NUMERIC_EXPORT_COLUMNS = Set.of(8, 9, 10, 11, 12, 13, 14, 15, 19); + private static final double MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH = 16.0; + private static final double MIN_TRACKING_NO_COLUMN_WIDTH = MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH; + private static final double MIN_FORMULA_COLUMN_WIDTH = 17.0; + private static final double MIN_FEE_TYPE_COLUMN_WIDTH = 10.0; + private static final int TEMPLATE_DETAIL_STYLE_INDEX = 31; + private static final String TEMPLATE_SHEET_XML = "xl/worksheets/sheet1.xml"; + private static final String TEMPLATE_SHEET_RELATIONSHIPS_XML = "xl/worksheets/_rels/sheet1.xml.rels"; + private static final String TEMPLATE_STYLES_XML = "xl/styles.xml"; + private static final String SPREADSHEET_DRAWING_NAMESPACE = + "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"; + private static final Pattern DRAWING_RELATIONSHIP_PATTERN = Pattern.compile( + "]*\\bType\\s*=\\s*[\\\"'][^\\\"']*/drawing[\\\"'])(?=[^>]*\\bTarget\\s*=\\s*[\\\"']([^\\\"']+)[\\\"'])[^>]*/?>", + Pattern.DOTALL); + private static final Pattern DRAWING_NAMESPACE_PREFIX_PATTERN = Pattern.compile( + "xmlns:([A-Za-z_][\\w.-]*)\\s*=\\s*[\\\"']" + + Pattern.quote(SPREADSHEET_DRAWING_NAMESPACE) + "[\\\"']"); + private static final Pattern TEMPLATE_COLUMN_PATTERN = Pattern.compile("]*)/\\s*>", Pattern.DOTALL); + private static final Pattern TEMPLATE_COLUMN_MIN_PATTERN = Pattern.compile("\\bmin\\s*=\\s*[\"'](\\d+)[\"']"); + private static final Pattern TEMPLATE_COLUMN_MAX_PATTERN = Pattern.compile("\\bmax\\s*=\\s*[\"'](\\d+)[\"']"); + private static final Pattern TEMPLATE_COLUMN_WIDTH_PATTERN = Pattern.compile("\\bwidth\\s*=\\s*[\"']([\\d.]+)[\"']"); + private static final Pattern MERGE_REF_PATTERN = Pattern.compile( + "(]*\\bref=\")([A-Z]+)(\\d+)(?::([A-Z]+)(\\d+))?(\")"); + + private record ExportStyleIndexes(int failedDetail, int detailNo, int failedDetailNo, + int customerOrderNo, int failedCustomerOrderNo, + int trackingNo, int failedTrackingNo, + int generalNumber, int failedGeneralNumber, + int formula, int failedFormula) { + } + + @Override + public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException { + // 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。 + StylesTable styles = readExportStyles(template); + String drawingPartPath = readTemplateDrawingPartPath(template); + XSSFCellStyle detailNoStyle = styles.createCellStyle(); + detailNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + detailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); + int detailNoStyleIndex = Short.toUnsignedInt(detailNoStyle.getIndex()); + XSSFCellStyle failedDetailStyle = styles.createCellStyle(); + failedDetailStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + failedDetailStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + failedDetailStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + int failedDetailStyleIndex = Short.toUnsignedInt(failedDetailStyle.getIndex()); + XSSFCellStyle customerOrderNoStyle = styles.createCellStyle(); + customerOrderNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + customerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); + int customerOrderNoStyleIndex = Short.toUnsignedInt(customerOrderNoStyle.getIndex()); + XSSFCellStyle failedCustomerOrderNoStyle = styles.createCellStyle(); + failedCustomerOrderNoStyle.cloneStyleFrom(failedDetailStyle); + failedCustomerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); + int failedCustomerOrderNoStyleIndex = Short.toUnsignedInt(failedCustomerOrderNoStyle.getIndex()); + XSSFCellStyle trackingNoStyle = styles.createCellStyle(); + trackingNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + trackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); + int trackingNoStyleIndex = Short.toUnsignedInt(trackingNoStyle.getIndex()); + XSSFCellStyle failedTrackingNoStyle = styles.createCellStyle(); + failedTrackingNoStyle.cloneStyleFrom(failedDetailStyle); + failedTrackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); + int failedTrackingNoStyleIndex = Short.toUnsignedInt(failedTrackingNoStyle.getIndex()); + XSSFCellStyle generalNumberStyle = styles.createCellStyle(); + generalNumberStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + generalNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); + int generalNumberStyleIndex = Short.toUnsignedInt(generalNumberStyle.getIndex()); + XSSFCellStyle failedGeneralNumberStyle = styles.createCellStyle(); + failedGeneralNumberStyle.cloneStyleFrom(failedDetailStyle); + failedGeneralNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); + int failedGeneralNumberStyleIndex = Short.toUnsignedInt(failedGeneralNumberStyle.getIndex()); + XSSFCellStyle failedDetailNoStyle = styles.createCellStyle(); + failedDetailNoStyle.cloneStyleFrom(failedDetailStyle); + failedDetailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); + int failedDetailNoStyleIndex = Short.toUnsignedInt(failedDetailNoStyle.getIndex()); + XSSFCellStyle formulaStyle = styles.createCellStyle(); + formulaStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + formulaStyle.setShrinkToFit(true); + int formulaStyleIndex = Short.toUnsignedInt(formulaStyle.getIndex()); + XSSFCellStyle failedFormulaStyle = styles.createCellStyle(); + failedFormulaStyle.cloneStyleFrom(failedDetailStyle); + failedFormulaStyle.setShrinkToFit(true); + int failedFormulaStyleIndex = Short.toUnsignedInt(failedFormulaStyle.getIndex()); + ExportStyleIndexes exportStyleIndexes = new ExportStyleIndexes( + failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex, + customerOrderNoStyleIndex, failedCustomerOrderNoStyleIndex, + trackingNoStyleIndex, failedTrackingNoStyleIndex, + generalNumberStyleIndex, failedGeneralNumberStyleIndex, + formulaStyleIndex, failedFormulaStyleIndex); + try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input); + OutputStream fileOutput = Files.newOutputStream(target); ZipOutputStream output = new ZipOutputStream(fileOutput)) { + boolean replaced = false; + Integer drawingRowOffset = null; + String pendingDrawingXml = null; + for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { + String entryName = entry.getName(); + if (!StringUtils.isEmpty(drawingPartPath) && drawingPartPath.equals(entryName)) { + String drawingXml = readUtf8(templateZip); + if (drawingRowOffset == null) { + // ZIP 包内绘图可能先于工作表出现,先缓存小型绘图 XML,待明细行数确定后再写入。 + pendingDrawingXml = drawingXml; + } else { + writeDrawingEntry(output, entryName, drawingXml, drawingRowOffset.intValue()); + } + templateZip.closeEntry(); + continue; + } + if (TEMPLATE_SHEET_XML.equals(entry.getName())) { + output.putNextEntry(new ZipEntry(entryName)); + int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes); + output.closeEntry(); + replaced = true; + drawingRowOffset = Integer.valueOf(rowOffset); + if (pendingDrawingXml != null) { + writeDrawingEntry(output, drawingPartPath, pendingDrawingXml, rowOffset); + pendingDrawingXml = null; + } + templateZip.closeEntry(); + continue; + } + + output.putNextEntry(new ZipEntry(entryName)); + if (TEMPLATE_STYLES_XML.equals(entryName)) { + styles.writeTo(output); + } else if (!entry.isDirectory()) { + templateZip.transferTo(output); + } + output.closeEntry(); + templateZip.closeEntry(); + } + if (!replaced) { + throw new IOException("应收账单导出模板工作表不存在: " + TEMPLATE_SHEET_XML); + } + } + } + + private String readTemplateDrawingPartPath(ArExportTemplate template) throws IOException { + try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { + for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { + if (TEMPLATE_SHEET_RELATIONSHIPS_XML.equals(entry.getName())) { + String relationshipsXml = readUtf8(templateZip); + Matcher matcher = DRAWING_RELATIONSHIP_PATTERN.matcher(relationshipsXml); + if (matcher.find()) { + String target = matcher.group(1); + if (target.startsWith("/")) { + return target.substring(1); + } + Path sheetDirectory = Paths.get(TEMPLATE_SHEET_XML).getParent(); + return sheetDirectory.resolve(target).normalize().toString().replace('\\', '/'); + } + return null; + } + templateZip.closeEntry(); + } + } + return null; + } + + private void writeDrawingEntry(ZipOutputStream output, String entryName, String drawingXml, + int rowOffset) throws IOException { + output.putNextEntry(new ZipEntry(entryName)); + writeUtf8(output, shiftDrawingAnchorRows(drawingXml, rowOffset)); + output.closeEntry(); + } + + /** + * 根据明细新增行及页脚前空行,同步下移图片锚点,保持二维码与页脚的相对位置。 + */ + + private String shiftDrawingAnchorRows(String drawingXml, int rowOffset) { + if (rowOffset <= 0) { + return drawingXml; + } + Matcher namespaceMatcher = DRAWING_NAMESPACE_PREFIX_PATTERN.matcher(drawingXml); + String rowTag = namespaceMatcher.find() + ? Pattern.quote(namespaceMatcher.group(1)) + ":row" + : "row"; + Pattern rowPattern = Pattern.compile("(<" + rowTag + "\\s*>\\s*)(\\d+)(\\s*)"); + Matcher rowMatcher = rowPattern.matcher(drawingXml); + StringBuffer shifted = new StringBuffer(); + while (rowMatcher.find()) { + int rowIndex = Integer.parseInt(rowMatcher.group(2)); + int targetRowIndex = rowIndex >= TEMPLATE_DRAWING_INSERT_ROW_INDEX ? rowIndex + rowOffset : rowIndex; + rowMatcher.appendReplacement(shifted, Matcher.quoteReplacement( + rowMatcher.group(1) + targetRowIndex + rowMatcher.group(3))); + } + rowMatcher.appendTail(shifted); + return shifted.toString(); + } + + private StylesTable readExportStyles(ArExportTemplate template) throws IOException { + try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { + for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { + if (TEMPLATE_STYLES_XML.equals(entry.getName())) { + StylesTable styles = new StylesTable(templateZip); + if (styles.getNumCellStyles() <= TEMPLATE_DETAIL_STYLE_INDEX) { + throw new IOException("应收账单导出模板缺少明细样式: " + TEMPLATE_DETAIL_STYLE_INDEX); + } + return styles; + } + templateZip.closeEntry(); + } + } + throw new IOException("应收账单导出模板缺少样式表: " + TEMPLATE_STYLES_XML); + } + + private int writeOoxmlSheet(String templateXml, ArBill bill, OutputStream output, + ExportStyleIndexes styleIndexes) throws IOException { + int sheetDataStart = templateXml.indexOf("', sheetDataStart); + int sheetDataEnd = templateXml.indexOf("", sheetDataOpenEnd); + if (sheetDataStart < 0 || sheetDataOpenEnd < 0 || sheetDataEnd < 0) { + throw new IOException("应收账单导出模板缺少 sheetData 节点"); + } + + Map templateRows = extractTemplateRows(templateXml.substring(sheetDataOpenEnd + 1, sheetDataEnd)); + Map receiveTimeRange = detailMapper.selectReceiveTimeRangeByBillId(bill.getArBillId()); + String prefix = adjustExportColumnWidths( + removeSheetDimension(templateXml.substring(0, sheetDataOpenEnd + 1))); + writeUtf8(output, prefix); + + String headerRow = replaceCellXml(templateRows.get(1), "A1", + StringUtils.isEmpty(bill.getBankAccountName()) ? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName(), false); + writeUtf8(output, headerRow); + writeUtf8(output, templateRows.get(2)); + String customerRow = replaceCellXml(templateRows.get(3), "C3", bill.getCustomerName(), false); + // 账单所属期区域为 O3:U3 合并单元格,必须写入左上角 O3 才能显示。 + customerRow = replaceCellXml(customerRow, "O3", exportReceiveTimeRange(receiveTimeRange), false); + writeUtf8(output, customerRow); + writeUtf8(output, templateRows.get(4)); + + int rowIndex = TEMPLATE_DATA_START_ROW; + int lastDetailNo = 0; + while (true) { + List details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE); + if (details.isEmpty()) { + break; + } + attachFees(details); + for (ArBillDetail detail : details) { + writeOoxmlDetailRow(output, rowIndex++, detail, styleIndexes); + } + lastDetailNo = details.get(details.size() - 1).getDetailNo(); + } + + int lastDetailRow = Math.max(rowIndex - 1, TEMPLATE_LAST_DETAIL_ROW); + int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW + EXPORT_FOOTER_GAP_ROWS; + writeUtf8(output, ""); + writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber()); + String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset); + writeUtf8(output, suffix); + return rowOffset; + } + + /** + * 仅加宽客户订单号、运单号、计算公式和费用类型列;不缩小模板原有列宽。 + */ + + private String adjustExportColumnWidths(String sheetPrefix) throws IOException { + Matcher columnMatcher = TEMPLATE_COLUMN_PATTERN.matcher(sheetPrefix); + StringBuffer result = new StringBuffer(); + int[] targetColumns = { + CUSTOMER_ORDER_NO_COLUMN_INDEX, + TRACKING_NO_COLUMN_INDEX, + FORMULA_COLUMN_INDEX, + FEE_TYPE_COLUMN_INDEX + }; + double[] minimumWidths = { + MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH, + MIN_TRACKING_NO_COLUMN_WIDTH, + MIN_FORMULA_COLUMN_WIDTH, + MIN_FEE_TYPE_COLUMN_WIDTH + }; + boolean[] targetColumnsFound = new boolean[targetColumns.length]; + + while (columnMatcher.find()) { + String attributes = columnMatcher.group(1); + Matcher minMatcher = TEMPLATE_COLUMN_MIN_PATTERN.matcher(attributes); + Matcher maxMatcher = TEMPLATE_COLUMN_MAX_PATTERN.matcher(attributes); + Matcher widthMatcher = TEMPLATE_COLUMN_WIDTH_PATTERN.matcher(attributes); + if (!minMatcher.find() || !maxMatcher.find() || !widthMatcher.find()) { + columnMatcher.appendReplacement(result, Matcher.quoteReplacement(columnMatcher.group())); + continue; + } + + int min = Integer.parseInt(minMatcher.group(1)); + int max = Integer.parseInt(maxMatcher.group(1)); + double currentWidth = Double.parseDouble(widthMatcher.group(1)); + boolean needsExpansion = false; + for (int index = 0; index < targetColumns.length; index++) { + if (min <= targetColumns[index] && max >= targetColumns[index]) { + targetColumnsFound[index] = true; + needsExpansion |= currentWidth < minimumWidths[index]; + } + } + if (!needsExpansion) { + columnMatcher.appendReplacement(result, Matcher.quoteReplacement(columnMatcher.group())); + continue; + } + + StringBuilder replacement = new StringBuilder(); + int segmentStart = min; + for (int index = 0; index < targetColumns.length; index++) { + int column = targetColumns[index]; + if (column < min || column > max || currentWidth >= minimumWidths[index]) { + continue; + } + if (segmentStart < column) { + appendColumnSegment(replacement, attributes, segmentStart, column - 1, currentWidth, false); + } + appendColumnSegment(replacement, attributes, column, column, minimumWidths[index], true); + segmentStart = column + 1; + } + if (segmentStart <= max) { + appendColumnSegment(replacement, attributes, segmentStart, max, currentWidth, false); + } + columnMatcher.appendReplacement(result, Matcher.quoteReplacement(replacement.toString())); + } + columnMatcher.appendTail(result); + + for (boolean found : targetColumnsFound) { + if (!found) { + throw new IOException("应收账单导出模板缺少客户订单号、运单号、计算公式或费用类型列宽定义"); + } + } + return result.toString(); + } + + private void appendColumnSegment(StringBuilder xml, String attributes, int min, int max, double width, + boolean customWidth) { + String segmentAttributes = replaceColumnAttribute(attributes, "min", String.valueOf(min)); + segmentAttributes = replaceColumnAttribute(segmentAttributes, "max", String.valueOf(max)); + segmentAttributes = replaceColumnAttribute(segmentAttributes, "width", String.valueOf(width)); + if (customWidth) { + segmentAttributes = replaceColumnAttribute(segmentAttributes, "customWidth", "1"); + } + xml.append(""); + } + + private String replaceColumnAttribute(String attributes, String name, String value) { + Pattern attributePattern = Pattern.compile("(\\b" + name + "\\s*=\\s*[\"'])([^\"']*)([\"'])", + Pattern.CASE_INSENSITIVE); + Matcher matcher = attributePattern.matcher(attributes); + if (matcher.find()) { + String replacement = matcher.group(1) + value + matcher.group(3); + return matcher.replaceFirst(Matcher.quoteReplacement(replacement)); + } + return attributes + " " + name + "=\"" + value + "\""; + } + + private void writeOoxmlFooter(OutputStream output, Map templateRows, int rowOffset, + ArBill bill, int generalNumberStyleIndex) throws IOException { + String totalAmountFormula = "SUM(S" + TEMPLATE_DATA_START_ROW + ":INDEX(S:S,ROW()-1))"; + for (int offset = 0; offset < 4; offset++) { + int sourceRowNumber = TEMPLATE_LAST_DETAIL_ROW + offset + 1; + int targetRowNumber = sourceRowNumber + rowOffset; + String row = shiftRowXml(templateRows.get(sourceRowNumber), targetRowNumber); + if (offset == 0) { + row = replaceCellXml(row, "B" + targetRowNumber, "银行信息", false); + row = replaceCellXml(row, "P" + targetRowNumber, "本期应收金额", false); + row = replaceFormulaCellXml(row, "S" + targetRowNumber, totalAmountFormula, + nvl(bill.getTotalAmount()), generalNumberStyleIndex); + } else if (offset == 1) { + row = replaceCellXml(row, "B" + targetRowNumber, "开户名", false); + row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankAccountName(), false); + row = replaceCellXml(row, "P" + targetRowNumber, "本期已核销金额", false); + row = replaceCellXml(row, "S" + targetRowNumber, bill.getWrittenOffAmount(), true, + generalNumberStyleIndex); + } else if (offset == 2) { + row = replaceCellXml(row, "B" + targetRowNumber, "账号", false); + row = replaceCellXml(row, "C" + targetRowNumber, exportBankAccountNo(bill.getBankAccountNo()), false); + row = replaceCellXml(row, "P" + targetRowNumber, "本期未核销金额", false); + String unwrittenAmountFormula = "S" + (targetRowNumber - 2) + "-S" + (targetRowNumber - 1); + row = replaceFormulaCellXml(row, "S" + targetRowNumber, unwrittenAmountFormula, + nvl(bill.getUnwrittenAmount()), generalNumberStyleIndex); + } else { + row = replaceCellXml(row, "B" + targetRowNumber, "开户行", false); + row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankName(), false); + } + writeUtf8(output, row); + } + } + + private void writeOoxmlDetailRow(OutputStream output, int rowNumber, ArBillDetail detail, + ExportStyleIndexes styleIndexes) throws IOException { + String failureDescription = exportBillingFailDescription(detail.getBillingFailStatus()); + boolean failedDetail = !failureDescription.isEmpty(); + int styleIndex = failedDetail ? styleIndexes.failedDetail() : TEMPLATE_DETAIL_STYLE_INDEX; + int sequenceStyleIndex = failedDetail ? styleIndexes.failedDetailNo() : styleIndexes.detailNo(); + Object[] values = { + detail.getDetailNo(), + detail.getReceiveTime() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(detail.getReceiveTime()), + detail.getOrderNo(), detail.getTrackingNo(), + StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(), + StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(), + detail.getDestPostcode(), detail.getReceiveWeight(), detail.getPkgLength(), + detail.getPkgHeight(), detail.getPkgWidth(), detail.getVolumeWeight(), + detail.getChargeWeight(), exportUnitPrice(detail), exportProcessingFee(detail), + exportFormula(detail), exportFeeType(), detail.getCurrency(), detail.getTotalAmount(), exportRemark(detail), + failureDescription + }; + StringBuilder row = new StringBuilder(2048); + row.append(""); + for (int index = 0; index < TEMPLATE_COLUMN_COUNT; index++) { + int excelColumnIndex = index + 1; + int cellStyleIndex = styleIndex; + if (index == 0) { + cellStyleIndex = sequenceStyleIndex; + } else if (excelColumnIndex == CUSTOMER_ORDER_NO_COLUMN_INDEX) { + cellStyleIndex = failedDetail ? styleIndexes.failedCustomerOrderNo() : styleIndexes.customerOrderNo(); + } else if (excelColumnIndex == TRACKING_NO_COLUMN_INDEX) { + cellStyleIndex = failedDetail ? styleIndexes.failedTrackingNo() : styleIndexes.trackingNo(); + } else if (excelColumnIndex == FORMULA_COLUMN_INDEX) { + cellStyleIndex = failedDetail ? styleIndexes.failedFormula() : styleIndexes.formula(); + } else if (GENERAL_NUMERIC_EXPORT_COLUMNS.contains(excelColumnIndex)) { + cellStyleIndex = failedDetail ? styleIndexes.failedGeneralNumber() : styleIndexes.generalNumber(); + } + appendOoxmlCell(row, (char) ('A' + index) + String.valueOf(rowNumber), values[index], cellStyleIndex); + } + row.append(""); + writeUtf8(output, row.toString()); + } + + @Override + protected String fallbackCellStyle(String reference) { + if ("A1".equalsIgnoreCase(reference)) { + return "5"; + } + if ("C3".equalsIgnoreCase(reference)) { + return "11"; + } + if ("O3".equalsIgnoreCase(reference) || "P3".equalsIgnoreCase(reference)) { + return "15"; + } + return null; + } + + private String shiftFooterMerges(String xml, int rowOffset) { + Matcher matcher = MERGE_REF_PATTERN.matcher(xml); + StringBuffer result = new StringBuffer(); + int sourceFooterStart = TEMPLATE_LAST_DETAIL_ROW + 1; + int sourceFooterEnd = sourceFooterStart + 3; + while (matcher.find()) { + int firstRow = Integer.parseInt(matcher.group(3)); + String lastColumn = matcher.group(4); + String lastRowText = matcher.group(5); + int lastRow = lastRowText == null ? firstRow : Integer.parseInt(lastRowText); + if (firstRow >= sourceFooterStart && lastRow <= sourceFooterEnd) { + String replacement = matcher.group(1) + matcher.group(2) + (firstRow + rowOffset) + + (lastColumn == null ? "" : ":" + lastColumn + (lastRow + rowOffset)) + matcher.group(6); + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); + } else { + matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); + } + } + matcher.appendTail(result); + return result.toString(); + } + + private String exportReceiveTimeRange(Map 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)) { + return formula; + } + boolean freight = feeAmount(detail, "BASIC_FREIGHT") != null; + boolean processing = exportProcessingFee(detail) != null; + boolean surcharge = hasFeeType(detail.getFees(), "SURCHARGE"); + if (!freight) { + return ""; + } + return "结算重量*公斤价" + (processing ? "+处理费" : "") + (surcharge ? "+附加费" : ""); + } + + private String exportFeeType() { + return "运费"; + } + + private String joinFeeText(List fees, boolean formula) { + if (fees == null || fees.isEmpty()) { + return ""; + } + StringBuilder result = new StringBuilder(); + for (ArBillDetailFee fee : fees) { + String value = formula ? fee.getCalculationFormula() : (StringUtils.isEmpty(fee.getFeeName()) ? fee.getFeeType() : fee.getFeeName()); + if (StringUtils.isEmpty(value)) { + continue; + } + if (result.length() > 0) { + result.append("、"); + } + result.append(value); + } + return result.toString(); + } + + private BigDecimal feeAmount(ArBillDetail detail, String feeType) { + if (detail.getFees() == null) { + return null; + } + BigDecimal total = BigDecimal.ZERO; + boolean found = false; + for (ArBillDetailFee fee : detail.getFees()) { + if (feeType.equalsIgnoreCase(fee.getFeeType())) { + total = total.add(nvl(fee.getAmount())); + found = true; + } + } + return found ? total : null; + } + + private boolean hasFeeType(List fees, String feeType) { + if (fees == null) { + return false; + } + for (ArBillDetailFee fee : fees) { + if (feeType.equalsIgnoreCase(fee.getFeeType())) { + return true; + } + } + return false; + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/export/SummaryArBillWorkbookWriter.java b/bms-back/bms-system/src/main/java/com/bms/receivable/export/SummaryArBillWorkbookWriter.java new file mode 100644 index 00000000..32dfdc72 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/export/SummaryArBillWorkbookWriter.java @@ -0,0 +1,352 @@ +package com.bms.receivable.export; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +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; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +import com.bms.common.utils.StringUtils; +import com.bms.receivable.domain.ArBill; +import com.bms.receivable.domain.ArBillDetail; +import com.bms.receivable.domain.ArExportTemplate; +import org.apache.poi.ss.SpreadsheetVersion; +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFName; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Component; + +/** 小模板由 POI 读取样式;订单数据只写入临时 XML,内存只保留当前批次和产品汇总。 */ +@Component +public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { + private static final int DETAIL_START_ROW = 5; + private static final int DETAIL_COLUMN_COUNT = 20; + private static final int SUMMARY_START_ROW = 4; + private static final String SUMMARY_REMARK = "国际货物运输代理服务费"; + private static final Pattern MERGE = Pattern.compile("(]*\\bref=\")([A-Z]+)(\\d+):([A-Z]+)(\\d+)(\")"); + private static final Pattern FILTER = Pattern.compile("(]*\\bref=\")[^\"]*(\")"); + + @Override + public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException { + Path detailXml = Files.createTempFile("ar-bill-summary-details-", ".xml"); + try (InputStream input = openTemplateStream(template); XSSFWorkbook workbook = new XSSFWorkbook(input)) { + validateTemplate(workbook); + prepareTemplate(workbook, bill); + DetailStyles detailStyles = createDetailStyles(workbook); + byte[] skeleton = serialize(workbook); + String summaryPath = partPath(workbook.getSheetAt(0)); + String detailPath = partPath(workbook.getSheetAt(1)); + SheetXml summary = readSheet(skeleton, summaryPath); + SheetXml detail = readSheet(skeleton, detailPath); + Map groups = new LinkedHashMap<>(); + DetailResult result; + try (OutputStream output = Files.newOutputStream(detailXml)) { + result = writeDetails(detail, bill, output, groups, detailStyles); + } + if (result.amount().compareTo(nvl(bill.getTotalAmount())) != 0) { + throw new IOException("账单明细应收金额合计与账单总额不一致,请检查账单"); + } + if (bill.getOrderCount() != null && bill.getOrderCount() != result.count()) { + throw new IOException("账单明细数量与账单订单数不一致,请检查账单"); + } + if ((long) groups.size() + 12 > SpreadsheetVersion.EXCEL2007.getMaxRows()) { + throw new IOException("账单产品分组数超过 Excel 单个工作表容量,请拆分账单后导出"); + } + + int summaryOffset = Math.max(1, groups.size()) - 1; + // 模板中原有打印区域为 #REF!,重建为本次实际导出范围。 + for (XSSFName name : new ArrayList<>(workbook.getAllNames())) { + if (name.getNameName().contains("FilterDatabase") || name.getNameName().contains("Print_Area")) { + workbook.removeName(name); + } + } + workbook.setPrintArea(0, 0, 6, 0, 12 + summaryOffset); + workbook.setPrintArea(1, 0, DETAIL_COLUMN_COUNT - 1, 0, result.lastRow() + 1); + skeleton = serialize(workbook); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(skeleton)); + OutputStream file = Files.newOutputStream(target); ZipOutputStream output = new ZipOutputStream(file)) { + 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); + } else if (detailPath.equals(entry.getName())) { + Files.copy(detailXml, output); + } else { + zip.transferTo(output); + } + output.closeEntry(); + } + } + } finally { + Files.deleteIfExists(detailXml); + } + } + + private void validateTemplate(XSSFWorkbook workbook) throws IOException { + if (workbook.getNumberOfSheets() != 2 || !"账单汇总".equals(workbook.getSheetAt(0).getSheetName()) + || !"运费明细".equals(workbook.getSheetAt(1).getSheetName())) { + throw new IOException("汇总模板必须只包含账单汇总、运费明细两个工作表,并按此顺序排列"); + } + requireRow(workbook.getSheetAt(0), 3); + requireRow(workbook.getSheetAt(0), 5); + requireRow(workbook.getSheetAt(1), 4); + requireRow(workbook.getSheetAt(1), 5); + XSSFCell explanationHeader = requireRow(workbook.getSheetAt(1), 3).getCell(DETAIL_COLUMN_COUNT - 1); + if (explanationHeader == null || !"说明".equals(explanationHeader.toString().trim())) { + throw new IOException("汇总模板运费明细缺少 T 列说明,请使用最新模板"); + } + } + + private XSSFRow requireRow(XSSFSheet sheet, int index) throws IOException { + XSSFRow row = sheet.getRow(index); + if (row == null) throw new IOException("汇总模板缺少行:" + sheet.getSheetName() + "!" + (index + 1)); + return row; + } + + private void prepareTemplate(XSSFWorkbook workbook, ArBill bill) throws IOException { + String currency = StringUtils.isEmpty(bill.getCurrency()) ? "CNY" : bill.getCurrency(); + String company = StringUtils.isEmpty(bill.getBankAccountName()) + ? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName(); + XSSFSheet summary = workbook.getSheetAt(0); + XSSFSheet detail = workbook.getSheetAt(1); + summary.getRow(0).getCell(0).setCellValue(company); + detail.getRow(0).getCell(0).setCellValue(company); + textCell(summary, 5, 5, currency); + textCell(summary, 10, 1, bill.getBankAccountName()); + textCell(summary, 11, 1, exportBankAccountNo(bill.getBankAccountNo())); + textCell(summary, 12, 1, bill.getBankName()); + textCell(detail, 2, 1, bill.getCustomerName()); + textCell(detail, 2, 17, billPeriod(bill)); + for (int column : new int[]{11, 12, 13, 14, 15}) { + XSSFCell header = detail.getRow(3).getCell(column); + header.setCellValue(header.getStringCellValue().replace("CNY", currency)); + } + for (int column = 0; column < DETAIL_COLUMN_COUNT; column++) { + XSSFCell cell = detail.getRow(4).getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK); + XSSFCellStyle style = workbook.createCellStyle(); + style.cloneStyleFrom(cell.getCellStyle()); + boolean identifier = column == 0 || column == 2 || column == 3 || column == 6; + String format = identifier ? "@" : (column == 13 || column == 15 ? "0.00" : "General"); + style.setDataFormat(workbook.createDataFormat().getFormat(format)); + cell.setCellStyle(style); + } + XSSFRow summaryRow = requireRow(summary, 3); + for (int column = 0; column < 7; column++) { + XSSFCell cell = summaryRow.getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK); + XSSFCellStyle style = workbook.createCellStyle(); + style.cloneStyleFrom(cell.getCellStyle()); + style.setDataFormat(workbook.createDataFormat().getFormat(column == 4 ? "0.00" : "General")); + cell.setCellStyle(style); + } + detail.getRow(4).setHeightInPoints(20); + summaryRow.setHeightInPoints(20); + // 订单号按文本输出并提供可读列宽;其他版式沿用用户模板。 + detail.setColumnWidth(2, Math.max(detail.getColumnWidth(2), 20 * 256)); + detail.setColumnWidth(3, Math.max(detail.getColumnWidth(3), 20 * 256)); + workbook.setForceFormulaRecalculation(true); + } + + private void textCell(XSSFSheet sheet, int row, int column, String value) { + XSSFRow target = sheet.getRow(row); + if (target == null) target = sheet.createRow(row); + target.getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK) + .setCellValue(value == null ? "" : value); + } + + private DetailStyles createDetailStyles(XSSFWorkbook workbook) { + int[] normal = new int[DETAIL_COLUMN_COUNT]; + int[] failed = new int[DETAIL_COLUMN_COUNT]; + for (int column = 0; column < normal.length; column++) { + XSSFCellStyle original = workbook.getSheetAt(1).getRow(4).getCell(column).getCellStyle(); + normal[column] = Short.toUnsignedInt(original.getIndex()); + XSSFCellStyle style = workbook.createCellStyle(); + style.cloneStyleFrom(original); + style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + failed[column] = Short.toUnsignedInt(style.getIndex()); + } + return new DetailStyles(normal, failed); + } + + private DetailResult writeDetails(SheetXml sheet, ArBill bill, OutputStream output, + Map groups, DetailStyles styles) throws IOException { + writeUtf8(output, sheet.prefix()); + for (int row = 1; row <= 4; row++) writeUtf8(output, sheet.rows().get(row)); + int rowNumber = DETAIL_START_ROW; + int lastDetailNo = 0; + BigDecimal total = BigDecimal.ZERO; + while (true) { + List details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE); + if (details.isEmpty()) break; + for (ArBillDetail detail : details) { + if (rowNumber + 2 > SpreadsheetVersion.EXCEL2007.getMaxRows()) { + throw new IOException("账单订单数超过 Excel 单个工作表容量,请拆分账单后导出"); + } + if (!StringUtils.isEmpty(detail.getCurrency()) && !detail.getCurrency().equals(bill.getCurrency())) { + throw new IOException("账单明细币种与账单币种不一致,请检查账单"); + } + writeUtf8(output, detailRow(rowNumber++, bill, detail, styles)); + BigDecimal amount = nvl(detail.getTotalAmount()); + total = total.add(amount); + String key = StringUtils.isEmpty(detail.getProductCode()) + ? "NAME:" + detail.getProductName() : "CODE:" + detail.getProductCode(); + ProductSummary product = groups.computeIfAbsent(key, ignored -> new ProductSummary( + StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName())); + product.amount = product.amount.add(amount); + } + lastDetailNo = details.get(details.size() - 1).getDetailNo(); + } + int count = rowNumber - DETAIL_START_ROW; + int lastRow = Math.max(DETAIL_START_ROW, rowNumber - 1); + if (count == 0) writeUtf8(output, ""); + writeUtf8(output, ""); + String footer = shiftRowXml(sheet.rows().get(6), lastRow + 2); + footer = replaceFormulaCellXml(footer, "P" + (lastRow + 2), "SUM(P5:P" + lastRow + ")", total); + writeUtf8(output, footer); + writeUtf8(output, withFilter(sheet.suffix(), "A4:T" + lastRow)); + return new DetailResult(count, lastRow, total); + } + + private String detailRow(int rowNumber, ArBill bill, ArBillDetail detail, DetailStyles styles) { + String failure = exportBillingFailDescription(detail.getBillingFailStatus()); + Object[] values = { + bill.getCustomerCode(), + detail.getReceiveTime() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(detail.getReceiveTime()), + detail.getTransferNo(), detail.getTrackingNo(), + StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(), + StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(), + detail.getDestPostcode(), null, detail.getReceiveWeight(), detail.getChargeWeight(), null, + exportUnitPrice(detail), exportProcessingFee(detail), null, null, detail.getTotalAmount(), null, null, + exportRemark(detail), failure + }; + StringBuilder row = new StringBuilder(2048).append(""); + for (int index = 0; index < values.length; index++) { + String reference = (char) ('A' + index) + String.valueOf(rowNumber); + int style = failure.isEmpty() ? styles.normal()[index] : styles.failed()[index]; + if (index == 13) { + BigDecimal amount = nvl(detail.getChargeWeight()).multiply(nvl(exportUnitPrice(detail))) + .setScale(2, RoundingMode.HALF_UP); + row.append("ROUND(J").append(rowNumber).append("*L").append(rowNumber) + .append(",2)").append(numberText(amount)).append(""); + } else { + appendOoxmlCell(row, reference, values[index], style); + } + } + return row.append("").toString(); + } + + private void writeSummary(SheetXml sheet, ArBill bill, Map groups, + BigDecimal total, 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), + 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); + } + writeUtf8(output, row); + rowNumber++; + } + int lastRow = Math.max(SUMMARY_START_ROW, rowNumber - 1); + if (groups.isEmpty()) writeUtf8(output, ""); + writeUtf8(output, ""); + int offset = lastRow - SUMMARY_START_ROW; + for (Map.Entry entry : sheet.rows().entrySet()) { + if (entry.getKey() < 6) continue; + int targetRow = entry.getKey() + offset; + String row = shiftRowXml(entry.getValue(), targetRow); + if (entry.getKey() == 6) { + row = replaceFormulaCellXml(row, "E" + targetRow, + "SUMIF(F4:F" + lastRow + ",F" + targetRow + ",E4:E" + lastRow + ")", total); + } + writeUtf8(output, row); + } + writeUtf8(output, withFilter(shiftMerges(sheet.suffix(), offset), "A3:G" + lastRow)); + } + + private String shiftMerges(String suffix, int offset) { + Matcher matcher = MERGE.matcher(suffix); + StringBuffer result = new StringBuffer(); + while (matcher.find()) { + int first = Integer.parseInt(matcher.group(3)); + int last = Integer.parseInt(matcher.group(5)); + if (first >= 6) { + matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group(1) + matcher.group(2) + + (first + offset) + ":" + matcher.group(4) + (last + offset) + matcher.group(6))); + } + } + matcher.appendTail(result); + return result.toString(); + } + + private String withFilter(String suffix, String range) { + 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); + } + + private byte[] serialize(XSSFWorkbook workbook) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + workbook.write(bytes); + return bytes.toByteArray(); + } + + private SheetXml readSheet(byte[] template, String path) throws IOException { + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(template))) { + for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) { + if (!path.equals(entry.getName())) continue; + String xml = readUtf8(zip); + int start = xml.indexOf("', start); + int end = xml.indexOf("", openEnd); + if (start < 0 || openEnd < 0 || end < 0) throw new IOException("汇总模板缺少 sheetData:" + path); + return new SheetXml(removeSheetDimension(xml.substring(0, openEnd + 1)), + new java.util.TreeMap<>(extractTemplateRows(xml.substring(openEnd + 1, end))), xml.substring(end)); + } + } + throw new IOException("汇总模板缺少工作表:" + path); + } + + private record SheetXml(String prefix, Map rows, String suffix) { } + private record DetailResult(int count, int lastRow, BigDecimal amount) { } + private record DetailStyles(int[] normal, int[] failed) { } + + private static class ProductSummary { + private final String name; + private BigDecimal amount = BigDecimal.ZERO; + private ProductSummary(String name) { this.name = name; } + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArBillExportMapper.java b/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArBillExportMapper.java index 3b4e74ee..5db5c2cd 100644 --- a/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArBillExportMapper.java +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArBillExportMapper.java @@ -13,7 +13,8 @@ public interface ArBillExportMapper { ArBillExport selectLatestSuccessByBillId(Long arBillId); - ArBillExport selectProcessingByBillId(Long arBillId); + ArBillExport selectProcessingByBillAndTemplate(@Param("arBillId") Long arBillId, + @Param("templateId") Long templateId); int insert(ArBillExport export); diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArExportTemplateMapper.java b/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArExportTemplateMapper.java index 2e70a0d9..00fec553 100644 --- a/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArExportTemplateMapper.java +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/mapper/ArExportTemplateMapper.java @@ -1,11 +1,19 @@ package com.bms.receivable.mapper; import java.util.Date; +import java.util.List; import org.apache.ibatis.annotations.Param; import com.bms.receivable.domain.ArExportTemplate; public interface ArExportTemplateMapper { + List selectEnabledList(@Param("businessType") String businessType, + @Param("effectiveDate") Date effectiveDate); + + ArExportTemplate selectEnabledById(@Param("templateId") Long templateId, + @Param("businessType") String businessType, + @Param("effectiveDate") Date effectiveDate); + /** * 查询指定业务类型当前生效的默认模板。 */ diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/service/IArBillService.java b/bms-back/bms-system/src/main/java/com/bms/receivable/service/IArBillService.java index a36c91e6..defa13b5 100644 --- a/bms-back/bms-system/src/main/java/com/bms/receivable/service/IArBillService.java +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/service/IArBillService.java @@ -16,6 +16,7 @@ import com.bms.receivable.domain.vo.ArBillGenerateQuery; import com.bms.receivable.domain.vo.ArBillActionRequest; import com.bms.receivable.domain.vo.ArBillQuery; import com.bms.receivable.domain.vo.ArBillSummary; +import com.bms.receivable.domain.vo.ArBillExportTemplateOption; import com.bms.receivable.security.ArBillRowScope; import com.bms.price.domain.PrcOrderBill; @@ -72,7 +73,9 @@ public interface IArBillService ArBill confirmBill(Long arBillId, ArBillActionRequest request, String operator, String requestId); - ArBillExport exportBill(Long arBillId, String operator, String requestId); + List selectExportTemplates(Long arBillId); + + ArBillExport exportBill(Long arBillId, Long templateId, String operator, String requestId); ArBillExport selectExport(Long exportId); diff --git a/bms-back/bms-system/src/main/java/com/bms/receivable/service/impl/ArBillServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/receivable/service/impl/ArBillServiceImpl.java index c952b7a3..fb2326ea 100644 --- a/bms-back/bms-system/src/main/java/com/bms/receivable/service/impl/ArBillServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/receivable/service/impl/ArBillServiceImpl.java @@ -1,18 +1,13 @@ package com.bms.receivable.service.impl; -import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -20,22 +15,12 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; import jakarta.servlet.http.HttpServletResponse; -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.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; -import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -92,6 +77,8 @@ import com.bms.receivable.domain.vo.ArBillGenerateQuery; import com.bms.receivable.domain.vo.ArBillGenerateRequest; import com.bms.receivable.domain.vo.ArBillQuery; import com.bms.receivable.domain.vo.ArBillSummary; +import com.bms.receivable.domain.vo.ArBillExportTemplateOption; +import com.bms.receivable.export.ArBillWorkbookWriters; import com.bms.common.config.BmsConfig; import com.bms.common.exception.ServiceException; import com.bms.common.utils.DateUtils; @@ -121,35 +108,7 @@ public class ArBillServiceImpl implements IArBillService { private static final Logger log = LoggerFactory.getLogger(ArBillServiceImpl.class); private static final String EXPORT_TEMPLATE_BUSINESS_TYPE = "AR_BILL"; - private static final String EXPORT_TEMPLATE_RESOURCE = "templates/receivable/ar_bill_template.xlsx"; private static final long EXPORT_DOWNLOAD_URL_TTL_MILLIS = 10 * 60 * 1000L; - /** - * Excel 行号从 1 开始;模板第 4 行是表头,明细从第 5 行开始写入。 - */ - private static final int TEMPLATE_DATA_START_ROW = 5; - /** 模板的明细区只有第 5 行;超出的明细行插入在页脚前。 */ - private static final int TEMPLATE_LAST_DETAIL_ROW = 5; - /** 明细与银行信息、合计区域之间固定保留一行空白。 */ - private static final int EXPORT_FOOTER_GAP_ROWS = 1; - /** DrawingML 行号从 0 开始,插入点是模板第 5 行之后。 */ - private static final int TEMPLATE_DRAWING_INSERT_ROW_INDEX = 5; - private static final int TEMPLATE_COLUMN_COUNT = 21; - private static final double EXPORT_DETAIL_ROW_HEIGHT = 20.0; - /** 客户订单号、运单号位于 Excel 的 C、D 列,并保持相同列宽。 */ - private static final int CUSTOMER_ORDER_NO_COLUMN_INDEX = 3; - private static final int TRACKING_NO_COLUMN_INDEX = 4; - private static final int FORMULA_COLUMN_INDEX = 16; - private static final int FEE_TYPE_COLUMN_INDEX = 17; - /** 数值明细列(Excel 列号):重量、尺寸、单价、处理费和应收金额。 */ - private static final Set GENERAL_NUMERIC_EXPORT_COLUMNS = Set.of(8, 9, 10, 11, 12, 13, 14, 15, 19); - private static final double MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH = 16.0; - private static final double MIN_TRACKING_NO_COLUMN_WIDTH = MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH; - private static final double MIN_FORMULA_COLUMN_WIDTH = 17.0; - private static final double MIN_FEE_TYPE_COLUMN_WIDTH = 10.0; - /** - * 单次查询订单数;费用仅查询当前订单批次,避免大账单占满堆内存。 - */ - private static final int EXPORT_PAGE_SIZE = 2000; /** * 异步生成账单单批订单数,2核4G环境下控制内存和事务时长。 */ @@ -164,47 +123,6 @@ public class ArBillServiceImpl implements IArBillService { /** 订单号会分别匹配订单号、运单号和转单号列;预留其他 SQL 参数空间后控制 MySQL 参数总数。 */ private static final int ORDER_IDENTIFIER_SQL_BIND_COUNT = 3; private static final int MAX_SQL_PARAMETER_COUNT = 65000; - /** - * 模板明细行使用的边框、字体和换行样式;样式定义来自 ar_bill_template.xlsx。 - */ - private static final int TEMPLATE_DETAIL_STYLE_INDEX = 31; - private static final String TEMPLATE_SHEET_XML = "xl/worksheets/sheet1.xml"; - private static final String TEMPLATE_SHEET_RELATIONSHIPS_XML = "xl/worksheets/_rels/sheet1.xml.rels"; - private static final String TEMPLATE_STYLES_XML = "xl/styles.xml"; - private static final String SPREADSHEET_DRAWING_NAMESPACE = - "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"; - private static final Pattern DRAWING_RELATIONSHIP_PATTERN = Pattern.compile( - "]*\\bType\\s*=\\s*[\\\"'][^\\\"']*/drawing[\\\"'])(?=[^>]*\\bTarget\\s*=\\s*[\\\"']([^\\\"']+)[\\\"'])[^>]*/?>", - Pattern.DOTALL); - private static final Pattern DRAWING_NAMESPACE_PREFIX_PATTERN = Pattern.compile( - "xmlns:([A-Za-z_][\\w.-]*)\\s*=\\s*[\\\"']" - + Pattern.quote(SPREADSHEET_DRAWING_NAMESPACE) + "[\\\"']"); - private static final Pattern TEMPLATE_COLUMN_PATTERN = Pattern.compile("]*)/\\s*>", Pattern.DOTALL); - private static final Pattern TEMPLATE_COLUMN_MIN_PATTERN = Pattern.compile("\\bmin\\s*=\\s*[\"'](\\d+)[\"']"); - private static final Pattern TEMPLATE_COLUMN_MAX_PATTERN = Pattern.compile("\\bmax\\s*=\\s*[\"'](\\d+)[\"']"); - private static final Pattern TEMPLATE_COLUMN_WIDTH_PATTERN = Pattern.compile("\\bwidth\\s*=\\s*[\"']([\\d.]+)[\"']"); - private static final Pattern TEMPLATE_ROW_PATTERN = Pattern.compile( - "]*\\br=\"(\\d+)\"[^>]*>.*?", Pattern.DOTALL); - private static final Pattern CELL_PATTERN = Pattern.compile( - "]*?)(?:/\\s*>|>(.*?))", Pattern.DOTALL); - private static final Pattern CELL_REF_PATTERN = Pattern.compile( - "\\br\\s*=\\s*[\\\"']([A-Z]+\\d+)[\\\"']", Pattern.CASE_INSENSITIVE); - private static final Pattern CELL_STYLE_PATTERN = Pattern.compile( - "\\bs\\s*=\\s*[\\\"'](\\d+)[\\\"']", Pattern.CASE_INSENSITIVE); - private static final Pattern CELL_ROW_REF_PATTERN = Pattern.compile( - "(]*\\br=\")([A-Z]+)\\d+(\")"); - private static final Pattern ROW_REF_PATTERN = Pattern.compile( - "(]*\\br=\")\\d+(\")"); - private static final Pattern DIMENSION_PATTERN = Pattern.compile("]*/>"); - private static final Pattern MERGE_REF_PATTERN = Pattern.compile( - "(]*\\bref=\")([A-Z]+)(\\d+)(?::([A-Z]+)(\\d+))?(\")"); - - private record ExportStyleIndexes(int failedDetail, int detailNo, int failedDetailNo, - int customerOrderNo, int failedCustomerOrderNo, - int trackingNo, int failedTrackingNo, - int generalNumber, int failedGeneralNumber, - int formula, int failedFormula) { - } @Autowired private ArBillMapper billMapper; @@ -223,6 +141,8 @@ public class ArBillServiceImpl implements IArBillService { @Autowired private ArExportTemplateMapper exportTemplateMapper; @Autowired + private ArBillWorkbookWriters workbookWriters; + @Autowired private ArBillDetailMapper detailMapper; @Autowired private ArBillDetailFeeMapper detailFeeMapper; @@ -1057,12 +977,23 @@ public class ArBillServiceImpl implements IArBillService { return result; } - /** - * 创建异步导出任务;模板版本在提交时绑定,保证后续模板变更不影响历史导出。 - */ + @Override + public List selectExportTemplates(Long arBillId) { + billScope.requireBillAccessible(arBillId); + ArBill bill = billMapper.selectArBillById(arBillId); + if (bill == null) throw new ServiceException("应收账单不存在"); + return exportTemplateMapper.selectEnabledList(EXPORT_TEMPLATE_BUSINESS_TYPE, exportTemplateDate(bill)) + .stream().map(ArBillExportTemplateOption::from).toList(); + } + + private Date exportTemplateDate(ArBill bill) { + return bill.getBillDate() == null ? bill.getBillPeriodEnd() : bill.getBillDate(); + } + + /** 创建异步任务时绑定选中的模板;未传编号时兼容原默认模板导出。 */ @Override @Transactional(rollbackFor = Exception.class) - public ArBillExport exportBill(Long arBillId, String operator, String requestId) { + public ArBillExport exportBill(Long arBillId, Long templateId, String operator, String requestId) { long startedAt = System.nanoTime(); Long exportUserId = SecurityUtils.getUserId(); billScope.requireBillAccessible(arBillId); @@ -1075,6 +1006,10 @@ public class ArBillServiceImpl implements IArBillService { ArBillExport previousExport = exportMapper.selectById(Long.valueOf(previous.getObjectId())); if (previousExport != null) { billScope.requireBillAccessible(previousExport.getArBillId()); + if (!Objects.equals(arBillId, previousExport.getArBillId()) + || (templateId != null && !Objects.equals(templateId, previousExport.getTemplateId()))) { + throw new ServiceException("导出请求编号已用于其他账单或模板,请重新发起导出"); + } log.info("应收账单导出请求命中幂等记录,operator={}, requestId={}, arBillId={}, exportId={}, status={}, costMs={}", safeLogValue(operator), safeLogValue(requestId), arBillId, previousExport.getExportId(), previousExport.getExportStatus(), elapsedMillis(startedAt)); @@ -1090,21 +1025,25 @@ public class ArBillServiceImpl implements IArBillService { bill.getStatus(), "草稿或作废账单不可导出", operator, requestId); } - ArBillExport processing = exportMapper.selectProcessingByBillId(arBillId); + if (templateId != null && templateId <= 0) throw new ServiceException("导出模板编号无效"); + ArExportTemplate template = templateId == null + ? exportTemplateMapper.selectDefaultEnabled(EXPORT_TEMPLATE_BUSINESS_TYPE, exportTemplateDate(bill)) + : exportTemplateMapper.selectEnabledById(templateId, EXPORT_TEMPLATE_BUSINESS_TYPE, exportTemplateDate(bill)); + if (template == null) { + throw failure(arBillId, ArLogObjectType.EXPORT, String.valueOf(arBillId), ArLogOperationType.EXPORT, + bill.getStatus(), templateId == null ? "未配置启用中的应收账单默认导出模板" + : "所选应收账单模板不存在、已停用或不在生效期内,请重新选择", operator, requestId); + } + ArBillExport processing = exportMapper.selectProcessingByBillAndTemplate(arBillId, template.getTemplateId()); if (processing != null) { log.info("应收账单导出任务已存在,operator={}, requestId={}, arBillId={}, exportId={}, status={}, costMs={}", safeLogValue(operator), safeLogValue(requestId), arBillId, processing.getExportId(), processing.getExportStatus(), elapsedMillis(startedAt)); return processing; } - ArExportTemplate template = exportTemplateMapper.selectDefaultEnabled(EXPORT_TEMPLATE_BUSINESS_TYPE, - bill.getBillDate() == null ? bill.getBillPeriodEnd() : bill.getBillDate()); - if (template == null) { - throw failure(arBillId, ArLogObjectType.EXPORT, String.valueOf(arBillId), ArLogOperationType.EXPORT, - bill.getStatus(), "未配置启用中的应收账单默认导出模板", operator, requestId); - } String fileName = safeFilePart(bill.getCustomerCode()) + "_" + safeFilePart(bill.getCustomerName()) + "_" - + new SimpleDateFormat("yyyyMM").format(bill.getBillPeriodEnd()) + ".xlsx"; + + new SimpleDateFormat("yyyyMM").format(bill.getBillPeriodEnd()) + + (workbookWriters.isSummary(template) ? "_汇总" : "") + ".xlsx"; ArBillExport export = new ArBillExport(); export.setArBillId(arBillId); export.setFileName(fileName); @@ -1172,7 +1111,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); - writeOoxmlWorkbook(bill, template, temp); + workbookWriters.select(template).write(bill, template, temp); export.setFileSize(Files.size(temp)); export.setFileHash(sha256(temp)); export.setStorageKey(ossStorage.upload(temp, objectKey, @@ -1406,842 +1345,6 @@ public class ArBillServiceImpl implements IArBillService { return template; } - /** - * 复制模板 ZIP 包,替换明细工作表并追加黄色明细样式,保留模板其他资源。 - */ - private void writeOoxmlWorkbook(ArBill bill, ArExportTemplate template, Path target) throws IOException { - // 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。 - StylesTable styles = readExportStyles(template); - String drawingPartPath = readTemplateDrawingPartPath(template); - XSSFCellStyle detailNoStyle = styles.createCellStyle(); - detailNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - detailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); - int detailNoStyleIndex = Short.toUnsignedInt(detailNoStyle.getIndex()); - XSSFCellStyle failedDetailStyle = styles.createCellStyle(); - failedDetailStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - failedDetailStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - failedDetailStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - int failedDetailStyleIndex = Short.toUnsignedInt(failedDetailStyle.getIndex()); - XSSFCellStyle customerOrderNoStyle = styles.createCellStyle(); - customerOrderNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - customerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); - int customerOrderNoStyleIndex = Short.toUnsignedInt(customerOrderNoStyle.getIndex()); - XSSFCellStyle failedCustomerOrderNoStyle = styles.createCellStyle(); - failedCustomerOrderNoStyle.cloneStyleFrom(failedDetailStyle); - failedCustomerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); - int failedCustomerOrderNoStyleIndex = Short.toUnsignedInt(failedCustomerOrderNoStyle.getIndex()); - XSSFCellStyle trackingNoStyle = styles.createCellStyle(); - trackingNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - trackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); - int trackingNoStyleIndex = Short.toUnsignedInt(trackingNoStyle.getIndex()); - XSSFCellStyle failedTrackingNoStyle = styles.createCellStyle(); - failedTrackingNoStyle.cloneStyleFrom(failedDetailStyle); - failedTrackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); - int failedTrackingNoStyleIndex = Short.toUnsignedInt(failedTrackingNoStyle.getIndex()); - XSSFCellStyle generalNumberStyle = styles.createCellStyle(); - generalNumberStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - generalNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); - int generalNumberStyleIndex = Short.toUnsignedInt(generalNumberStyle.getIndex()); - XSSFCellStyle failedGeneralNumberStyle = styles.createCellStyle(); - failedGeneralNumberStyle.cloneStyleFrom(failedDetailStyle); - failedGeneralNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); - int failedGeneralNumberStyleIndex = Short.toUnsignedInt(failedGeneralNumberStyle.getIndex()); - XSSFCellStyle failedDetailNoStyle = styles.createCellStyle(); - failedDetailNoStyle.cloneStyleFrom(failedDetailStyle); - failedDetailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); - int failedDetailNoStyleIndex = Short.toUnsignedInt(failedDetailNoStyle.getIndex()); - XSSFCellStyle formulaStyle = styles.createCellStyle(); - formulaStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); - formulaStyle.setShrinkToFit(true); - int formulaStyleIndex = Short.toUnsignedInt(formulaStyle.getIndex()); - XSSFCellStyle failedFormulaStyle = styles.createCellStyle(); - failedFormulaStyle.cloneStyleFrom(failedDetailStyle); - failedFormulaStyle.setShrinkToFit(true); - int failedFormulaStyleIndex = Short.toUnsignedInt(failedFormulaStyle.getIndex()); - ExportStyleIndexes exportStyleIndexes = new ExportStyleIndexes( - failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex, - customerOrderNoStyleIndex, failedCustomerOrderNoStyleIndex, - trackingNoStyleIndex, failedTrackingNoStyleIndex, - generalNumberStyleIndex, failedGeneralNumberStyleIndex, - formulaStyleIndex, failedFormulaStyleIndex); - try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input); - OutputStream fileOutput = Files.newOutputStream(target); ZipOutputStream output = new ZipOutputStream(fileOutput)) { - boolean replaced = false; - Integer drawingRowOffset = null; - String pendingDrawingXml = null; - for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { - String entryName = entry.getName(); - if (!StringUtils.isEmpty(drawingPartPath) && drawingPartPath.equals(entryName)) { - String drawingXml = readUtf8(templateZip); - if (drawingRowOffset == null) { - // ZIP 包内绘图可能先于工作表出现,先缓存小型绘图 XML,待明细行数确定后再写入。 - pendingDrawingXml = drawingXml; - } else { - writeDrawingEntry(output, entryName, drawingXml, drawingRowOffset.intValue()); - } - templateZip.closeEntry(); - continue; - } - if (TEMPLATE_SHEET_XML.equals(entry.getName())) { - output.putNextEntry(new ZipEntry(entryName)); - int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes); - output.closeEntry(); - replaced = true; - drawingRowOffset = Integer.valueOf(rowOffset); - if (pendingDrawingXml != null) { - writeDrawingEntry(output, drawingPartPath, pendingDrawingXml, rowOffset); - pendingDrawingXml = null; - } - templateZip.closeEntry(); - continue; - } - - output.putNextEntry(new ZipEntry(entryName)); - if (TEMPLATE_STYLES_XML.equals(entryName)) { - styles.writeTo(output); - } else if (!entry.isDirectory()) { - templateZip.transferTo(output); - } - output.closeEntry(); - templateZip.closeEntry(); - } - if (!replaced) { - throw new IOException("应收账单导出模板工作表不存在: " + TEMPLATE_SHEET_XML); - } - } - } - - private String readTemplateDrawingPartPath(ArExportTemplate template) throws IOException { - try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { - for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { - if (TEMPLATE_SHEET_RELATIONSHIPS_XML.equals(entry.getName())) { - String relationshipsXml = readUtf8(templateZip); - Matcher matcher = DRAWING_RELATIONSHIP_PATTERN.matcher(relationshipsXml); - if (matcher.find()) { - String target = matcher.group(1); - if (target.startsWith("/")) { - return target.substring(1); - } - Path sheetDirectory = Paths.get(TEMPLATE_SHEET_XML).getParent(); - return sheetDirectory.resolve(target).normalize().toString().replace('\\', '/'); - } - return null; - } - templateZip.closeEntry(); - } - } - return null; - } - - private void writeDrawingEntry(ZipOutputStream output, String entryName, String drawingXml, - int rowOffset) throws IOException { - output.putNextEntry(new ZipEntry(entryName)); - writeUtf8(output, shiftDrawingAnchorRows(drawingXml, rowOffset)); - output.closeEntry(); - } - - /** - * 根据明细新增行及页脚前空行,同步下移图片锚点,保持二维码与页脚的相对位置。 - */ - private String shiftDrawingAnchorRows(String drawingXml, int rowOffset) { - if (rowOffset <= 0) { - return drawingXml; - } - Matcher namespaceMatcher = DRAWING_NAMESPACE_PREFIX_PATTERN.matcher(drawingXml); - String rowTag = namespaceMatcher.find() - ? Pattern.quote(namespaceMatcher.group(1)) + ":row" - : "row"; - Pattern rowPattern = Pattern.compile("(<" + rowTag + "\\s*>\\s*)(\\d+)(\\s*)"); - Matcher rowMatcher = rowPattern.matcher(drawingXml); - StringBuffer shifted = new StringBuffer(); - while (rowMatcher.find()) { - int rowIndex = Integer.parseInt(rowMatcher.group(2)); - int targetRowIndex = rowIndex >= TEMPLATE_DRAWING_INSERT_ROW_INDEX ? rowIndex + rowOffset : rowIndex; - rowMatcher.appendReplacement(shifted, Matcher.quoteReplacement( - rowMatcher.group(1) + targetRowIndex + rowMatcher.group(3))); - } - rowMatcher.appendTail(shifted); - return shifted.toString(); - } - - private StylesTable readExportStyles(ArExportTemplate template) throws IOException { - try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { - for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { - if (TEMPLATE_STYLES_XML.equals(entry.getName())) { - StylesTable styles = new StylesTable(templateZip); - if (styles.getNumCellStyles() <= TEMPLATE_DETAIL_STYLE_INDEX) { - throw new IOException("应收账单导出模板缺少明细样式: " + TEMPLATE_DETAIL_STYLE_INDEX); - } - return styles; - } - templateZip.closeEntry(); - } - } - throw new IOException("应收账单导出模板缺少样式表: " + TEMPLATE_STYLES_XML); - } - - private InputStream openTemplateStream(ArExportTemplate template) throws IOException { - String storageType = StringUtils.isEmpty(template.getStorageType()) ? "CLASSPATH" : template.getStorageType(); - String storageKey = StringUtils.isEmpty(template.getStorageKey()) ? EXPORT_TEMPLATE_RESOURCE : template.getStorageKey(); - if ("CLASSPATH".equalsIgnoreCase(storageType)) { - ClassPathResource resource = new ClassPathResource(storageKey); - if (!resource.exists()) { - throw new IOException("应收账单导出模板不存在: " + storageKey); - } - return resource.getInputStream(); - } - if ("FILE".equalsIgnoreCase(storageType)) { - if (!FileUtils.checkAllowDownload(storageKey)) { - throw new IOException("应收账单模板路径非法"); - } - Path profileRoot = new File(BmsConfig.getProfile()).toPath().toAbsolutePath().normalize(); - Path templatePath = profileRoot.resolve(storageKey).normalize(); - if (!templatePath.startsWith(profileRoot) || !Files.exists(templatePath)) { - throw new IOException("应收账单导出模板不存在: " + storageKey); - } - return Files.newInputStream(templatePath); - } - throw new IOException("不支持的应收账单模板存储类型: " + storageType); - } - - /** - * 以 XML 流方式写入表头、分页明细和银行信息,避免 POI 在大数据量下移动行。 - */ - private int writeOoxmlSheet(String templateXml, ArBill bill, OutputStream output, - ExportStyleIndexes styleIndexes) throws IOException { - int sheetDataStart = templateXml.indexOf("', sheetDataStart); - int sheetDataEnd = templateXml.indexOf("", sheetDataOpenEnd); - if (sheetDataStart < 0 || sheetDataOpenEnd < 0 || sheetDataEnd < 0) { - throw new IOException("应收账单导出模板缺少 sheetData 节点"); - } - - Map templateRows = extractTemplateRows(templateXml.substring(sheetDataOpenEnd + 1, sheetDataEnd)); - Map receiveTimeRange = detailMapper.selectReceiveTimeRangeByBillId(bill.getArBillId()); - String prefix = adjustExportColumnWidths( - removeSheetDimension(templateXml.substring(0, sheetDataOpenEnd + 1))); - writeUtf8(output, prefix); - - String headerRow = replaceCellXml(templateRows.get(1), "A1", - StringUtils.isEmpty(bill.getBankAccountName()) ? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName(), false); - writeUtf8(output, headerRow); - writeUtf8(output, templateRows.get(2)); - String customerRow = replaceCellXml(templateRows.get(3), "C3", bill.getCustomerName(), false); - // 账单所属期区域为 O3:U3 合并单元格,必须写入左上角 O3 才能显示。 - customerRow = replaceCellXml(customerRow, "O3", exportReceiveTimeRange(receiveTimeRange), false); - writeUtf8(output, customerRow); - writeUtf8(output, templateRows.get(4)); - - int rowIndex = TEMPLATE_DATA_START_ROW; - int lastDetailNo = 0; - while (true) { - List details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE); - if (details.isEmpty()) { - break; - } - attachFees(details); - for (ArBillDetail detail : details) { - writeOoxmlDetailRow(output, rowIndex++, detail, styleIndexes); - } - lastDetailNo = details.get(details.size() - 1).getDetailNo(); - } - - int lastDetailRow = Math.max(rowIndex - 1, TEMPLATE_LAST_DETAIL_ROW); - int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW + EXPORT_FOOTER_GAP_ROWS; - writeUtf8(output, ""); - writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber()); - String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset); - writeUtf8(output, suffix); - return rowOffset; - } - - /** - * 仅加宽客户订单号、运单号、计算公式和费用类型列;不缩小模板原有列宽。 - */ - private String adjustExportColumnWidths(String sheetPrefix) throws IOException { - Matcher columnMatcher = TEMPLATE_COLUMN_PATTERN.matcher(sheetPrefix); - StringBuffer result = new StringBuffer(); - int[] targetColumns = { - CUSTOMER_ORDER_NO_COLUMN_INDEX, - TRACKING_NO_COLUMN_INDEX, - FORMULA_COLUMN_INDEX, - FEE_TYPE_COLUMN_INDEX - }; - double[] minimumWidths = { - MIN_CUSTOMER_ORDER_NO_COLUMN_WIDTH, - MIN_TRACKING_NO_COLUMN_WIDTH, - MIN_FORMULA_COLUMN_WIDTH, - MIN_FEE_TYPE_COLUMN_WIDTH - }; - boolean[] targetColumnsFound = new boolean[targetColumns.length]; - - while (columnMatcher.find()) { - String attributes = columnMatcher.group(1); - Matcher minMatcher = TEMPLATE_COLUMN_MIN_PATTERN.matcher(attributes); - Matcher maxMatcher = TEMPLATE_COLUMN_MAX_PATTERN.matcher(attributes); - Matcher widthMatcher = TEMPLATE_COLUMN_WIDTH_PATTERN.matcher(attributes); - if (!minMatcher.find() || !maxMatcher.find() || !widthMatcher.find()) { - columnMatcher.appendReplacement(result, Matcher.quoteReplacement(columnMatcher.group())); - continue; - } - - int min = Integer.parseInt(minMatcher.group(1)); - int max = Integer.parseInt(maxMatcher.group(1)); - double currentWidth = Double.parseDouble(widthMatcher.group(1)); - boolean needsExpansion = false; - for (int index = 0; index < targetColumns.length; index++) { - if (min <= targetColumns[index] && max >= targetColumns[index]) { - targetColumnsFound[index] = true; - needsExpansion |= currentWidth < minimumWidths[index]; - } - } - if (!needsExpansion) { - columnMatcher.appendReplacement(result, Matcher.quoteReplacement(columnMatcher.group())); - continue; - } - - StringBuilder replacement = new StringBuilder(); - int segmentStart = min; - for (int index = 0; index < targetColumns.length; index++) { - int column = targetColumns[index]; - if (column < min || column > max || currentWidth >= minimumWidths[index]) { - continue; - } - if (segmentStart < column) { - appendColumnSegment(replacement, attributes, segmentStart, column - 1, currentWidth, false); - } - appendColumnSegment(replacement, attributes, column, column, minimumWidths[index], true); - segmentStart = column + 1; - } - if (segmentStart <= max) { - appendColumnSegment(replacement, attributes, segmentStart, max, currentWidth, false); - } - columnMatcher.appendReplacement(result, Matcher.quoteReplacement(replacement.toString())); - } - columnMatcher.appendTail(result); - - for (boolean found : targetColumnsFound) { - if (!found) { - throw new IOException("应收账单导出模板缺少客户订单号、运单号、计算公式或费用类型列宽定义"); - } - } - return result.toString(); - } - - private void appendColumnSegment(StringBuilder xml, String attributes, int min, int max, double width, - boolean customWidth) { - String segmentAttributes = replaceColumnAttribute(attributes, "min", String.valueOf(min)); - segmentAttributes = replaceColumnAttribute(segmentAttributes, "max", String.valueOf(max)); - segmentAttributes = replaceColumnAttribute(segmentAttributes, "width", String.valueOf(width)); - if (customWidth) { - segmentAttributes = replaceColumnAttribute(segmentAttributes, "customWidth", "1"); - } - xml.append(""); - } - - private String replaceColumnAttribute(String attributes, String name, String value) { - Pattern attributePattern = Pattern.compile("(\\b" + name + "\\s*=\\s*[\"'])([^\"']*)([\"'])", - Pattern.CASE_INSENSITIVE); - Matcher matcher = attributePattern.matcher(attributes); - if (matcher.find()) { - String replacement = matcher.group(1) + value + matcher.group(3); - return matcher.replaceFirst(Matcher.quoteReplacement(replacement)); - } - return attributes + " " + name + "=\"" + value + "\""; - } - - private Map extractTemplateRows(String sheetData) { - Map rows = new HashMap<>(); - Matcher matcher = TEMPLATE_ROW_PATTERN.matcher(sheetData); - while (matcher.find()) { - rows.put(Integer.valueOf(matcher.group(1)), matcher.group()); - } - return rows; - } - - private void writeOoxmlFooter(OutputStream output, Map templateRows, int rowOffset, - ArBill bill, int generalNumberStyleIndex) throws IOException { - String totalAmountFormula = "SUM(S" + TEMPLATE_DATA_START_ROW + ":INDEX(S:S,ROW()-1))"; - for (int offset = 0; offset < 4; offset++) { - int sourceRowNumber = TEMPLATE_LAST_DETAIL_ROW + offset + 1; - int targetRowNumber = sourceRowNumber + rowOffset; - String row = shiftRowXml(templateRows.get(sourceRowNumber), targetRowNumber); - if (offset == 0) { - row = replaceCellXml(row, "B" + targetRowNumber, "银行信息", false); - row = replaceCellXml(row, "P" + targetRowNumber, "本期应收金额", false); - row = replaceFormulaCellXml(row, "S" + targetRowNumber, totalAmountFormula, - nvl(bill.getTotalAmount()), generalNumberStyleIndex); - } else if (offset == 1) { - row = replaceCellXml(row, "B" + targetRowNumber, "开户名", false); - row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankAccountName(), false); - row = replaceCellXml(row, "P" + targetRowNumber, "本期已核销金额", false); - row = replaceCellXml(row, "S" + targetRowNumber, bill.getWrittenOffAmount(), true, - generalNumberStyleIndex); - } else if (offset == 2) { - row = replaceCellXml(row, "B" + targetRowNumber, "账号", false); - row = replaceCellXml(row, "C" + targetRowNumber, exportBankAccountNo(bill.getBankAccountNo()), false); - row = replaceCellXml(row, "P" + targetRowNumber, "本期未核销金额", false); - String unwrittenAmountFormula = "S" + (targetRowNumber - 2) + "-S" + (targetRowNumber - 1); - row = replaceFormulaCellXml(row, "S" + targetRowNumber, unwrittenAmountFormula, - nvl(bill.getUnwrittenAmount()), generalNumberStyleIndex); - } else { - row = replaceCellXml(row, "B" + targetRowNumber, "开户行", false); - row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankName(), false); - } - writeUtf8(output, row); - } - } - - private void writeOoxmlDetailRow(OutputStream output, int rowNumber, ArBillDetail detail, - ExportStyleIndexes styleIndexes) throws IOException { - String failureDescription = exportBillingFailDescription(detail.getBillingFailStatus()); - boolean failedDetail = !failureDescription.isEmpty(); - int styleIndex = failedDetail ? styleIndexes.failedDetail() : TEMPLATE_DETAIL_STYLE_INDEX; - int sequenceStyleIndex = failedDetail ? styleIndexes.failedDetailNo() : styleIndexes.detailNo(); - Object[] values = { - detail.getDetailNo(), - detail.getReceiveTime() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(detail.getReceiveTime()), - detail.getOrderNo(), detail.getTrackingNo(), - StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(), - StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(), - detail.getDestPostcode(), detail.getReceiveWeight(), detail.getPkgLength(), - detail.getPkgHeight(), detail.getPkgWidth(), detail.getVolumeWeight(), - detail.getChargeWeight(), exportUnitPrice(detail), exportProcessingFee(detail), - exportFormula(detail), exportFeeType(), detail.getCurrency(), detail.getTotalAmount(), exportRemark(detail), - failureDescription - }; - StringBuilder row = new StringBuilder(2048); - row.append(""); - for (int index = 0; index < TEMPLATE_COLUMN_COUNT; index++) { - int excelColumnIndex = index + 1; - int cellStyleIndex = styleIndex; - if (index == 0) { - cellStyleIndex = sequenceStyleIndex; - } else if (excelColumnIndex == CUSTOMER_ORDER_NO_COLUMN_INDEX) { - cellStyleIndex = failedDetail ? styleIndexes.failedCustomerOrderNo() : styleIndexes.customerOrderNo(); - } else if (excelColumnIndex == TRACKING_NO_COLUMN_INDEX) { - cellStyleIndex = failedDetail ? styleIndexes.failedTrackingNo() : styleIndexes.trackingNo(); - } else if (excelColumnIndex == FORMULA_COLUMN_INDEX) { - cellStyleIndex = failedDetail ? styleIndexes.failedFormula() : styleIndexes.formula(); - } else if (GENERAL_NUMERIC_EXPORT_COLUMNS.contains(excelColumnIndex)) { - cellStyleIndex = failedDetail ? styleIndexes.failedGeneralNumber() : styleIndexes.generalNumber(); - } - appendOoxmlCell(row, (char) ('A' + index) + String.valueOf(rowNumber), values[index], cellStyleIndex); - } - row.append(""); - writeUtf8(output, row.toString()); - } - - private String exportBillingFailDescription(Integer billingFailStatus) { - BillBillingFailStatus status = BillBillingFailStatus.of(billingFailStatus); - if (status == null) { - return ""; - } - return switch (status) { - case SUCCESS -> ""; - case NOT_BILLED -> "未计费"; - case PRODUCT -> "销售价未匹配产品"; - case COUNTRY -> "销售价未匹配国家"; - case WEIGHT -> "销售价未匹配重量段"; - case CATALOG_PRODUCT -> "产品价未匹配产品"; - case CATALOG_COUNTRY -> "产品价未匹配国家"; - case CATALOG_WEIGHT -> "产品价未匹配重量段"; - case NO_CUSTOMER_PACKAGE -> "未绑定套餐"; - case NO_ACTIVE_PACKAGE_VERSION -> "套餐未启用/无生效版本"; - case ALREADY_IN_AR_BILL -> "已生成应收账单"; - case PRODUCT_ARCHIVE_MISSING -> "产品档案缺失"; - case PRICE_NOT_HIT -> "未命中价格"; - case ZONE_PRICE_NOT_HIT -> "分区无价格"; - case POSTCODE_REQUIRED -> "邮编必填"; - case POSTCODE_ZONE_NOT_FOUND -> "邮编未匹配分区"; - case ORACLE_ORDER_NOT_FOUND -> "上游订单不存在"; - case ORACLE_ORDERNO_EMPTY -> "上游订单号为空"; - case ORACLE_CUSTOMER_EMPTY -> "上游客户为空"; - case ORACLE_PRODUCT_EMPTY -> "上游产品为空"; - case ORACLE_WEIGHT_INVALID -> "上游重量无效"; - case BILL_TIME_EMPTY -> "计费时间为空"; - case REFUND_ORDER_UNRESOLVED -> "退费订单无法解析"; - case CUSTOMER_CODE_REQUIRED -> "客户代码为空"; - case CUSTOMER_DISABLED -> "客户已停用"; - case FREIGHT_MISSING -> "运费为空"; - case UNKNOWN -> "未知失败"; - }; - } - - private void appendOoxmlCell(StringBuilder row, String reference, Object value, int styleIndex) { - row.append("").append(numberText((Number) value)).append(""); - } else { - String text = value == null ? "" : String.valueOf(value); - row.append(" t=\"inlineStr\">").append(xmlEscape(text)).append(""); - } - } - - private String replaceCellXml(String rowXml, String reference, Object value, boolean numeric) throws IOException { - return replaceCellXml(rowXml, reference, value, numeric, null); - } - - private String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, int styleIndex) - throws IOException { - return replaceCellXml(rowXml, reference, value, numeric, null, styleIndex); - } - - private String replaceFormulaCellXml(String rowXml, String reference, String formula, Number cachedValue) - throws IOException { - return replaceCellXml(rowXml, reference, cachedValue, true, formula); - } - - private String replaceFormulaCellXml(String rowXml, String reference, String formula, Number cachedValue, - int styleIndex) throws IOException { - return replaceCellXml(rowXml, reference, cachedValue, true, formula, styleIndex); - } - - private String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, String formula) - throws IOException { - return replaceCellXml(rowXml, reference, value, numeric, formula, null); - } - - private String replaceCellXml(String rowXml, String reference, Object value, boolean numeric, String formula, - Integer styleIndex) throws IOException { - if (rowXml == null) { - throw new IOException("应收账单模板缺少行: " + reference); - } - Matcher matcher = CELL_PATTERN.matcher(rowXml); - StringBuffer result = new StringBuffer(); - boolean found = false; - while (matcher.find()) { - String attributes = matcher.group(1); - Matcher referenceMatcher = CELL_REF_PATTERN.matcher(attributes); - if (!referenceMatcher.find() || !reference.equalsIgnoreCase(referenceMatcher.group(1))) { - matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); - continue; - } - found = true; - String normalizedAttributes = attributes.replaceAll("(?i)\\s+t\\s*=\\s*[\\\"'][^\\\"']*[\\\"']", "") - .replaceAll("\\s*/\\s*$", ""); - if (styleIndex != null) { - normalizedAttributes = replaceCellStyle(normalizedAttributes, styleIndex); - } - StringBuilder cell = new StringBuilder(""); - if (numeric) { - if (formula != null) { - cell.append("").append(xmlEscape(formula)).append(""); - } - cell.append("").append(value == null ? "" : numberText((Number) value)).append(""); - } else { - String text = value == null ? "" : String.valueOf(value); - cell.append("").append(xmlEscape(text)).append(""); - } - cell.append(""); - matcher.appendReplacement(result, Matcher.quoteReplacement(cell.toString())); - } - matcher.appendTail(result); - if (!found) { - return insertMissingCellXml(rowXml, reference, value, numeric, formula, styleIndex); - } - return result.toString(); - } - - private String replaceCellStyle(String attributes, int styleIndex) { - Matcher matcher = CELL_STYLE_PATTERN.matcher(attributes); - if (!matcher.find()) { - return attributes + " s=\"" + styleIndex + "\""; - } - return matcher.replaceFirst(Matcher.quoteReplacement("s=\"" + styleIndex + "\"")); - } - - /** - * 兼容不同 Excel/WPS 版本保存后被省略的空单元格,按列顺序补回动态单元格。 - * C3/P3 使用模板中对应的样式,避免客户名称或账单周期单元格变成无边框样式。 - */ - private String insertMissingCellXml(String rowXml, String reference, Object value, boolean numeric, String formula, - Integer styleIndex) throws IOException { - int rowEnd = rowXml.lastIndexOf(""); - if (rowEnd < 0) { - throw new IOException("应收账单模板缺少行结束节点: " + reference); - } - int targetColumn = columnNumber(reference); - int insertAt = rowEnd; - Matcher matcher = CELL_PATTERN.matcher(rowXml); - while (matcher.find()) { - Matcher referenceMatcher = CELL_REF_PATTERN.matcher(matcher.group(1)); - if (referenceMatcher.find() && columnNumber(referenceMatcher.group(1)) > targetColumn) { - insertAt = matcher.start(); - break; - } - } - - String style = styleIndex == null ? fallbackCellStyle(reference) : String.valueOf(styleIndex); - StringBuilder cell = new StringBuilder(""); - if (formula != null) { - cell.append("").append(xmlEscape(formula)).append(""); - } - cell.append("").append(value == null ? "" : numberText((Number) value)).append(""); - } else { - String text = value == null ? "" : String.valueOf(value); - cell.append(" t=\"inlineStr\">").append(xmlEscape(text)).append(""); - } - return rowXml.substring(0, insertAt) + cell + rowXml.substring(insertAt); - } - - private int columnNumber(String reference) { - int result = 0; - for (int index = 0; index < reference.length() && Character.isLetter(reference.charAt(index)); index++) { - result = result * 26 + Character.toUpperCase(reference.charAt(index)) - 'A' + 1; - } - return result; - } - - private String fallbackCellStyle(String reference) { - if ("A1".equalsIgnoreCase(reference)) { - return "5"; - } - if ("C3".equalsIgnoreCase(reference)) { - return "11"; - } - if ("O3".equalsIgnoreCase(reference) || "P3".equalsIgnoreCase(reference)) { - return "15"; - } - return null; - } - - private String shiftRowXml(String rowXml, int targetRowNumber) throws IOException { - if (rowXml == null) { - throw new IOException("应收账单模板缺少合计区域行"); - } - Matcher rowMatcher = ROW_REF_PATTERN.matcher(rowXml); - if (!rowMatcher.find()) { - throw new IOException("应收账单模板行缺少行号"); - } - StringBuffer shifted = new StringBuffer(); - rowMatcher.appendReplacement(shifted, Matcher.quoteReplacement(rowMatcher.group(1) + targetRowNumber + rowMatcher.group(2))); - rowMatcher.appendTail(shifted); - - Matcher cellMatcher = CELL_ROW_REF_PATTERN.matcher(shifted.toString()); - StringBuffer result = new StringBuffer(); - while (cellMatcher.find()) { - cellMatcher.appendReplacement(result, Matcher.quoteReplacement( - cellMatcher.group(1) + cellMatcher.group(2) + targetRowNumber + cellMatcher.group(3))); - } - cellMatcher.appendTail(result); - return result.toString(); - } - - private String shiftFooterMerges(String xml, int rowOffset) { - Matcher matcher = MERGE_REF_PATTERN.matcher(xml); - StringBuffer result = new StringBuffer(); - int sourceFooterStart = TEMPLATE_LAST_DETAIL_ROW + 1; - int sourceFooterEnd = sourceFooterStart + 3; - while (matcher.find()) { - int firstRow = Integer.parseInt(matcher.group(3)); - String lastColumn = matcher.group(4); - String lastRowText = matcher.group(5); - int lastRow = lastRowText == null ? firstRow : Integer.parseInt(lastRowText); - if (firstRow >= sourceFooterStart && lastRow <= sourceFooterEnd) { - String replacement = matcher.group(1) + matcher.group(2) + (firstRow + rowOffset) - + (lastColumn == null ? "" : ":" + lastColumn + (lastRow + rowOffset)) + matcher.group(6); - matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); - } else { - matcher.appendReplacement(result, Matcher.quoteReplacement(matcher.group())); - } - } - matcher.appendTail(result); - return result.toString(); - } - - private String removeSheetDimension(String xml) { - Matcher matcher = DIMENSION_PATTERN.matcher(xml); - StringBuffer result = new StringBuffer(); - while (matcher.find()) { - matcher.appendReplacement(result, ""); - } - matcher.appendTail(result); - return result.toString(); - } - - private String readUtf8(InputStream input) throws IOException { - StringBuilder result = new StringBuilder(16384); - char[] buffer = new char[8192]; - java.io.Reader reader = new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8); - for (int size; (size = reader.read(buffer)) != -1; ) { - result.append(buffer, 0, size); - } - return result.toString(); - } - - private void writeUtf8(OutputStream output, String value) throws IOException { - output.write(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - } - - private String numberText(Number value) { - return value instanceof BigDecimal ? ((BigDecimal) value).toPlainString() : value.toString(); - } - - private String xmlEscape(String value) { - return value.replace("&", "&").replace("<", "<").replace(">", ">") - .replace("\"", """).replace("'", "'"); - } - - /** - * 只为当前内存中的一批明细查询费用,避免一次加载整张账单的费用数据。 - */ - private void attachFees(List details) { - List detailIds = new ArrayList<>(); - Map> feesByDetailId = new HashMap<>(); - for (ArBillDetail detail : details) { - detailIds.add(detail.getDetailId()); - feesByDetailId.put(detail.getDetailId(), new ArrayList<>()); - } - for (ArBillDetailFee fee : detailFeeMapper.selectByDetailIds(detailIds)) { - List fees = feesByDetailId.get(fee.getDetailId()); - if (fees != null) { - fees.add(fee); - } - } - for (ArBillDetail detail : details) { - detail.setFees(feesByDetailId.get(detail.getDetailId())); - } - } - - private String exportRemark(ArBillDetail detail) { - return StringUtils.isEmpty(detail.getRemark()) ? detail.getGoodsDescription() : detail.getRemark(); - } - - private String exportReceiveTimeRange(Map 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 BigDecimal exportUnitPrice(ArBillDetail detail) { - return detail == null ? null : detail.getFreightRate(); - } - - private BigDecimal exportProcessingFee(ArBillDetail detail) { - return detail == null ? null : detail.getRegistrationFee(); - } - - private String exportFormula(ArBillDetail detail) { - String formula = joinFeeText(detail.getFees(), true); - if (!StringUtils.isEmpty(formula)) { - return formula; - } - boolean freight = feeAmount(detail, "BASIC_FREIGHT") != null; - boolean processing = exportProcessingFee(detail) != null; - boolean surcharge = hasFeeType(detail.getFees(), "SURCHARGE"); - if (!freight) { - return ""; - } - return "结算重量*公斤价" + (processing ? "+处理费" : "") + (surcharge ? "+附加费" : ""); - } - - private String exportFeeType() { - return "运费"; - } - - private String joinFeeText(List fees, boolean formula) { - if (fees == null || fees.isEmpty()) { - return ""; - } - StringBuilder result = new StringBuilder(); - for (ArBillDetailFee fee : fees) { - String value = formula ? fee.getCalculationFormula() : (StringUtils.isEmpty(fee.getFeeName()) ? fee.getFeeType() : fee.getFeeName()); - if (StringUtils.isEmpty(value)) { - continue; - } - if (result.length() > 0) { - result.append("、"); - } - result.append(value); - } - return result.toString(); - } - - private BigDecimal feeAmount(ArBillDetail detail, String feeType) { - if (detail.getFees() == null) { - return null; - } - BigDecimal total = BigDecimal.ZERO; - boolean found = false; - for (ArBillDetailFee fee : detail.getFees()) { - if (feeType.equalsIgnoreCase(fee.getFeeType())) { - total = total.add(nvl(fee.getAmount())); - found = true; - } - } - return found ? total : null; - } - - private boolean hasFeeType(List fees, String feeType) { - if (fees == null) { - return false; - } - for (ArBillDetailFee fee : fees) { - if (feeType.equalsIgnoreCase(fee.getFeeType())) { - return true; - } - } - return false; - } - - private String exportBankAccountNo(String value) { - if (StringUtils.isEmpty(value)) { - return ""; - } - String normalized = value.replaceAll("\\s+", ""); - StringBuilder result = new StringBuilder(normalized.length() + normalized.length() / 4); - for (int index = 0; index < normalized.length(); index++) { - if (index > 0 && index % 4 == 0) { - result.append(' '); - } - result.append(normalized.charAt(index)); - } - return result.toString(); - } - private BigDecimal nvl(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; } diff --git a/bms-back/bms-system/src/main/resources/mapper/receivable/ArBillExportMapper.xml b/bms-back/bms-system/src/main/resources/mapper/receivable/ArBillExportMapper.xml index 5ad69c71..4d873a36 100644 --- a/bms-back/bms-system/src/main/resources/mapper/receivable/ArBillExportMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/receivable/ArBillExportMapper.xml @@ -63,9 +63,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" order by export_time desc limit 1 - where ar_bill_id = #{arBillId} and export_status = 'PROCESSING' + and template_id = #{templateId} order by export_id desc limit 1 diff --git a/bms-back/bms-system/src/main/resources/mapper/receivable/ArExportTemplateMapper.xml b/bms-back/bms-system/src/main/resources/mapper/receivable/ArExportTemplateMapper.xml index 9344a2ca..f038bef4 100644 --- a/bms-back/bms-system/src/main/resources/mapper/receivable/ArExportTemplateMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/receivable/ArExportTemplateMapper.xml @@ -20,7 +20,7 @@ - + + + order by is_default desc, effective_start desc, template_id desc + + + + + diff --git a/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_summary.xlsx b/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_summary.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f128fedde62059b1954f44123845024de771b465 GIT binary patch literal 14399 zcma)jb9|jk*LJMNjcwab8e5HRt3hKmwynlC8r!y=G`5{D={e6q-{*aQ-~6%fy=Ru@ znz`5PSu;yk0vH4e;JpM$Z}PoA|5G5}z8F~R%i3Do*wMQ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 literal 0 HcmV?d00001 diff --git a/bms-front/src/api/ar/bill.js b/bms-front/src/api/ar/bill.js index 6f887c4b..562912d6 100644 --- a/bms-front/src/api/ar/bill.js +++ b/bms-front/src/api/ar/bill.js @@ -88,8 +88,12 @@ export function getArBillVoidTask(taskId) { return request({ url: '/ar/bill/void/task/' + taskId, method: 'get' }) } -export function exportArBill(arBillId) { - return request({ url: '/ar/bill/' + arBillId + '/export', method: 'post' }) +export function listArBillExportTemplates(arBillId) { + return request({ url: '/ar/bill/' + arBillId + '/export-templates', method: 'get' }) +} + +export function exportArBill(arBillId, data) { + return request({ url: '/ar/bill/' + arBillId + '/export', method: 'post', data }) } export function listArBillExports(arBillId) { diff --git a/bms-front/src/views/ar/bill/components/BillDetail.vue b/bms-front/src/views/ar/bill/components/BillDetail.vue index 5c75d3ec..87ebd515 100644 --- a/bms-front/src/views/ar/bill/components/BillDetail.vue +++ b/bms-front/src/views/ar/bill/components/BillDetail.vue @@ -59,7 +59,7 @@ @size-change="handleDetailSizeChange" /> -
导出历史{{ exporting ? '生成中' : '导出账单明细' }}
+
导出历史导出账单明细
@@ -87,7 +87,6 @@ const detailPageNum = ref(1) const detailPageSize = ref(10) const detailListLoading = ref(false) let detailRequestSerial = 0 -const exporting = computed(() => props.detail?.exports?.some(item => item.exportStatus === AR_EXPORT_STATUS.PROCESSING)) // 切换账单时重置分页和请求序号,旧账单的慢响应不能覆盖新账单。 watch(() => props.detail?.arBillId, billId => { diff --git a/bms-front/src/views/ar/bill/components/ExportBillDialog.vue b/bms-front/src/views/ar/bill/components/ExportBillDialog.vue new file mode 100644 index 00000000..69a45398 --- /dev/null +++ b/bms-front/src/views/ar/bill/components/ExportBillDialog.vue @@ -0,0 +1,86 @@ + + + + + diff --git a/bms-front/src/views/ar/bill/index.vue b/bms-front/src/views/ar/bill/index.vue index 3d168ecf..c0054fde 100644 --- a/bms-front/src/views/ar/bill/index.vue +++ b/bms-front/src/views/ar/bill/index.vue @@ -60,6 +60,8 @@ + @@ -75,9 +77,10 @@