Merge remote-tracking branch 'origin/test' into test

This commit is contained in:
liuminghui
2026-11-19 18:30:58 +08:00
7 changed files with 198 additions and 82 deletions
@@ -6,6 +6,7 @@ import static org.mockito.Mockito.*;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Path; import java.nio.file.Path;
import java.sql.Date; import java.sql.Date;
import java.util.ArrayList; import java.util.ArrayList;
@@ -60,7 +61,7 @@ class ArBillWorkbookWriterTest {
assertTrue(summary.getMergedRegions().stream().anyMatch(region -> "A11:B11".equals(region.formatAsString()))); assertTrue(summary.getMergedRegions().stream().anyMatch(region -> "A11:B11".equals(region.formatAsString())));
assertEquals("客户 & <测试>", freight.getRow(2).getCell(1).getStringCellValue()); 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("0000123", freight.getRow(4).getCell(0).getStringCellValue());
assertEquals("00000001", freight.getRow(4).getCell(2).getStringCellValue()); assertEquals("00000001", freight.getRow(4).getCell(2).getStringCellValue());
assertEquals("001234567890123456789", freight.getRow(4).getCell(3).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(9.5, freight.getRow(4).getCell(8).getNumericCellValue());
assertEquals("ROUND(J5*L5,2)", freight.getRow(4).getCell(13).getCellFormula()); assertEquals("ROUND(J5*L5,2)", freight.getRow(4).getCell(13).getCellFormula());
assertEquals(2.81, freight.getRow(4).getCell(13).getNumericCellValue(), 0.00001); assertEquals(2.81, freight.getRow(4).getCell(13).getNumericCellValue(), 0.00001);
assertEquals(CellType.NUMERIC, freight.getRow(4).getCell(15).getCellType()); assertEquals(CellType.FORMULA, freight.getRow(4).getCell(16).getCellType());
assertEquals(10.12, freight.getRow(4).getCell(15).getNumericCellValue(), 0.00001); assertEquals("N5+K5+M5+P5+O5", freight.getRow(4).getCell(16).getCellFormula());
assertEquals(-2.22, freight.getRow(5).getCell(15).getNumericCellValue(), 0.00001); assertEquals(10.12, freight.getRow(4).getCell(16).getNumericCellValue(), 0.00001);
assertEquals(20, freight.getRow(4).getLastCellNum()); assertEquals(-2.22, freight.getRow(5).getCell(16).getNumericCellValue(), 0.00001);
assertEquals("说明", freight.getRow(3).getCell(19).getStringCellValue()); assertEquals(21, freight.getRow(4).getLastCellNum());
assertEquals("备注 & <快照>", freight.getRow(4).getCell(18).getStringCellValue()); assertEquals("说明", freight.getRow(3).getCell(20).getStringCellValue());
assertEquals("", freight.getRow(4).getCell(19).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("", freight.getRow(4).getCell(column).getStringCellValue());
} }
assertEquals("SUM(P5:P7)", freight.getRow(8).getCell(15).getCellFormula()); assertEquals("SUM(Q5:Q7)", freight.getRow(8).getCell(16).getCellFormula());
assertEquals(13.20, freight.getRow(8).getCell(15).getNumericCellValue(), 0.00001); assertEquals(13.20, freight.getRow(8).getCell(16).getNumericCellValue(), 0.00001);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
assertEquals(13.20, evaluator.evaluate(summary.getRow(6).getCell(4)).getNumberValue(), 0.00001); 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); assertEquals(2.81, evaluator.evaluate(freight.getRow(4).getCell(13)).getNumberValue(), 0.00001);
assertFalse(workbook.getPrintArea(0).contains("#REF!")); 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; int count = 4001;
SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter();
writer.detailMapper = mock(ArBillDetailMapper.class); writer.detailMapper = mock(ArBillDetailMapper.class);
writer.detailFeeMapper = mock(ArBillDetailFeeMapper.class);
when(writer.detailFeeMapper.selectByDetailIds(anyList())).thenReturn(List.of());
List<Integer> cursors = new ArrayList<>(); List<Integer> cursors = new ArrayList<>();
when(writer.detailMapper.selectExportPage(eq(7L), anyInt(), eq(2000))).thenAnswer(invocation -> { when(writer.detailMapper.selectExportPage(eq(7L), anyInt(), eq(2000))).thenAnswer(invocation -> {
int previous = invocation.getArgument(1); int previous = invocation.getArgument(1);
@@ -108,8 +116,8 @@ class ArBillWorkbookWriterTest {
assertEquals(2, workbook.getNumberOfSheets()); assertEquals(2, workbook.getNumberOfSheets());
XSSFSheet sheet = workbook.getSheetAt(1); XSSFSheet sheet = workbook.getSheetAt(1);
assertEquals("ROUND(J4005*L4005,2)", sheet.getRow(4004).getCell(13).getCellFormula()); assertEquals("ROUND(J4005*L4005,2)", sheet.getRow(4004).getCell(13).getCellFormula());
assertEquals("SUM(P5:P4005)", sheet.getRow(4006).getCell(15).getCellFormula()); assertEquals("SUM(Q5:Q4005)", sheet.getRow(4006).getCell(16).getCellFormula());
assertEquals(4001, sheet.getRow(4006).getCell(15).getNumericCellValue()); assertEquals(4001, sheet.getRow(4006).getCell(16).getNumericCellValue());
assertEquals(4001, workbook.getSheetAt(0).getRow(7).getCell(4).getNumericCellValue()); assertEquals(4001, workbook.getSheetAt(0).getRow(7).getCell(4).getNumericCellValue());
} }
} }
@@ -123,6 +131,7 @@ class ArBillWorkbookWriterTest {
withoutRemark.setCurrency("USD"); withoutRemark.setCurrency("USD");
withoutRemark.setBillingFailStatus(2); withoutRemark.setBillingFailStatus(2);
withoutRemark.setRemark(null); withoutRemark.setRemark(null);
withoutRemark.setGoodsDescription("仅供内部使用的品名描述");
ArBillDetail success = detail(3, "P1", "1.00"); ArBillDetail success = detail(3, "P1", "1.00");
success.setCurrency("USD"); success.setCurrency("USD");
success.setBillingFailStatus(0); success.setBillingFailStatus(0);
@@ -130,21 +139,21 @@ class ArBillWorkbookWriterTest {
summaryWriter(List.of(detail, withoutRemark, success)).write(bill(3, "3.00", "USD"), summaryTemplate(), target); summaryWriter(List.of(detail, withoutRemark, success)).write(bill(3, "3.00", "USD"), summaryTemplate(), target);
try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) { try (XSSFWorkbook workbook = new XSSFWorkbook(target.toFile())) {
XSSFSheet freight = workbook.getSheetAt(1); 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(); String title = freight.getRow(3).getCell(column).getStringCellValue();
assertTrue(title.contains("USD")); assertTrue(title.contains("USD"));
assertFalse(title.contains("CNY")); assertFalse(title.contains("CNY"));
} }
assertEquals("USD", workbook.getSheetAt(0).getRow(5).getCell(5).getStringCellValue()); 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(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(4).getCell(19).getStringCellValue()); assertEquals("销售价未匹配国家", freight.getRow(4).getCell(20).getStringCellValue());
assertEquals("", freight.getRow(5).getCell(18).getStringCellValue()); assertEquals("", freight.getRow(5).getCell(19).getStringCellValue());
assertEquals("销售价未匹配国家", freight.getRow(5).getCell(19).getStringCellValue()); assertEquals("销售价未匹配国家", freight.getRow(5).getCell(20).getStringCellValue());
assertEquals("备注 & <快照>", freight.getRow(6).getCell(18).getStringCellValue());
assertEquals("", freight.getRow(6).getCell(19).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); XSSFSheet sheet = workbook.getSheetAt(0);
assertEquals(21, sheet.getRow(4).getLastCellNum()); assertEquals(21, sheet.getRow(4).getLastCellNum());
assertEquals(1, sheet.getRow(4).getCell(18).getNumericCellValue()); assertEquals(1, sheet.getRow(4).getCell(18).getNumericCellValue());
assertEquals("备注 & <快照>", sheet.getRow(4).getCell(19).getStringCellValue());
assertEquals(0, sheet.getRow(5).getPhysicalNumberOfCells()); assertEquals(0, sheet.getRow(5).getPhysicalNumberOfCells());
assertEquals("银行信息", sheet.getRow(6).getCell(1).getStringCellValue()); assertEquals("银行信息", sheet.getRow(6).getCell(1).getStringCellValue());
assertEquals("收款账户快照", sheet.getRow(7).getCell(2).getStringCellValue()); assertEquals("收款账户快照", sheet.getRow(7).getCell(2).getStringCellValue());
@@ -182,6 +192,8 @@ class ArBillWorkbookWriterTest {
private SummaryArBillWorkbookWriter summaryWriter(List<ArBillDetail> details) { private SummaryArBillWorkbookWriter summaryWriter(List<ArBillDetail> details) {
SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter(); SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter();
writer.detailMapper = mapper(details); writer.detailMapper = mapper(details);
writer.detailFeeMapper = mock(ArBillDetailFeeMapper.class);
when(writer.detailFeeMapper.selectByDetailIds(anyList())).thenReturn(List.of());
return writer; return writer;
} }
@@ -235,7 +247,9 @@ class ArBillWorkbookWriterTest {
detail.setActualWeight(new BigDecimal("8.5")); detail.setActualWeight(new BigDecimal("8.5"));
detail.setChargeWeight(new BigDecimal("1.125")); detail.setChargeWeight(new BigDecimal("1.125"));
detail.setFreightRate(new BigDecimal("2.5")); 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.setTotalAmount(new BigDecimal(amount));
detail.setCurrency("CNY"); detail.setCurrency("CNY");
detail.setRemark("备注 & <快照>"); detail.setRemark("备注 & <快照>");
@@ -7,6 +7,7 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ArBillWorkbookWriters { public class ArBillWorkbookWriters {
public static final String SUMMARY_TEMPLATE_CODE = "AR_BILL_SUMMARY"; 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 DefaultArBillWorkbookWriter defaultWriter;
private final SummaryArBillWorkbookWriter summaryWriter; private final SummaryArBillWorkbookWriter summaryWriter;
@@ -31,7 +31,7 @@ import com.bms.receivable.domain.ArBillDetail;
import com.bms.receivable.domain.ArBillDetailFee; import com.bms.receivable.domain.ArBillDetailFee;
import com.bms.receivable.domain.ArExportTemplate; import com.bms.receivable.domain.ArExportTemplate;
/** 默认应收账单模板的 21 列明细及银行页脚排版。 */ /** 默认及广州应收账单模板共用的 21 列明细和银行页脚排版。 */
@Component @Component
public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport { public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
private static final int TEMPLATE_DATA_START_ROW = 5; 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( private static final Pattern MERGE_REF_PATTERN = Pattern.compile(
"(<mergeCell\\b[^>]*\\bref=\")([A-Z]+)(\\d+)(?::([A-Z]+)(\\d+))?(\")"); "(<mergeCell\\b[^>]*\\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 customerOrderNo, int failedCustomerOrderNo,
int trackingNo, int failedTrackingNo, int trackingNo, int failedTrackingNo,
int generalNumber, int failedGeneralNumber, int generalNumber, int failedGeneralNumber,
@@ -79,18 +79,24 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException { public void write(ArBill bill, ArExportTemplate template, Path target) throws IOException {
// 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。 // 样式表单独读取;不加载整张工作簿,且不依赖 styles.xml 和 sheet1.xml 在 ZIP 中的先后顺序。
StylesTable styles = readExportStyles(template); 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); String drawingPartPath = readTemplateDrawingPartPath(template);
XSSFCellStyle detailNoStyle = styles.createCellStyle(); XSSFCellStyle detailNoStyle = styles.createCellStyle();
detailNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); detailNoStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
detailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); detailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0"));
int detailNoStyleIndex = Short.toUnsignedInt(detailNoStyle.getIndex()); int detailNoStyleIndex = Short.toUnsignedInt(detailNoStyle.getIndex());
XSSFCellStyle failedDetailStyle = styles.createCellStyle(); XSSFCellStyle failedDetailStyle = styles.createCellStyle();
failedDetailStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); failedDetailStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
failedDetailStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); failedDetailStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
failedDetailStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); failedDetailStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
int failedDetailStyleIndex = Short.toUnsignedInt(failedDetailStyle.getIndex()); int failedDetailStyleIndex = Short.toUnsignedInt(failedDetailStyle.getIndex());
XSSFCellStyle customerOrderNoStyle = styles.createCellStyle(); XSSFCellStyle customerOrderNoStyle = styles.createCellStyle();
customerOrderNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); customerOrderNoStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
customerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); customerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@"));
int customerOrderNoStyleIndex = Short.toUnsignedInt(customerOrderNoStyle.getIndex()); int customerOrderNoStyleIndex = Short.toUnsignedInt(customerOrderNoStyle.getIndex());
XSSFCellStyle failedCustomerOrderNoStyle = styles.createCellStyle(); XSSFCellStyle failedCustomerOrderNoStyle = styles.createCellStyle();
@@ -98,7 +104,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
failedCustomerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); failedCustomerOrderNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@"));
int failedCustomerOrderNoStyleIndex = Short.toUnsignedInt(failedCustomerOrderNoStyle.getIndex()); int failedCustomerOrderNoStyleIndex = Short.toUnsignedInt(failedCustomerOrderNoStyle.getIndex());
XSSFCellStyle trackingNoStyle = styles.createCellStyle(); XSSFCellStyle trackingNoStyle = styles.createCellStyle();
trackingNoStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); trackingNoStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
trackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); trackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@"));
int trackingNoStyleIndex = Short.toUnsignedInt(trackingNoStyle.getIndex()); int trackingNoStyleIndex = Short.toUnsignedInt(trackingNoStyle.getIndex());
XSSFCellStyle failedTrackingNoStyle = styles.createCellStyle(); XSSFCellStyle failedTrackingNoStyle = styles.createCellStyle();
@@ -106,7 +112,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
failedTrackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@")); failedTrackingNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("@"));
int failedTrackingNoStyleIndex = Short.toUnsignedInt(failedTrackingNoStyle.getIndex()); int failedTrackingNoStyleIndex = Short.toUnsignedInt(failedTrackingNoStyle.getIndex());
XSSFCellStyle generalNumberStyle = styles.createCellStyle(); XSSFCellStyle generalNumberStyle = styles.createCellStyle();
generalNumberStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); generalNumberStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
generalNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General")); generalNumberStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("General"));
int generalNumberStyleIndex = Short.toUnsignedInt(generalNumberStyle.getIndex()); int generalNumberStyleIndex = Short.toUnsignedInt(generalNumberStyle.getIndex());
XSSFCellStyle failedGeneralNumberStyle = styles.createCellStyle(); XSSFCellStyle failedGeneralNumberStyle = styles.createCellStyle();
@@ -118,7 +124,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
failedDetailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0")); failedDetailNoStyle.setDataFormat(BuiltinFormats.getBuiltinFormat("0"));
int failedDetailNoStyleIndex = Short.toUnsignedInt(failedDetailNoStyle.getIndex()); int failedDetailNoStyleIndex = Short.toUnsignedInt(failedDetailNoStyle.getIndex());
XSSFCellStyle formulaStyle = styles.createCellStyle(); XSSFCellStyle formulaStyle = styles.createCellStyle();
formulaStyle.cloneStyleFrom(styles.getStyleAt(TEMPLATE_DETAIL_STYLE_INDEX)); formulaStyle.cloneStyleFrom(styles.getStyleAt(detailStyleIndex));
formulaStyle.setShrinkToFit(true); formulaStyle.setShrinkToFit(true);
int formulaStyleIndex = Short.toUnsignedInt(formulaStyle.getIndex()); int formulaStyleIndex = Short.toUnsignedInt(formulaStyle.getIndex());
XSSFCellStyle failedFormulaStyle = styles.createCellStyle(); XSSFCellStyle failedFormulaStyle = styles.createCellStyle();
@@ -126,7 +132,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
failedFormulaStyle.setShrinkToFit(true); failedFormulaStyle.setShrinkToFit(true);
int failedFormulaStyleIndex = Short.toUnsignedInt(failedFormulaStyle.getIndex()); int failedFormulaStyleIndex = Short.toUnsignedInt(failedFormulaStyle.getIndex());
ExportStyleIndexes exportStyleIndexes = new ExportStyleIndexes( ExportStyleIndexes exportStyleIndexes = new ExportStyleIndexes(
failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex, detailStyleIndex, failedDetailStyleIndex, detailNoStyleIndex, failedDetailNoStyleIndex,
customerOrderNoStyleIndex, failedCustomerOrderNoStyleIndex, customerOrderNoStyleIndex, failedCustomerOrderNoStyleIndex,
trackingNoStyleIndex, failedTrackingNoStyleIndex, trackingNoStyleIndex, failedTrackingNoStyleIndex,
generalNumberStyleIndex, failedGeneralNumberStyleIndex, generalNumberStyleIndex, failedGeneralNumberStyleIndex,
@@ -151,7 +157,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
} }
if (TEMPLATE_SHEET_XML.equals(entry.getName())) { if (TEMPLATE_SHEET_XML.equals(entry.getName())) {
output.putNextEntry(new ZipEntry(entryName)); output.putNextEntry(new ZipEntry(entryName));
int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes); int rowOffset = writeOoxmlSheet(readUtf8(templateZip), bill, output, exportStyleIndexes, guangzhouTemplate);
output.closeEntry(); output.closeEntry();
replaced = true; replaced = true;
drawingRowOffset = Integer.valueOf(rowOffset); 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 { private String readTemplateDrawingPartPath(ArExportTemplate template) throws IOException {
try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) { try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) {
for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { 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)) { try (InputStream input = openTemplateStream(template); ZipInputStream templateZip = new ZipInputStream(input)) {
for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) { for (ZipEntry entry; (entry = templateZip.getNextEntry()) != null; ) {
if (TEMPLATE_STYLES_XML.equals(entry.getName())) { if (TEMPLATE_STYLES_XML.equals(entry.getName())) {
StylesTable styles = new StylesTable(templateZip); return new StylesTable(templateZip);
if (styles.getNumCellStyles() <= TEMPLATE_DETAIL_STYLE_INDEX) {
throw new IOException("应收账单导出模板缺少明细样式: " + TEMPLATE_DETAIL_STYLE_INDEX);
}
return styles;
} }
templateZip.closeEntry(); templateZip.closeEntry();
} }
@@ -249,7 +274,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
} }
private int writeOoxmlSheet(String templateXml, ArBill bill, OutputStream output, private int writeOoxmlSheet(String templateXml, ArBill bill, OutputStream output,
ExportStyleIndexes styleIndexes) throws IOException { ExportStyleIndexes styleIndexes, boolean guangzhouTemplate) throws IOException {
int sheetDataStart = templateXml.indexOf("<sheetData"); int sheetDataStart = templateXml.indexOf("<sheetData");
int sheetDataOpenEnd = templateXml.indexOf('>', sheetDataStart); int sheetDataOpenEnd = templateXml.indexOf('>', sheetDataStart);
int sheetDataEnd = templateXml.indexOf("</sheetData>", sheetDataOpenEnd); int sheetDataEnd = templateXml.indexOf("</sheetData>", sheetDataOpenEnd);
@@ -263,7 +288,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
removeSheetDimension(templateXml.substring(0, sheetDataOpenEnd + 1))); removeSheetDimension(templateXml.substring(0, sheetDataOpenEnd + 1)));
writeUtf8(output, prefix); 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); StringUtils.isEmpty(bill.getBankAccountName()) ? "威狮国际供应链(深圳)有限公司" : bill.getBankAccountName(), false);
writeUtf8(output, headerRow); writeUtf8(output, headerRow);
writeUtf8(output, templateRows.get(2)); 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; int rowOffset = lastDetailRow - TEMPLATE_LAST_DETAIL_ROW + EXPORT_FOOTER_GAP_ROWS;
writeUtf8(output, "<row r=\"" + (lastDetailRow + 1) + "\" ht=\"" writeUtf8(output, "<row r=\"" + (lastDetailRow + 1) + "\" ht=\""
+ EXPORT_DETAIL_ROW_HEIGHT + "\" customHeight=\"true\"/>"); + EXPORT_DETAIL_ROW_HEIGHT + "\" customHeight=\"true\"/>");
writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber()); writeOoxmlFooter(output, templateRows, rowOffset, bill, styleIndexes.generalNumber(), guangzhouTemplate);
String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset); String suffix = shiftFooterMerges(templateXml.substring(sheetDataEnd), rowOffset);
writeUtf8(output, suffix); writeUtf8(output, suffix);
return rowOffset; return rowOffset;
@@ -394,7 +419,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
} }
private void writeOoxmlFooter(OutputStream output, Map<Integer, String> templateRows, int rowOffset, private void writeOoxmlFooter(OutputStream output, Map<Integer, String> 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))"; String totalAmountFormula = "SUM(S" + TEMPLATE_DATA_START_ROW + ":INDEX(S:S,ROW()-1))";
for (int offset = 0; offset < 4; offset++) { for (int offset = 0; offset < 4; offset++) {
int sourceRowNumber = TEMPLATE_LAST_DETAIL_ROW + offset + 1; int sourceRowNumber = TEMPLATE_LAST_DETAIL_ROW + offset + 1;
@@ -407,20 +432,26 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
nvl(bill.getTotalAmount()), generalNumberStyleIndex); nvl(bill.getTotalAmount()), generalNumberStyleIndex);
} else if (offset == 1) { } else if (offset == 1) {
row = replaceCellXml(row, "B" + targetRowNumber, "开户名", false); 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, "P" + targetRowNumber, "本期已核销金额", false);
row = replaceCellXml(row, "S" + targetRowNumber, bill.getWrittenOffAmount(), true, row = replaceCellXml(row, "S" + targetRowNumber, bill.getWrittenOffAmount(), true,
generalNumberStyleIndex); generalNumberStyleIndex);
} else if (offset == 2) { } else if (offset == 2) {
row = replaceCellXml(row, "B" + targetRowNumber, "账号", false); 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); row = replaceCellXml(row, "P" + targetRowNumber, "本期未核销金额", false);
String unwrittenAmountFormula = "S" + (targetRowNumber - 2) + "-S" + (targetRowNumber - 1); String unwrittenAmountFormula = "S" + (targetRowNumber - 2) + "-S" + (targetRowNumber - 1);
row = replaceFormulaCellXml(row, "S" + targetRowNumber, unwrittenAmountFormula, row = replaceFormulaCellXml(row, "S" + targetRowNumber, unwrittenAmountFormula,
nvl(bill.getUnwrittenAmount()), generalNumberStyleIndex); nvl(bill.getUnwrittenAmount()), generalNumberStyleIndex);
} else { } else {
row = replaceCellXml(row, "B" + targetRowNumber, "开户行", false); 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); writeUtf8(output, row);
} }
@@ -430,7 +461,7 @@ public class DefaultArBillWorkbookWriter extends ArBillWorkbookSupport {
ExportStyleIndexes styleIndexes) throws IOException { ExportStyleIndexes styleIndexes) throws IOException {
String failureDescription = exportBillingFailDescription(detail.getBillingFailStatus()); String failureDescription = exportBillingFailDescription(detail.getBillingFailStatus());
boolean failedDetail = !failureDescription.isEmpty(); 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(); int sequenceStyleIndex = failedDetail ? styleIndexes.failedDetailNo() : styleIndexes.detailNo();
Object[] values = { Object[] values = {
detail.getDetailNo(), detail.getDetailNo(),
@@ -23,6 +23,7 @@ import java.util.zip.ZipOutputStream;
import com.bms.common.utils.StringUtils; import com.bms.common.utils.StringUtils;
import com.bms.receivable.domain.ArBill; import com.bms.receivable.domain.ArBill;
import com.bms.receivable.domain.ArBillDetail; import com.bms.receivable.domain.ArBillDetail;
import com.bms.receivable.domain.ArBillDetailFee;
import com.bms.receivable.domain.ArExportTemplate; import com.bms.receivable.domain.ArExportTemplate;
import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.FillPatternType;
@@ -39,9 +40,13 @@ import org.springframework.stereotype.Component;
@Component @Component
public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport { public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
private static final int DETAIL_START_ROW = 5; 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 int SUMMARY_START_ROW = 4;
private static final String SUMMARY_REMARK = "国际货物运输代理服务费"; 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("(<mergeCell\\b[^>]*\\bref=\")([A-Z]+)(\\d+):([A-Z]+)(\\d+)(\")"); private static final Pattern MERGE = Pattern.compile("(<mergeCell\\b[^>]*\\bref=\")([A-Z]+)(\\d+):([A-Z]+)(\\d+)(\")");
private static final Pattern FILTER = Pattern.compile("(<autoFilter\\b[^>]*\\bref=\")[^\"]*(\")"); private static final Pattern FILTER = Pattern.compile("(<autoFilter\\b[^>]*\\bref=\")[^\"]*(\")");
@@ -110,9 +115,15 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
requireRow(workbook.getSheetAt(0), 5); requireRow(workbook.getSheetAt(0), 5);
requireRow(workbook.getSheetAt(1), 4); requireRow(workbook.getSheetAt(1), 4);
requireRow(workbook.getSheetAt(1), 5); requireRow(workbook.getSheetAt(1), 5);
XSSFCell explanationHeader = requireRow(workbook.getSheetAt(1), 3).getCell(DETAIL_COLUMN_COUNT - 1); requireDetailHeader(workbook.getSheetAt(1), 14, "附加费");
if (explanationHeader == null || !"说明".equals(explanationHeader.toString().trim())) { requireDetailHeader(workbook.getSheetAt(1), 19, "备注");
throw new IOException("汇总模板运费明细缺少 T 列说明,请使用最新模板"); 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, 11, 1, exportBankAccountNo(bill.getBankAccountNo()));
textCell(summary, 12, 1, bill.getBankName()); textCell(summary, 12, 1, bill.getBankName());
textCell(detail, 2, 1, bill.getCustomerName()); textCell(detail, 2, 1, bill.getCustomerName());
textCell(detail, 2, 17, billPeriod(bill)); textCell(detail, 2, 18, billPeriod(bill));
for (int column : new int[]{11, 12, 13, 14, 15}) { for (int column : new int[]{11, 12, 13, 15, 16}) {
XSSFCell header = detail.getRow(3).getCell(column); XSSFCell header = detail.getRow(3).getCell(column);
header.setCellValue(header.getStringCellValue().replace("CNY", currency)); header.setCellValue(header.getStringCellValue().replace("CNY", currency));
} }
for (int column = 0; column < DETAIL_COLUMN_COUNT; column++) { for (int column = 0; column < DETAIL_COLUMN_COUNT; column++) {
XSSFCell cell = detail.getRow(4).getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK); 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(); XSSFCellStyle style = workbook.createCellStyle();
style.cloneStyleFrom(cell.getCellStyle()); style.cloneStyleFrom(cell.getCellStyle());
boolean identifier = column == 0 || column == 2 || column == 3 || column == 6; String format = identifier ? "@" : "0.00";
String format = identifier ? "@" : (column == 13 || column == 15 ? "0.00" : "General");
style.setDataFormat(workbook.createDataFormat().getFormat(format)); style.setDataFormat(workbook.createDataFormat().getFormat(format));
cell.setCellStyle(style); cell.setCellStyle(style);
} }
XSSFRow summaryRow = requireRow(summary, 3); XSSFCell summaryAmount = requireRow(summary, 3).getCell(4, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK);
for (int column = 0; column < 7; column++) { XSSFCellStyle summaryAmountStyle = workbook.createCellStyle();
XSSFCell cell = summaryRow.getCell(column, XSSFRow.MissingCellPolicy.CREATE_NULL_AS_BLANK); summaryAmountStyle.cloneStyleFrom(summaryAmount.getCellStyle());
XSSFCellStyle style = workbook.createCellStyle(); summaryAmountStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00"));
style.cloneStyleFrom(cell.getCellStyle()); summaryAmount.setCellStyle(summaryAmountStyle);
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); workbook.setForceFormulaRecalculation(true);
} }
@@ -184,7 +190,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
failed[column] = Short.toUnsignedInt(style.getIndex()); 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, private DetailResult writeDetails(SheetXml sheet, ArBill bill, OutputStream output,
@@ -197,6 +203,7 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
while (true) { while (true) {
List<ArBillDetail> details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE); List<ArBillDetail> details = detailMapper.selectExportPage(bill.getArBillId(), lastDetailNo, EXPORT_PAGE_SIZE);
if (details.isEmpty()) break; if (details.isEmpty()) break;
attachFees(details);
for (ArBillDetail detail : details) { for (ArBillDetail detail : details) {
if (rowNumber + 2 > SpreadsheetVersion.EXCEL2007.getMaxRows()) { if (rowNumber + 2 > SpreadsheetVersion.EXCEL2007.getMaxRows()) {
throw new IOException("账单订单数超过 Excel 单个工作表容量,请拆分账单后导出"); throw new IOException("账单订单数超过 Excel 单个工作表容量,请拆分账单后导出");
@@ -204,8 +211,9 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
if (!StringUtils.isEmpty(detail.getCurrency()) && !detail.getCurrency().equals(bill.getCurrency())) { if (!StringUtils.isEmpty(detail.getCurrency()) && !detail.getCurrency().equals(bill.getCurrency())) {
throw new IOException("账单明细币种与账单币种不一致,请检查账单"); throw new IOException("账单明细币种与账单币种不一致,请检查账单");
} }
writeUtf8(output, detailRow(rowNumber++, bill, detail, styles)); DetailAmounts amounts = calculateDetailAmounts(detail);
BigDecimal amount = nvl(detail.getTotalAmount()); writeUtf8(output, detailRow(rowNumber++, bill, detail, amounts, styles));
BigDecimal amount = amounts.total();
total = total.add(amount); total = total.add(amount);
String key = StringUtils.isEmpty(detail.getProductCode()) String key = StringUtils.isEmpty(detail.getProductCode())
? "NAME:" + detail.getProductName() : "CODE:" + detail.getProductCode(); ? "NAME:" + detail.getProductName() : "CODE:" + detail.getProductCode();
@@ -220,13 +228,14 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
if (count == 0) writeUtf8(output, "<row r=\"5\"/>"); if (count == 0) writeUtf8(output, "<row r=\"5\"/>");
writeUtf8(output, "<row r=\"" + (lastRow + 1) + "\"/>"); writeUtf8(output, "<row r=\"" + (lastRow + 1) + "\"/>");
String footer = shiftRowXml(sheet.rows().get(6), lastRow + 2); 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, footer);
writeUtf8(output, withFilter(sheet.suffix(), "A4:T" + lastRow)); writeUtf8(output, withFilter(sheet.suffix(), "A4:U" + lastRow));
return new DetailResult(count, lastRow, total); 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()); String failure = exportBillingFailDescription(detail.getBillingFailStatus());
Object[] values = { Object[] values = {
bill.getCustomerCode(), bill.getCustomerCode(),
@@ -234,21 +243,27 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
detail.getTransferNo(), detail.getTrackingNo(), detail.getTransferNo(), detail.getTrackingNo(),
StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(), StringUtils.isEmpty(detail.getProductName()) ? detail.getProductCode() : detail.getProductName(),
StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(), StringUtils.isEmpty(detail.getCountryName()) ? detail.getCountryCode() : detail.getCountryName(),
detail.getDestPostcode(), null, detail.getReceiveWeight(), detail.getChargeWeight(), null, detail.getDestPostcode(), null, detail.getReceiveWeight(), nvl(detail.getChargeWeight()),
exportUnitPrice(detail), exportProcessingFee(detail), null, null, detail.getTotalAmount(), null, null, amounts.remote(), nvl(exportUnitPrice(detail)), amounts.processing(), amounts.freight(),
exportRemark(detail), failure amounts.surcharge(), amounts.romania(), amounts.total(), null, null,
null, failure // 客户版汇总模板的 T 列备注固定留空,不输出内部备注或品名描述。
}; };
StringBuilder row = new StringBuilder(2048).append("<row r=\"").append(rowNumber) StringBuilder row = new StringBuilder(2048).append("<row r=\"").append(rowNumber)
.append("\" ht=\"20\" customHeight=\"true\" spans=\"1:").append(DETAIL_COLUMN_COUNT).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++) { for (int index = 0; index < values.length; index++) {
String reference = (char) ('A' + index) + String.valueOf(rowNumber); String reference = (char) ('A' + index) + String.valueOf(rowNumber);
int style = failure.isEmpty() ? styles.normal()[index] : styles.failed()[index]; int style = failure.isEmpty() ? styles.normal()[index] : styles.failed()[index];
if (index == 13) { String formula = switch (index) {
BigDecimal amount = nvl(detail.getChargeWeight()).multiply(nvl(exportUnitPrice(detail))) case 13 -> "ROUND(J" + rowNumber + "*L" + rowNumber + ",2)";
.setScale(2, RoundingMode.HALF_UP); case 16 -> "N" + rowNumber + "+K" + rowNumber + "+M" + rowNumber
+ "+P" + rowNumber + "+O" + rowNumber;
default -> null;
};
if (formula != null) {
row.append("<c r=\"").append(reference).append("\" s=\"").append(style) row.append("<c r=\"").append(reference).append("\" s=\"").append(style)
.append("\" t=\"n\"><f>ROUND(J").append(rowNumber).append("*L").append(rowNumber) .append("\" t=\"n\"><f>").append(xmlEscape(formula)).append("</f><v>")
.append(",2)</f><v>").append(numberText(amount)).append("</v></c>"); .append(numberText((Number) values[index])).append("</v></c>");
} else { } else {
appendOoxmlCell(row, reference, values[index], style); appendOoxmlCell(row, reference, values[index], style);
} }
@@ -256,6 +271,39 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
return row.append("</row>").toString(); return row.append("</row>").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<String, ProductSummary> groups, private void writeSummary(SheetXml sheet, ArBill bill, Map<String, ProductSummary> groups,
BigDecimal total, OutputStream output) throws IOException { BigDecimal total, OutputStream output) throws IOException {
writeUtf8(output, sheet.prefix()); writeUtf8(output, sheet.prefix());
@@ -342,7 +390,9 @@ public class SummaryArBillWorkbookWriter extends ArBillWorkbookSupport {
private record SheetXml(String prefix, Map<Integer, String> rows, String suffix) { } private record SheetXml(String prefix, Map<Integer, String> rows, String suffix) { }
private record DetailResult(int count, int lastRow, BigDecimal amount) { } 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 static class ProductSummary {
private final String name; private final String name;
@@ -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';