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 index ecbf1782..6e5b1c6e 100644 --- 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 @@ -6,6 +6,7 @@ import static org.mockito.Mockito.*; import java.io.IOException; import java.math.BigDecimal; +import java.math.RoundingMode; import java.nio.file.Path; import java.sql.Date; import java.util.ArrayList; @@ -60,7 +61,7 @@ class ArBillWorkbookWriterTest { assertTrue(summary.getMergedRegions().stream().anyMatch(region -> "A11:B11".equals(region.formatAsString()))); assertEquals("客户 & <测试>", freight.getRow(2).getCell(1).getStringCellValue()); - assertEquals("20261001-20261031", freight.getRow(2).getCell(17).getStringCellValue()); + assertEquals("20261001-20261031", freight.getRow(2).getCell(18).getStringCellValue()); assertEquals("0000123", freight.getRow(4).getCell(0).getStringCellValue()); assertEquals("00000001", freight.getRow(4).getCell(2).getStringCellValue()); assertEquals("001234567890123456789", freight.getRow(4).getCell(3).getStringCellValue()); @@ -68,24 +69,29 @@ class ArBillWorkbookWriterTest { 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(CellType.FORMULA, freight.getRow(4).getCell(16).getCellType()); + assertEquals("N5+K5+M5+P5+O5", freight.getRow(4).getCell(16).getCellFormula()); + assertEquals(10.12, freight.getRow(4).getCell(16).getNumericCellValue(), 0.00001); + assertEquals(-2.22, freight.getRow(5).getCell(16).getNumericCellValue(), 0.00001); + assertEquals(21, freight.getRow(4).getLastCellNum()); + assertEquals("说明", freight.getRow(3).getCell(20).getStringCellValue()); assertEquals("", freight.getRow(4).getCell(19).getStringCellValue()); - for (int column : new int[]{7, 10, 14, 16, 17}) { + assertEquals("", freight.getRow(4).getCell(20).getStringCellValue()); + for (int column : new int[]{10, 14, 15}) { + assertEquals(0.0, freight.getRow(4).getCell(column).getNumericCellValue()); + assertEquals("0.00", freight.getRow(4).getCell(column).getCellStyle().getDataFormatString()); + } + for (int column : new int[]{7, 17, 18}) { 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); + assertEquals("SUM(Q5:Q7)", freight.getRow(8).getCell(16).getCellFormula()); + assertEquals(13.20, freight.getRow(8).getCell(16).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(13.20, evaluator.evaluate(freight.getRow(8).getCell(16)).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")); + assertTrue(workbook.getPrintArea(1).contains("$U$9")); } } @@ -94,6 +100,8 @@ class ArBillWorkbookWriterTest { int count = 4001; SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); writer.detailMapper = mock(ArBillDetailMapper.class); + writer.detailFeeMapper = mock(ArBillDetailFeeMapper.class); + when(writer.detailFeeMapper.selectByDetailIds(anyList())).thenReturn(List.of()); List cursors = new ArrayList<>(); when(writer.detailMapper.selectExportPage(eq(7L), anyInt(), eq(2000))).thenAnswer(invocation -> { int previous = invocation.getArgument(1); @@ -108,8 +116,8 @@ class ArBillWorkbookWriterTest { 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("SUM(Q5:Q4005)", sheet.getRow(4006).getCell(16).getCellFormula()); + assertEquals(4001, sheet.getRow(4006).getCell(16).getNumericCellValue()); assertEquals(4001, workbook.getSheetAt(0).getRow(7).getCell(4).getNumericCellValue()); } } @@ -123,6 +131,7 @@ class ArBillWorkbookWriterTest { withoutRemark.setCurrency("USD"); withoutRemark.setBillingFailStatus(2); withoutRemark.setRemark(null); + withoutRemark.setGoodsDescription("仅供内部使用的品名描述"); ArBillDetail success = detail(3, "P1", "1.00"); success.setCurrency("USD"); success.setBillingFailStatus(0); @@ -130,21 +139,21 @@ class ArBillWorkbookWriterTest { 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}) { + for (int column : new int[]{11, 12, 13, 15, 16}) { 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++) { + for (int column = 0; column < 21; 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(4).getCell(19).getStringCellValue()); + assertEquals("销售价未匹配国家", freight.getRow(4).getCell(20).getStringCellValue()); + assertEquals("", freight.getRow(5).getCell(19).getStringCellValue()); + assertEquals("销售价未匹配国家", freight.getRow(5).getCell(20).getStringCellValue()); assertEquals("", freight.getRow(6).getCell(19).getStringCellValue()); + assertEquals("", freight.getRow(6).getCell(20).getStringCellValue()); } } @@ -173,6 +182,7 @@ class ArBillWorkbookWriterTest { XSSFSheet sheet = workbook.getSheetAt(0); assertEquals(21, sheet.getRow(4).getLastCellNum()); assertEquals(1, sheet.getRow(4).getCell(18).getNumericCellValue()); + assertEquals("备注 & <快照>", sheet.getRow(4).getCell(19).getStringCellValue()); assertEquals(0, sheet.getRow(5).getPhysicalNumberOfCells()); assertEquals("银行信息", sheet.getRow(6).getCell(1).getStringCellValue()); assertEquals("收款账户快照", sheet.getRow(7).getCell(2).getStringCellValue()); @@ -182,6 +192,8 @@ class ArBillWorkbookWriterTest { private SummaryArBillWorkbookWriter summaryWriter(List details) { SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); writer.detailMapper = mapper(details); + writer.detailFeeMapper = mock(ArBillDetailFeeMapper.class); + when(writer.detailFeeMapper.selectByDetailIds(anyList())).thenReturn(List.of()); return writer; } @@ -235,7 +247,9 @@ class ArBillWorkbookWriterTest { detail.setActualWeight(new BigDecimal("8.5")); detail.setChargeWeight(new BigDecimal("1.125")); detail.setFreightRate(new BigDecimal("2.5")); - detail.setRegistrationFee(new BigDecimal("3.25")); + // 公式导出要求费用组成与账单快照一致,保留运费样例,其余金额作为操作费。 + BigDecimal freight = detail.getChargeWeight().multiply(detail.getFreightRate()).setScale(2, RoundingMode.HALF_UP); + detail.setRegistrationFee(new BigDecimal(amount).subtract(freight)); detail.setTotalAmount(new BigDecimal(amount)); detail.setCurrency("CNY"); detail.setRemark("备注 & <快照>"); 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 index 091ed6c4..74c8afe3 100644 --- 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 @@ -7,6 +7,7 @@ import org.springframework.stereotype.Component; @Component public class ArBillWorkbookWriters { public static final String SUMMARY_TEMPLATE_CODE = "AR_BILL_SUMMARY"; + public static final String GUANGZHOU_TEMPLATE_CODE = "AR_BILL_GZ"; private final DefaultArBillWorkbookWriter defaultWriter; private final SummaryArBillWorkbookWriter summaryWriter; 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 index b0d3f916..9c323736 100644 --- 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 @@ -31,7 +31,7 @@ import com.bms.receivable.domain.ArBillDetail; import com.bms.receivable.domain.ArBillDetailFee; import com.bms.receivable.domain.ArExportTemplate; -/** 默认应收账单模板的 21 列明细及银行页脚排版。 */ +/** 默认及广州应收账单模板共用的 21 列明细和银行页脚排版。 */ @Component public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { private static final int TEMPLATE_DATA_START_ROW = 5; @@ -68,7 +68,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { 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, + private record ExportStyleIndexes(int detail, int failedDetail, int detailNo, int failedDetailNo, int customerOrderNo, int failedCustomerOrderNo, int trackingNo, int failedTrackingNo, int generalNumber, int failedGeneralNumber, @@ -79,18 +79,24 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException { // 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。 StylesTable styles = readExportStyles(template); + boolean guangzhouTemplate = ArBillWorkbookWriters.GUANGZHOU_TEMPLATE_CODE.equals(template.getTemplateCode()); + // 广州模板的样式编号与默认模板不同,使用其明细合计单元格的完整边框样式。 + int detailStyleIndex = guangzhouTemplate ? readGuangzhouDetailStyleIndex(template) : TEMPLATE_DETAIL_STYLE_INDEX; + if (detailStyleIndex >= styles.getNumCellStyles()) { + throw new IOException("应收账单导出模板明细样式不存在: " + detailStyleIndex); + } String drawingPartPath = readTemplateDrawingPartPath(template); XSSFCellStyle detailNoStyle = styles.createCellStyle(); - detailNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + detailNoStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); detailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); int detailNoStyleIndex = Short.toUnsignedInt(detailNoStyle.getIndex()); XSSFCellStyle failedDetailStyle = styles.createCellStyle(); - failedDetailStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + failedDetailStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); 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.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); customerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); int customerOrderNoStyleIndex = Short.toUnsignedInt(customerOrderNoStyle.getIndex()); XSSFCellStyle failedCustomerOrderNoStyle = styles.createCellStyle(); @@ -98,7 +104,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { failedCustomerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); int failedCustomerOrderNoStyleIndex = Short.toUnsignedInt(failedCustomerOrderNoStyle.getIndex()); XSSFCellStyle trackingNoStyle = styles.createCellStyle(); - trackingNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + trackingNoStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); trackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); int trackingNoStyleIndex = Short.toUnsignedInt(trackingNoStyle.getIndex()); XSSFCellStyle failedTrackingNoStyle = styles.createCellStyle(); @@ -106,7 +112,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { failedTrackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); int failedTrackingNoStyleIndex = Short.toUnsignedInt(failedTrackingNoStyle.getIndex()); XSSFCellStyle generalNumberStyle = styles.createCellStyle(); - generalNumberStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + generalNumberStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); generalNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); int generalNumberStyleIndex = Short.toUnsignedInt(generalNumberStyle.getIndex()); XSSFCellStyle failedGeneralNumberStyle = styles.createCellStyle(); @@ -118,7 +124,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { failedDetailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); int failedDetailNoStyleIndex = Short.toUnsignedInt(failedDetailNoStyle.getIndex()); XSSFCellStyle formulaStyle = styles.createCellStyle(); - formulaStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); + formulaStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex)); formulaStyle.setShrinkToFit(true); int formulaStyleIndex = Short.toUnsignedInt(formulaStyle.getIndex()); XSSFCellStyle failedFormulaStyle = styles.createCellStyle(); @@ -126,7 +132,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { failedFormulaStyle.setShrinkToFit(true); int failedFormulaStyleIndex = Short.toUnsignedInt(failedFormulaStyle.getIndex()); ExportStyleIndexes exportStyleIndexes = new ExportStyleIndexes( - failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex, + detailStyleIndex, failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex, customerOrderNoStyleIndex, failedCustomerOrderNoStyleIndex, trackingNoStyleIndex, failedTrackingNoStyleIndex, generalNumberStyleIndex, failedGeneralNumberStyleIndex, @@ -151,7 +157,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { } if (TEMPLATE_SHEET_XML.equals(entry.getName())) { output.putNextEntry(new ZipEntry(entryName)); - int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes); + int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes, guangzhouTemplate); output.closeEntry(); replaced = true; drawingRowOffset = Integer.valueOf(rowOffset); @@ -178,6 +184,29 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { } } + private int readGuangzhouDetailStyleIndex(ArExportTemplate template) throws IOException { + try (InputStream input = openTemplateStream(template); ZipInputStream zip = new ZipInputStream(input)) { + for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) { + if (TEMPLATE_SHEET_XML.equals(entry.getName())) { + String row = extractTemplateRows(readUtf8(zip)).get(6); + if (row != null) { + Matcher cells = CELL_PATTERN.matcher(row); + while (cells.find()) { + Matcher reference = CELL_REF_PATTERN.matcher(cells.group(1)); + Matcher style = CELL_STYLE_PATTERN.matcher(cells.group(1)); + if (reference.find() && "S6".equalsIgnoreCase(reference.group(1)) && style.find()) { + return Integer.parseInt(style.group(1)); + } + } + } + throw new IOException("广州应收账单模板缺少 S6 合计单元格样式"); + } + zip.closeEntry(); + } + } + throw new IOException("广州应收账单模板缺少运费工作表"); + } + private String readTemplateDrawingPartPath(ArExportTemplate template) throws IOException { try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { @@ -236,11 +265,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { 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; + return new StylesTable(templateZip); } templateZip.closeEntry(); } @@ -249,7 +274,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { } private int writeOoxmlSheet(String templateXml, ArBill bill, OutputStream output, - ExportStyleIndexes styleIndexes) throws IOException { + ExportStyleIndexes styleIndexes, boolean guangzhouTemplate) throws IOException { int sheetDataStart = templateXml.indexOf("', sheetDataStart); int sheetDataEnd = templateXml.indexOf("", sheetDataOpenEnd); @@ -263,7 +288,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { removeSheetDimension(templateXml.substring(0, sheetDataOpenEnd + 1))); writeUtf8(output, prefix); - String headerRow = replaceCellXml(templateRows.get(1), "A1", + String headerRow = guangzhouTemplate ? templateRows.get(1) : replaceCellXml(templateRows.get(1), "A1", StringUtils.isEmpty(bill.getBankAccountName()) ? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName(), false); writeUtf8(output, headerRow); writeUtf8(output, templateRows.get(2)); @@ -291,7 +316,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW + EXPORT_FOOTER_GAP_ROWS; writeUtf8(output, ""); - writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber()); + writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber(), guangzhouTemplate); String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset); writeUtf8(output, suffix); return rowOffset; @@ -394,7 +419,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { } private void writeOoxmlFooter(OutputStream output, Map templateRows, int rowOffset, - ArBill bill, int generalNumberStyleIndex) throws IOException { + ArBill bill, int generalNumberStyleIndex, boolean guangzhouTemplate) 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; @@ -407,20 +432,26 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { nvl(bill.getTotalAmount()), generalNumberStyleIndex); } else if (offset == 1) { row = replaceCellXml(row, "B" + targetRowNumber, "开户名", false); - row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankAccountName(), false); + if (!guangzhouTemplate) { + 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); + if (!guangzhouTemplate) { + 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); + if (!guangzhouTemplate) { + row = replaceCellXml(row, "C" + targetRowNumber, bill.getBankName(), false); + } } writeUtf8(output, row); } @@ -430,7 +461,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { ExportStyleIndexes styleIndexes) throws IOException { String failureDescription = exportBillingFailDescription(detail.getBillingFailStatus()); boolean failedDetail = !failureDescription.isEmpty(); - int styleIndex = failedDetail ? styleIndexes.failedDetail() : TEMPLATE_DETAIL_STYLE_INDEX; + int styleIndex = failedDetail ? styleIndexes.failedDetail() : styleIndexes.detail(); int sequenceStyleIndex = failedDetail ? styleIndexes.failedDetailNo() : styleIndexes.detailNo(); Object[] values = { detail.getDetailNo(), 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 index 32dfdc72..7f2c116d 100644 --- 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 @@ -23,6 +23,7 @@ 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.ArBillDetailFee; import com.bms.receivable.domain.ArExportTemplate; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.FillPatternType; @@ -39,9 +40,13 @@ import org.springframework.stereotype.Component; @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 DETAIL_COLUMN_COUNT = 21; private static final int SUMMARY_START_ROW = 4; private static final String SUMMARY_REMARK = "国际货物运输代理服务费"; + private static final String REMOTE_FEE_TYPE = "REMOTE"; + private static final String SURCHARGE_FEE_TYPE = "SURCHARGE"; + private static final String ROMANIA_FEE_TYPE = "REGISTRATION"; + private static final String ROMANIA_FEE_NAME = "罗马尼亚费用"; private static final Pattern MERGE = Pattern.compile("(]*\\bref=\")([A-Z]+)(\\d+):([A-Z]+)(\\d+)(\")"); private static final Pattern FILTER = Pattern.compile("(]*\\bref=\")[^\"]*(\")"); @@ -110,9 +115,15 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { 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 列说明,请使用最新模板"); + requireDetailHeader(workbook.getSheetAt(1), 14, "附加费"); + requireDetailHeader(workbook.getSheetAt(1), 19, "备注"); + requireDetailHeader(workbook.getSheetAt(1), 20, "说明"); + } + + private void requireDetailHeader(XSSFSheet sheet, int column, String label) throws IOException { + XSSFCell header = requireRow(sheet, 3).getCell(column); + if (header == null || !label.equals(header.toString().trim())) { + throw new IOException("汇总模板运费明细缺少 " + (char) ('A' + column) + " 列" + label + ",请使用最新模板"); } } @@ -135,33 +146,28 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { textCell(summary, 11, 1, exportBankAccountNo(bill.getBankAccountNo())); textCell(summary, 12, 1, bill.getBankName()); textCell(detail, 2, 1, bill.getCustomerName()); - textCell(detail, 2, 17, billPeriod(bill)); - for (int column : new int[]{11, 12, 13, 14, 15}) { + textCell(detail, 2, 18, billPeriod(bill)); + for (int column : new int[]{11, 12, 13, 15, 16}) { 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); + boolean identifier = column == 0 || column == 2 || column == 3 || column == 6; + boolean money = column == 10 || column == 13 || column == 14 || column == 15 || column == 16; + if (!identifier && !money) continue; 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"); + String format = identifier ? "@" : "0.00"; 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)); + XSSFCell summaryAmount = requireRow(summary, 3).getCell(4, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK); + XSSFCellStyle summaryAmountStyle = workbook.createCellStyle(); + summaryAmountStyle.cloneStyleFrom(summaryAmount.getCellStyle()); + summaryAmountStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00")); + summaryAmount.setCellStyle(summaryAmountStyle); + // 行高、列宽、字体和配色沿用用户模板。 workbook.setForceFormulaRecalculation(true); } @@ -184,7 +190,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { style.setFillPattern(FillPatternType.SOLID_FOREGROUND); failed[column] = Short.toUnsignedInt(style.getIndex()); } - return new DetailStyles(normal, failed); + return new DetailStyles(normal, failed, workbook.getSheetAt(1).getRow(4).getHeightInPoints()); } private DetailResult writeDetails(SheetXml sheet, ArBill bill, OutputStream output, @@ -197,6 +203,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { while (true) { List details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE); if (details.isEmpty()) break; + attachFees(details); for (ArBillDetail detail : details) { if (rowNumber + 2 > SpreadsheetVersion.EXCEL2007.getMaxRows()) { throw new IOException("账单订单数超过 Excel 单个工作表容量,请拆分账单后导出"); @@ -204,8 +211,9 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { 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()); + DetailAmounts amounts = calculateDetailAmounts(detail); + writeUtf8(output, detailRow(rowNumber++, bill, detail, amounts, styles)); + BigDecimal amount = amounts.total(); total = total.add(amount); String key = StringUtils.isEmpty(detail.getProductCode()) ? "NAME:" + detail.getProductName() : "CODE:" + detail.getProductCode(); @@ -220,13 +228,14 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { 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); + footer = replaceFormulaCellXml(footer, "Q" + (lastRow + 2), "SUM(Q5:Q" + lastRow + ")", total); writeUtf8(output, footer); - writeUtf8(output, withFilter(sheet.suffix(), "A4:T" + lastRow)); + writeUtf8(output, withFilter(sheet.suffix(), "A4:U" + lastRow)); return new DetailResult(count, lastRow, total); } - private String detailRow(int rowNumber, ArBill bill, ArBillDetail detail, DetailStyles styles) { + private String detailRow(int rowNumber, ArBill bill, ArBillDetail detail, + DetailAmounts amounts, DetailStyles styles) { String failure = exportBillingFailDescription(detail.getBillingFailStatus()); Object[] values = { bill.getCustomerCode(), @@ -234,21 +243,27 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { 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 + detail.getDestPostcode(), null, detail.getReceiveWeight(), nvl(detail.getChargeWeight()), + amounts.remote(), nvl(exportUnitPrice(detail)), amounts.processing(), amounts.freight(), + amounts.surcharge(), amounts.romania(), amounts.total(), null, null, + null, failure // 客户版汇总模板的 T 列备注固定留空,不输出内部备注或品名描述。 }; StringBuilder row = new StringBuilder(2048).append(""); + .append("\" ht=\"").append(numberText(styles.rowHeight())) + .append("\" customHeight=\"true\" spans=\"1:").append(DETAIL_COLUMN_COUNT).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); + String formula = switch (index) { + case 13 -> "ROUND(J" + rowNumber + "*L" + rowNumber + ",2)"; + case 16 -> "N" + rowNumber + "+K" + rowNumber + "+M" + rowNumber + + "+P" + rowNumber + "+O" + rowNumber; + default -> null; + }; + if (formula != null) { row.append("ROUND(J").append(rowNumber).append("*L").append(rowNumber) - .append(",2)").append(numberText(amount)).append(""); + .append("\" t=\"n\">").append(xmlEscape(formula)).append("") + .append(numberText((Number) values[index])).append(""); } else { appendOoxmlCell(row, reference, values[index], style); } @@ -256,6 +271,39 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { return row.append("").toString(); } + /** 与工作表 N、Q 列的公式使用相同数值,缓存和产品汇总均复用本次计算结果。 */ + private DetailAmounts calculateDetailAmounts(ArBillDetail detail) throws IOException { + BigDecimal freight = nvl(detail.getChargeWeight()).multiply(nvl(exportUnitPrice(detail))) + .setScale(2, RoundingMode.HALF_UP); + BigDecimal processing = nvl(exportProcessingFee(detail)); + BigDecimal remote = exportFeeAmount(detail, REMOTE_FEE_TYPE, null); + BigDecimal surcharge = exportFeeAmount(detail, SURCHARGE_FEE_TYPE, null); + BigDecimal romania = exportFeeAmount(detail, ROMANIA_FEE_TYPE, ROMANIA_FEE_NAME); + BigDecimal total = freight.add(remote).add(processing).add(romania).add(surcharge); + BigDecimal snapshot = nvl(detail.getTotalAmount()); + if (total.compareTo(snapshot) != 0) { + String order = StringUtils.isEmpty(detail.getOrderNo()) ? detail.getTransferNo() : detail.getOrderNo(); + if (StringUtils.isEmpty(order)) order = "明细" + detail.getDetailNo(); + throw new IOException("订单 " + order + " 总金额与账单快照不一致:公式金额 " + numberText(total) + + ",账单金额 " + numberText(snapshot) + ",差额 " + numberText(total.subtract(snapshot)) + + ",请检查其他费用、退费或计费快照"); + } + return new DetailAmounts(freight, processing, remote, surcharge, romania, total); + } + + /** 从当前账单的费用快照汇总应收金额;无匹配项输出零,负金额照常输出。 */ + private BigDecimal exportFeeAmount(ArBillDetail detail, String feeType, String feeName) { + if (detail.getFees() == null) return BigDecimal.ZERO; + BigDecimal amount = BigDecimal.ZERO; + for (ArBillDetailFee fee : detail.getFees()) { + if (fee == null || !feeType.equalsIgnoreCase(StringUtils.trim(fee.getFeeType()))) continue; + // REGISTRATION 也用于其他处理费,罗马尼亚费用必须同时精确匹配名称。 + if (feeName != null && !feeName.equals(StringUtils.trim(fee.getFeeName()))) continue; + amount = amount.add(nvl(fee.getAmount())); + } + return amount; + } + private void writeSummary(SheetXml sheet, ArBill bill, Map groups, BigDecimal total, OutputStream output) throws IOException { writeUtf8(output, sheet.prefix()); @@ -342,7 +390,9 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { 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 record DetailStyles(int[] normal, int[] failed, float rowHeight) { } + private record DetailAmounts(BigDecimal freight, BigDecimal processing, BigDecimal remote, + BigDecimal surcharge, BigDecimal romania, BigDecimal total) { } private static class ProductSummary { private final String name; diff --git a/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_gz.xlsx b/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_gz.xlsx new file mode 100644 index 00000000..415b0f68 Binary files /dev/null and b/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_gz.xlsx differ 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 index f128fedd..01330f24 100644 Binary files a/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_summary.xlsx and b/bms-back/bms-system/src/main/resources/templates/receivable/ar_bill_template_summary.xlsx differ diff --git a/bms-back/sql/20261119_ar_bill_guangzhou_template.sql b/bms-back/sql/20261119_ar_bill_guangzhou_template.sql new file mode 100644 index 00000000..6a9ccaeb --- /dev/null +++ b/bms-back/sql/20261119_ar_bill_guangzhou_template.sql @@ -0,0 +1,20 @@ +-- 广州分公司应收账单模板:适用于已存在 ar_export_template 表的数据库。 +-- 执行一次;若相同业务类型、模板编码和版本已存在,唯一索引会报错,不覆盖现有配置。 +INSERT INTO `ar_export_template` ( + `template_code`, `template_name`, `business_type`, `template_version`, + `storage_type`, `storage_key`, `file_hash`, `status`, `is_default`, + `effective_start`, `effective_end`, `remark`, `create_by`, `create_time` +) VALUES ( + 'AR_BILL_GZ', '应收账单广州模板', 'AR_BILL', '1.0', + 'CLASSPATH', 'templates/receivable/ar_bill_template_gz.xlsx', NULL, 'ENABLED', '0', + NULL, NULL, '广州分公司应收账单导出模板', SUBSTRING_INDEX(CURRENT_USER(), '@', 1), NOW() +); + +-- 核对新增记录,正常应返回一条。 +SELECT `template_id`, `template_code`, `template_name`, `business_type`, + `template_version`, `storage_type`, `storage_key`, `status`, `is_default`, + `effective_start`, `effective_end` +FROM `ar_export_template` +WHERE `business_type` = 'AR_BILL' + AND `template_code` = 'AR_BILL_GZ' + AND `template_version` = '1.0';