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

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;
}
}