✨ 支持应收账单选择模板并导出产品汇总与运费明细

This commit is contained in:
caojia
2026-11-18 15:59:08 +08:00
parent b4569e5c15
commit 69491b07d9
21 changed files with 1973 additions and 961 deletions
@@ -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);
}
/**
@@ -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;
}
}
@@ -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<ArBillDetail> details = List.of(detail(1, "P1", "10.12"), detail(2, "P1", "-2.22"),
detail(3, "P2", "5.30"));
// 相同名称的不同产品仍需分组;收货日期也不能替代账单所属期。
details.forEach(row -> row.setProductName("相同产品名"));
Path target = temporary.resolve("summary.xlsx");
SummaryArBillWorkbookWriter writer = summaryWriter(details);
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<Integer> 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<ArBillDetail> details) {
SummaryArBillWorkbookWriter writer = new SummaryArBillWorkbookWriter();
writer.detailMapper = mapper(details);
return writer;
}
private ArBillDetailMapper mapper(List<ArBillDetail> 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;
}
}
@@ -0,0 +1,9 @@
package com.bms.receivable.domain.vo;
import lombok.Data;
/** 不传模板编号时兼容原接口,使用当前生效的默认模板。 */
@Data
public class ArBillExportRequest {
private Long templateId;
}
@@ -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;
}
}
@@ -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(
"<row\\b(?=[^>]*\\br=\"(\\d+)\")(?:[^>]*/>|[^>]*>.*?</row>)", Pattern.DOTALL);
protected static final Pattern CELL_PATTERN = Pattern.compile(
"<c\\b([^>]*?)(?:/\\s*>|>(.*?)</c>)", 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(
"(<c\\b[^>]*\\br=\")([A-Z]+)\\d+(\")");
protected static final Pattern ROW_REF_PATTERN = Pattern.compile(
"(<row\\b[^>]*\\br=\")\\d+(\")");
protected static final Pattern DIMENSION_PATTERN = Pattern.compile("<dimension\\b[^>]*/>");
@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<Integer, String> extractTemplateRows(String sheetData) {
Map<Integer, String> 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("<c r=\"").append(reference).append("\" s=\"").append(styleIndex).append("\"");
if (value instanceof Number) {
row.append(" t=\"n\"><v>").append(numberText((Number) value)).append("</v></c>");
} else {
String text = value == null ? "" : String.valueOf(value);
row.append(" t=\"inlineStr\"><is><t");
if (text.startsWith(" ") || text.endsWith(" ")) {
row.append(" xml:space=\"preserve\"");
}
row.append(">").append(xmlEscape(text)).append("</t></is></c>");
}
}
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("<c").append(normalizedAttributes)
.append(" t=\"").append(numeric ? "n" : "inlineStr").append("\">");
if (numeric) {
if (formula != null) {
cell.append("<f>").append(xmlEscape(formula)).append("</f>");
}
cell.append("<v>").append(value == null ? "" : numberText((Number) value)).append("</v>");
} else {
String text = value == null ? "" : String.valueOf(value);
cell.append("<is><t");
if (text.startsWith(" ") || text.endsWith(" ")) {
cell.append(" xml:space=\"preserve\"");
}
cell.append(">").append(xmlEscape(text)).append("</t></is>");
}
cell.append("</c>");
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("</row>");
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("<c r=\"").append(reference).append("\"");
if (!StringUtils.isEmpty(style)) {
cell.append(" s=\"").append(style).append("\"");
}
if (numeric) {
cell.append(" t=\"n\">");
if (formula != null) {
cell.append("<f>").append(xmlEscape(formula)).append("</f>");
}
cell.append("<v>").append(value == null ? "" : numberText((Number) value)).append("</v></c>");
} else {
String text = value == null ? "" : String.valueOf(value);
cell.append(" t=\"inlineStr\"><is><t");
if (text.startsWith(" ") || text.endsWith(" ")) {
cell.append(" xml:space=\"preserve\"");
}
cell.append(">").append(xmlEscape(text)).append("</t></is></c>");
}
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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
.replace("\"", "&quot;").replace("'", "&apos;");
}
/**
* 只为当前内存中的一批明细查询费用,避免一次加载整张账单的费用数据。
*/
protected void attachFees(List<ArBillDetail> details) {
List<Long> detailIds = new ArrayList<>();
Map<Long, List<ArBillDetailFee>> feesByDetailId = new HashMap<>();
for (ArBillDetail detail : details) {
detailIds.add(detail.getDetailId());
feesByDetailId.put(detail.getDetailId(), new ArrayList<>());
}
for (ArBillDetailFee fee : detailFeeMapper.selectByDetailIds(detailIds)) {
List<ArBillDetailFee> 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; }
}
@@ -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;
}
@@ -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());
}
}
@@ -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<Integer> 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(
"<Relationship\\b(?=[^>]*\\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("<col\\b([^>]*)/\\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(
"(<mergeCell\\b[^>]*\\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*</" + rowTag + "\\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("<sheetData");
int sheetDataOpenEnd = templateXml.indexOf('>', sheetDataStart);
int sheetDataEnd = templateXml.indexOf("</sheetData>", sheetDataOpenEnd);
if (sheetDataStart < 0 || sheetDataOpenEnd < 0 || sheetDataEnd < 0) {
throw new IOException("应收账单导出模板缺少 sheetData 节点");
}
Map<Integer, String> templateRows = extractTemplateRows(templateXml.substring(sheetDataOpenEnd + 1, sheetDataEnd));
Map<String, Object> 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<ArBillDetail> 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, "<row r=\"" + (lastDetailRow + 1) + "\" ht=\""
+ EXPORT_DETAIL_ROW_HEIGHT + "\" customHeight=\"true\"/>");
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("<col").append(segmentAttributes).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<Integer, String> 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("<row r=\"").append(rowNumber).append("\" ht=\"")
.append(EXPORT_DETAIL_ROW_HEIGHT).append("\" customHeight=\"true\" spans=\"1:21\">");
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("</row>");
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<String, Object> receiveTimeRange) {
if (receiveTimeRange == null) {
return "";
}
String start = formatReceiveDate(receiveTimeRange.get("minReceiveTime"));
String end = formatReceiveDate(receiveTimeRange.get("maxReceiveTime"));
return StringUtils.isEmpty(start) || StringUtils.isEmpty(end) ? "" : start + " 至 " + end;
}
private String formatReceiveDate(Object value) {
if (value instanceof LocalDateTime) {
return ((LocalDateTime) value).toLocalDate().toString();
}
if (value instanceof LocalDate) {
return value.toString();
}
if (value instanceof java.sql.Date) {
return ((java.sql.Date) value).toLocalDate().toString();
}
if (value instanceof Date) {
return new SimpleDateFormat("yyyy-MM-dd").format((Date) value);
}
if (value == null) {
return "";
}
throw new IllegalArgumentException("不支持的收货时间类型: " + value.getClass().getName());
}
private String exportFormula(ArBillDetail detail) {
String formula = joinFeeText(detail.getFees(), true);
if (!StringUtils.isEmpty(formula)) {
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<ArBillDetailFee> 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<ArBillDetailFee> fees, String feeType) {
if (fees == null) {
return false;
}
for (ArBillDetailFee fee : fees) {
if (feeType.equalsIgnoreCase(fee.getFeeType())) {
return true;
}
}
return false;
}
}
@@ -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("(<mergeCell\\b[^>]*\\bref=\")([A-Z]+)(\\d+):([A-Z]+)(\\d+)(\")");
private static final Pattern FILTER = Pattern.compile("(<autoFilter\\b[^>]*\\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<String, ProductSummary> 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<String, ProductSummary> 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<ArBillDetail> 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, "<row r=\"5\"/>");
writeUtf8(output, "<row r=\"" + (lastRow + 1) + "\"/>");
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("<row r=\"").append(rowNumber)
.append("\" ht=\"20\" 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);
row.append("<c r=\"").append(reference).append("\" s=\"").append(style)
.append("\" t=\"n\"><f>ROUND(J").append(rowNumber).append("*L").append(rowNumber)
.append(",2)</f><v>").append(numberText(amount)).append("</v></c>");
} else {
appendOoxmlCell(row, reference, values[index], style);
}
}
return row.append("</row>").toString();
}
private void writeSummary(SheetXml sheet, ArBill bill, Map<String, ProductSummary> 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, "<row r=\"4\"/>");
writeUtf8(output, "<row r=\"" + (lastRow + 1) + "\"/>");
int offset = lastRow - SUMMARY_START_ROW;
for (Map.Entry<Integer, String> 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("<sheetData");
int openEnd = xml.indexOf('>', start);
int end = xml.indexOf("</sheetData>", 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<Integer, String> 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; }
}
}
@@ -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);
@@ -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<ArExportTemplate> selectEnabledList(@Param("businessType") String businessType,
@Param("effectiveDate") Date effectiveDate);
ArExportTemplate selectEnabledById(@Param("templateId") Long templateId,
@Param("businessType") String businessType,
@Param("effectiveDate") Date effectiveDate);
/**
* 查询指定业务类型当前生效的默认模板。
*/
@@ -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<ArBillExportTemplateOption> selectExportTemplates(Long arBillId);
ArBillExport exportBill(Long arBillId, Long templateId, String operator, String requestId);
ArBillExport selectExport(Long exportId);
@@ -63,9 +63,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
order by export_time desc limit 1
</select>
<select id="selectProcessingByBillId" parameterType="long" resultMap="ArBillExportResult">
<select id="selectProcessingByBillAndTemplate" resultMap="ArBillExportResult">
<include refid="selectExportColumns"/>
where ar_bill_id = #{arBillId} and export_status = 'PROCESSING'
and template_id = #{templateId}
order by export_id desc limit 1
</select>
@@ -20,7 +20,7 @@
<result property="remark" column="remark"/>
</resultMap>
<select id="selectDefaultEnabled" resultMap="ArExportTemplateResult">
<sql id="templateColumns">
select template_id,
template_code,
template_name,
@@ -35,11 +35,31 @@
effective_end,
remark
from ar_export_template
</sql>
<sql id="enabledFilter">
where business_type = #{businessType}
and status = 'ENABLED'
and is_default = '1'
and (effective_start is null or effective_start &lt;= #{effectiveDate})
and (effective_end is null or effective_end &gt;= #{effectiveDate})
</sql>
<select id="selectEnabledList" resultMap="ArExportTemplateResult">
<include refid="templateColumns"/>
<include refid="enabledFilter"/>
order by is_default desc, effective_start desc, template_id desc
</select>
<select id="selectEnabledById" resultMap="ArExportTemplateResult">
<include refid="templateColumns"/>
<include refid="enabledFilter"/>
and template_id = #{templateId}
</select>
<select id="selectDefaultEnabled" resultMap="ArExportTemplateResult">
<include refid="templateColumns"/>
<include refid="enabledFilter"/>
and is_default = '1'
order by effective_start desc, template_id desc limit 1
</select>
</mapper>
+6 -2
View File
@@ -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) {
@@ -59,7 +59,7 @@
@size-change="handleDetailSizeChange"
/>
<div class="section-title export-title"><span>导出历史</span><el-button size="small" type="primary" plain icon="Download" v-hasPermi="['ar:bill:export']" :loading="exporting" :disabled="exporting" @click="$emit('export')">{{ exporting ? '生成中' : '导出账单明细' }}</el-button></div>
<div class="section-title export-title"><span>导出历史</span><el-button size="small" type="primary" plain icon="Download" v-hasPermi="['ar:bill:export']" @click="$emit('export')">导出账单明细</el-button></div>
<el-table :data="detail.exports || []" border size="small">
<el-table-column prop="fileName" label="文件名" min-width="250" show-overflow-tooltip />
<el-table-column prop="templateVersion" label="模板版本" width="100" />
@@ -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 => {
@@ -0,0 +1,86 @@
<template>
<el-dialog :model-value="modelValue" title="导出账单" width="480px" append-to-body
:close-on-click-modal="false" :close-on-press-escape="!submitting" :show-close="!submitting"
@update:model-value="$emit('update:modelValue', $event)">
<el-form label-width="88px" v-loading="loading">
<el-form-item label="账单号">
<span>{{ bill?.billNo || '-' }}</span>
</el-form-item>
<el-form-item label="导出模板" required>
<el-select v-model="templateId" placeholder="请选择导出模板" :disabled="loading || submitting" style="width: 100%">
<el-option v-for="item in templates" :key="item.templateId" :value="item.templateId"
:label="item.templateName" />
</el-select>
</el-form-item>
</el-form>
<div v-if="loadError" class="template-load-error">
<span>模板加载失败</span>
<el-button link type="primary" @click="loadTemplates">重新加载</el-button>
</div>
<el-alert v-else-if="!loading && !templates.length" title="暂无可用的账单导出模板" type="info" :closable="false" />
<template #footer>
<el-button :disabled="submitting" @click="$emit('update:modelValue', false)">取消</el-button>
<el-button type="primary" :loading="submitting" :disabled="loading || !templateId" @click="submit">开始导出</el-button>
</template>
</el-dialog>
</template>
<script setup>
import { exportArBill, listArBillExportTemplates } from '@/api/ar/bill'
const props = defineProps({ modelValue: Boolean, bill: { type: Object, default: null } })
const emit = defineEmits(['update:modelValue', 'success', 'submitting'])
const templates = ref([])
const templateId = ref()
const loading = ref(false)
const loadError = ref(false)
const submitting = ref(false)
let requestSerial = 0
watch(() => [props.modelValue, props.bill?.arBillId], ([open]) => {
requestSerial += 1
if (open) loadTemplates()
})
async function loadTemplates() {
const billId = props.bill?.arBillId
if (!billId) return
const serial = ++requestSerial
templates.value = []
templateId.value = undefined
loadError.value = false
loading.value = true
try {
const res = await listArBillExportTemplates(billId)
if (serial !== requestSerial) return
templates.value = res.data || []
templateId.value = templates.value.find(item => String(item.isDefault) === '1')?.templateId
?? templates.value[0]?.templateId
} catch (_) {
if (serial === requestSerial) loadError.value = true
} finally {
if (serial === requestSerial) loading.value = false
}
}
async function submit() {
if (submitting.value || loading.value || !templateId.value || !props.bill?.arBillId) return
const bill = props.bill
submitting.value = true
emit('submitting', true)
try {
const res = await exportArBill(bill.arBillId, { templateId: templateId.value })
emit('update:modelValue', false)
emit('success', { bill, exportTask: res.data })
} catch (_) {
// 请求错误统一由 request 封装提示,保留弹窗中的选择便于重试。
} finally {
submitting.value = false
emit('submitting', false)
}
}
</script>
<style scoped>
.template-load-error { display: flex; align-items: center; gap: 12px; color: var(--el-color-danger); }
</style>
+12 -9
View File
@@ -60,6 +60,8 @@
<bill-detail v-model="detailOpen" :detail="detail" :loading="detailLoading" @download="downloadExport" @export="exportBill(detail)" />
<generate-bill-dialog v-model="generateOpen" @success="handleGenerateSuccess" />
<export-bill-dialog v-model="exportOpen" :bill="exportBillTarget" @success="handleExportSuccess"
@submitting="exportSubmittingCount = $event ? 1 : 0" />
<el-dialog v-model="cancelConfirmVisible" title="取消账单生成" width="420px" append-to-body
:close-on-click-modal="false" :close-on-press-escape="!cancelConfirmLoading"
:show-close="!cancelConfirmLoading" @closed="handleCancelConfirmClosed">
@@ -75,9 +77,10 @@
<script setup name="ArBill">
import { saveAs } from 'file-saver'
import { listArBillCustomerOptions, listArBill, getArBill, confirmArBill, voidArBill, getArBillVoidTask, exportArBill, getArBillExport, downloadArBillExport, getArBillExportDownloadInfo, getArBillGenerateTask, listActiveArBillGenerateTasks, cancelArBillGenerateTask, retryArBillGenerateTask } from '@/api/ar/bill'
import { listArBillCustomerOptions, listArBill, getArBill, confirmArBill, voidArBill, getArBillVoidTask, getArBillExport, downloadArBillExport, getArBillExportDownloadInfo, getArBillGenerateTask, listActiveArBillGenerateTasks, cancelArBillGenerateTask, retryArBillGenerateTask } from '@/api/ar/bill'
import BillDetail from './components/BillDetail.vue'
import GenerateBillDialog from './components/GenerateBillDialog.vue'
import ExportBillDialog from './components/ExportBillDialog.vue'
import { AR_BILL_STATUS, AR_BILL_STATUS_OPTIONS, AR_BILL_STATUS_TYPES } from '@/constants/ar/bill'
const { proxy } = getCurrentInstance()
@@ -102,6 +105,8 @@ const voidPollTimers = new Map()
let voidPageClosed = false
const openedBillId = ref()
const generateOpen = ref(false)
const exportOpen = ref(false)
const exportBillTarget = ref(null)
// 任务可能在首次轮询前就完成,至少展示一段时间让用户感知到“正在生成”。
const MIN_GENERATE_STATUS_VISIBLE_MS = 1800
// 每个任务独立保存轮询、收尾定时器和开始展示时间,避免多个账单任务互相覆盖。
@@ -377,19 +382,17 @@ function pollVoidTask(billId, taskId) {
}
function exportBill(row) {
if (!row?.arBillId) return
exportSubmittingCount.value += 1
exportArBill(row.arBillId).then(res => {
const exportTask = res.data
exportBillTarget.value = row
exportOpen.value = true
}
function handleExportSuccess({ bill, exportTask }) {
tableRef.value?.refresh()
// 导出同样是异步任务;打开详情展示“生成中”状态及完成后的下载入口。
viewBill(row)
viewBill(bill)
if (exportTask?.exportId) {
exportTasks.set(exportTask.exportId, exportTask)
startExportPolling(exportTask.exportId)
}
}).finally(() => {
exportSubmittingCount.value = Math.max(0, exportSubmittingCount.value - 1)
})
}
onMounted(loadActiveGenerateTasks)