Merge branch 'test' of https://git.lionquexpress.com/wuweihua/BMS into test
This commit is contained in:
+14
-6
@@ -25,11 +25,13 @@ 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;
|
||||
import com.bms.receivable.domain.ArBillLog;
|
||||
import com.bms.receivable.domain.vo.ArBillActionRequest;
|
||||
import com.bms.receivable.domain.vo.ArBillDetailQuery;
|
||||
import com.bms.receivable.domain.vo.ArBillGenerateQuery;
|
||||
import com.bms.receivable.domain.vo.ArBillGenerateRequest;
|
||||
import com.bms.receivable.domain.vo.ArBillListExportRow;
|
||||
@@ -140,9 +142,9 @@ public class ArBillController extends BaseController {
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/{arBillId}/details")
|
||||
public TableDataInfo details(@PathVariable Long arBillId) {
|
||||
public TableDataInfo details(@PathVariable Long arBillId, @Valid ArBillDetailQuery query) {
|
||||
startPage();
|
||||
return getDataTable(billService.selectArBillDetails(arBillId));
|
||||
return getDataTable(billService.selectArBillDetails(arBillId, query));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -311,16 +313,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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -25,6 +25,17 @@ class PayZoneMatcherTest
|
||||
assertEquals("UK Mainland\n英国大陆", decision.getZoneName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryUkPostcodeIsMainlandAndNotARemoteZone()
|
||||
{
|
||||
PayZoneMatcher.Decision decision = PayZoneMatcher.resolve(ZONES, evriLines(), "KY4 0DN");
|
||||
assertNull(decision.getMessage());
|
||||
assertEquals("UK Mainland\n英国大陆", decision.getZoneName());
|
||||
PayZoneMatcher.Decision emptyBook = PayZoneMatcher.resolve(ZONES, List.of(), "KY4 0DN");
|
||||
assertNull(emptyBook.getMessage());
|
||||
assertEquals("UK Mainland\n英国大陆", emptyBook.getZoneName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void northernIrelandAndHighlandsComeFromThePostcodeBook()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.bms.receivable;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import com.bms.receivable.domain.ArBillDetail;
|
||||
import com.bms.receivable.domain.vo.ArBillDetailQuery;
|
||||
import com.bms.receivable.mapper.ArBillDetailMapper;
|
||||
import com.bms.receivable.security.ArBillRowScope;
|
||||
import com.bms.receivable.security.ArBillScopeResolver;
|
||||
import com.bms.receivable.service.impl.ArBillServiceImpl;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.parser.defaults.DefaultCountSqlParser;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.mapping.BoundSql;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
class ArBillDetailSearchTest {
|
||||
@Test
|
||||
void numberSearchUsesExactMatchesAndCannotBypassBillOrPermissionScope() throws Exception {
|
||||
ArBillDetailQuery query = new ArBillDetailQuery();
|
||||
query.setOrderKeyword("00123' OR 1=1 --");
|
||||
BoundSql bound = detailSql(query, scope(false, true));
|
||||
String sql = normalized(bound.getSql());
|
||||
assertTrue(sql.contains("where ar_bill_id = ?"));
|
||||
assertTrue(sql.contains("and (order_no = ? or tracking_no = ? or transfer_no = ?)"));
|
||||
assertTrue(sql.contains("b.ar_bill_id = ar_bill_detail.ar_bill_id"));
|
||||
assertTrue(sql.contains("c.customer_id = b.customer_id"));
|
||||
assertTrue(sql.contains("su.user_id = ?"));
|
||||
assertFalse(sql.contains("order_no like"));
|
||||
assertFalse(sql.contains(query.getOrderKeyword()));
|
||||
assertEquals(3, bound.getParameterMappings().stream()
|
||||
.filter(parameter -> parameter.getProperty().equals("query.orderKeyword")).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void productSearchAndPaginationCountApplyBothFiltersAndTheSameScope() throws Exception {
|
||||
ArBillDetailQuery query = new ArBillDetailQuery();
|
||||
query.setOrderKeyword("ORDER001");
|
||||
query.setProductKeyword("荷兰");
|
||||
String sql = normalized(detailSql(query, scope(false, true)).getSql());
|
||||
assertTrue(sql.contains("and (product_code like concat('%', ?, '%') or product_name like concat('%', ?, '%'))"));
|
||||
String count = normalized(new DefaultCountSqlParser().getSmartCountSql(sql, "0"));
|
||||
assertTrue(count.startsWith("select count(0)"));
|
||||
assertTrue(count.contains("ar_bill_id = ?"));
|
||||
assertTrue(count.contains("order_no = ?"));
|
||||
assertTrue(count.contains("tracking_no = ?"));
|
||||
assertTrue(count.contains("transfer_no = ?"));
|
||||
assertTrue(count.contains("product_code like"));
|
||||
assertTrue(count.contains("product_name like"));
|
||||
assertTrue(count.contains("su.user_id = ?"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noSearchKeepsExistingQueryAndDeniedScopeRemainsDenied() throws Exception {
|
||||
for (ArBillDetailQuery query : new ArBillDetailQuery[]{null, new ArBillDetailQuery()}) {
|
||||
String sql = normalized(detailSql(query, scope(false, false)).getSql());
|
||||
assertFalse(sql.contains("order_no = ?"));
|
||||
assertFalse(sql.contains("product_code like"));
|
||||
assertTrue(sql.contains("and 1 = 0"));
|
||||
assertTrue(sql.contains("where ar_bill_id = ?"));
|
||||
assertTrue(sql.endsWith("order by detail_no"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceTrimsSearchAndPreservesPaginationForTheScopedDetailQuery() {
|
||||
ArBillServiceImpl service = new ArBillServiceImpl();
|
||||
ArBillDetailMapper details = mock(ArBillDetailMapper.class);
|
||||
ArBillScopeResolver resolver = mock(ArBillScopeResolver.class);
|
||||
ArBillRowScope scope = mock(ArBillRowScope.class);
|
||||
ReflectionTestUtils.setField(service, "detailMapper", details);
|
||||
ReflectionTestUtils.setField(service, "billScope", resolver);
|
||||
when(resolver.resolve()).thenReturn(scope);
|
||||
List<ArBillDetail> result = List.of(new ArBillDetail());
|
||||
when(details.selectByBillIdScoped(eq(7L), any(), same(scope))).thenAnswer(invocation -> {
|
||||
ArBillDetailQuery query = invocation.getArgument(1);
|
||||
assertEquals("000123", query.getOrderKeyword());
|
||||
assertEquals("荷兰", query.getProductKeyword());
|
||||
assertEquals(3, PageHelper.getLocalPage().getPageNum());
|
||||
return result;
|
||||
});
|
||||
ArBillDetailQuery query = new ArBillDetailQuery();
|
||||
query.setOrderKeyword(" 000123 ");
|
||||
query.setProductKeyword(" 荷兰 ");
|
||||
PageHelper.startPage(3, 10);
|
||||
try {
|
||||
assertSame(result, service.selectArBillDetails(7L, query));
|
||||
verify(details).selectByBillIdScoped(eq(7L), any(), same(scope));
|
||||
verifyNoMoreInteractions(details);
|
||||
} finally {
|
||||
PageHelper.clearPage();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void wholeBillExportQueryDoesNotInheritDetailSearchFilters() throws Exception {
|
||||
String sql = normalized(configuration().getMappedStatement("com.bms.receivable.mapper.ArBillDetailMapper.selectExportPage")
|
||||
.getBoundSql(Map.of("arBillId", 7L, "lastDetailNo", 0, "pageSize", 2000)).getSql());
|
||||
assertTrue(sql.contains("where ar_bill_id = ? and detail_no > ?"));
|
||||
assertFalse(sql.contains("order_no = ?"));
|
||||
assertFalse(sql.contains("product_code like"));
|
||||
assertTrue(sql.endsWith("limit ?"));
|
||||
}
|
||||
|
||||
private BoundSql detailSql(ArBillDetailQuery query, Map<String, Object> scope) throws Exception {
|
||||
Map<String, Object> parameters = new HashMap<>();
|
||||
parameters.put("arBillId", 7L);
|
||||
parameters.put("query", query);
|
||||
parameters.put("scope", scope);
|
||||
return configuration().getMappedStatement("com.bms.receivable.mapper.ArBillDetailMapper.selectByBillIdScoped")
|
||||
.getBoundSql(parameters);
|
||||
}
|
||||
|
||||
private Configuration configuration() throws Exception {
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.getTypeAliasRegistry().registerAlias("ArBillDetail", ArBillDetail.class);
|
||||
for (String resource : List.of("mapper/receivable/ArBillScopeMapper.xml", "mapper/receivable/ArBillDetailMapper.xml")) {
|
||||
try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource)) {
|
||||
new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
|
||||
}
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private Map<String, Object> scope(boolean all, boolean self) {
|
||||
return Map.of("all", all, "self", self, "department", false, "userId", 9L, "deptId", 10L);
|
||||
}
|
||||
|
||||
private String normalized(String sql) {
|
||||
return sql.replaceAll("\\s+", " ").trim().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
+144
@@ -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;
|
||||
}
|
||||
}
|
||||
+244
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,7 @@ public class LoginUser implements UserDetails
|
||||
@Override
|
||||
public String getUsername()
|
||||
{
|
||||
return user.getUserName();
|
||||
return user == null ? null : user.getUserName();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,6 +23,9 @@ public class PayOrderRow
|
||||
|
||||
private String countryName;
|
||||
|
||||
/** 收件邮编,来自 prc_order_bill.dest_postcode */
|
||||
private String destPostcode;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private BigDecimal chargeWeight;
|
||||
|
||||
@@ -5,6 +5,8 @@ import java.math.RoundingMode;
|
||||
import java.util.Date;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.bms.common.core.domain.entity.SysUser;
|
||||
import com.bms.common.core.domain.model.LoginUser;
|
||||
import com.bms.common.utils.SecurityUtils;
|
||||
import com.bms.common.utils.StringUtils;
|
||||
import com.bms.system.domain.BmsExchangeRate;
|
||||
@@ -24,6 +26,11 @@ public class PayFeeMoney
|
||||
/** 汇总金额小数位 */
|
||||
public static final int TOTAL_SCALE = 2;
|
||||
|
||||
/** 提交重算的那个人。后台线程没有登录态,用提交时记下的账号。 */
|
||||
private static final ThreadLocal<String> BOUND_NAME = new ThreadLocal<>();
|
||||
|
||||
private static final ThreadLocal<String> BOUND_ID = new ThreadLocal<>();
|
||||
|
||||
@Autowired
|
||||
private IBmsExchangeRateService exchangeRateService;
|
||||
|
||||
@@ -57,17 +64,107 @@ public class PayFeeMoney
|
||||
return value.setScale(TOTAL_SCALE, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
/** 当前登录用户的主键。没有登录信息时返回空,费用上不写账号。 */
|
||||
/**
|
||||
* 在还有登录态的线程上取出账号和用户主键。后台重算把这两个值带过去。
|
||||
*
|
||||
* @return 下标 0 是账号,下标 1 是用户主键;取不到时对应位置为空串
|
||||
*/
|
||||
public static String[] capture()
|
||||
{
|
||||
String name = "";
|
||||
String id = "";
|
||||
try
|
||||
{
|
||||
LoginUser login = SecurityUtils.getLoginUser();
|
||||
if (login.getUserId() != null)
|
||||
{
|
||||
id = String.valueOf(login.getUserId());
|
||||
}
|
||||
SysUser user = login.getUser();
|
||||
if (user != null && user.getUserName() != null && !user.getUserName().isBlank())
|
||||
{
|
||||
name = user.getUserName().trim();
|
||||
}
|
||||
}
|
||||
catch (Exception ignored)
|
||||
{
|
||||
name = "";
|
||||
id = "";
|
||||
}
|
||||
return new String[] { name, id };
|
||||
}
|
||||
|
||||
/** 后台线程开始处理前放上提交人。空值表示这根线程不覆盖登录态。 */
|
||||
public static void bind(String name, String userId)
|
||||
{
|
||||
if (name == null || name.isBlank())
|
||||
{
|
||||
BOUND_NAME.remove();
|
||||
}
|
||||
else
|
||||
{
|
||||
BOUND_NAME.set(name.trim());
|
||||
}
|
||||
if (userId == null || userId.isBlank())
|
||||
{
|
||||
BOUND_ID.remove();
|
||||
}
|
||||
else
|
||||
{
|
||||
BOUND_ID.set(userId.trim());
|
||||
}
|
||||
}
|
||||
|
||||
/** 线程归还线程池前清掉,避免下一票用到上一个人。 */
|
||||
public static void clear()
|
||||
{
|
||||
BOUND_NAME.remove();
|
||||
BOUND_ID.remove();
|
||||
}
|
||||
|
||||
/** 操作人账号。优先用提交重算时记下的账号,没有登录信息时记 system。 */
|
||||
public static String operatorName()
|
||||
{
|
||||
String bound = BOUND_NAME.get();
|
||||
if (bound != null && !bound.isBlank())
|
||||
{
|
||||
return bound;
|
||||
}
|
||||
try
|
||||
{
|
||||
String name = SecurityUtils.getUsername();
|
||||
if (name != null && !name.isBlank())
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
catch (Exception ignored)
|
||||
{
|
||||
return "system";
|
||||
}
|
||||
return "system";
|
||||
}
|
||||
|
||||
/** 当前登录用户的主键。订单同步等没有登录信息时记 system,页面回显为系统自动。 */
|
||||
public static String userId()
|
||||
{
|
||||
String bound = BOUND_ID.get();
|
||||
if (bound != null && !bound.isBlank())
|
||||
{
|
||||
return bound;
|
||||
}
|
||||
try
|
||||
{
|
||||
Long id = SecurityUtils.getUserId();
|
||||
return id == null ? null : String.valueOf(id);
|
||||
if (id != null)
|
||||
{
|
||||
return String.valueOf(id);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception ignored)
|
||||
{
|
||||
return null;
|
||||
return "system";
|
||||
}
|
||||
return "system";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +340,7 @@ public class PayOrderFeeCalculator
|
||||
return null;
|
||||
}
|
||||
List<Long> linkedZoneIds = zoneGroupIds(linked, countryCode, countryName);
|
||||
addRemoteZoneIds(linkedZoneIds, linked, countryCode, countryName);
|
||||
if (!linkedZoneIds.isEmpty())
|
||||
{
|
||||
return decideZone(zoneNames, linkedZoneIds, postcode);
|
||||
@@ -363,6 +364,11 @@ public class PayOrderFeeCalculator
|
||||
}
|
||||
if (groups.isEmpty())
|
||||
{
|
||||
PayZoneMatcher.Decision mainland = PayZoneMatcher.resolve(zoneNames, new ArrayList<>(), postcode);
|
||||
if (mainland.getZoneName() != null)
|
||||
{
|
||||
return mainland.getZoneName();
|
||||
}
|
||||
throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,没有找到对应的邮编分区");
|
||||
}
|
||||
List<Long> groupIds = new ArrayList<>();
|
||||
@@ -409,7 +415,35 @@ public class PayOrderFeeCalculator
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出用来选派送费的普通分区。偏远、附加费邮编和不可达不参与选区。
|
||||
* 偏远邮编同时用来选价卡地区。对上高地、岛屿这类邮编时走对应价格列,对不上则由大陆列承接。
|
||||
*
|
||||
* @param ids 已经放入的分区组
|
||||
* @param linked 已对上的邮编组
|
||||
* @param countryCode 目的国二字码
|
||||
* @param countryName 目的国名称
|
||||
*/
|
||||
private static void addRemoteZoneIds(List<Long> ids, List<PayPostcodeGroup> linked, String countryCode, String countryName)
|
||||
{
|
||||
if (linked == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (PayPostcodeGroup group : linked)
|
||||
{
|
||||
if (group == null || group.getGroupId() == null || ids.contains(group.getGroupId()) || !PayRemoteBook.remoteGroup(group))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ("FEE".equals(group.getConfigKind()) || !sameCountry(group, countryCode, countryName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ids.add(group.getGroupId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出用来选派送费的普通分区。附加费邮编和不可达不参与选区。
|
||||
*
|
||||
* @param linked 已对上的邮编组
|
||||
* @param countryCode 目的国二字码
|
||||
|
||||
@@ -110,6 +110,11 @@ public final class PayZoneMatcher
|
||||
}
|
||||
if (lines == null || lines.isEmpty())
|
||||
{
|
||||
String mainland = mainlandZone(zoneNames);
|
||||
if (mainland != null)
|
||||
{
|
||||
return Decision.zone(mainland);
|
||||
}
|
||||
return Decision.unknown();
|
||||
}
|
||||
String bestZone = null;
|
||||
|
||||
+39
-26
@@ -9,7 +9,6 @@ import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.bms.common.enums.PaymentMesEnum;
|
||||
import com.bms.common.exception.ServiceException;
|
||||
import com.bms.common.utils.SecurityUtils;
|
||||
import com.bms.masterdata.domain.ServiceChannel;
|
||||
import com.bms.masterdata.mapper.ServiceChannelMapper;
|
||||
import com.bms.price.domain.PayCostLine;
|
||||
@@ -149,7 +148,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
{
|
||||
throw new ServiceException(result.getMessage() == null ? PaymentMesEnum.BMS_PAY_NO_COST.getCnMes() : result.getMessage());
|
||||
}
|
||||
String operator = SecurityUtils.getUsername();
|
||||
String operator = operator();
|
||||
PrcPayBill payBill = saveBill(bill, result, operator);
|
||||
saveFees(bill.getBillId(), payBill.getPayBillId(), result);
|
||||
String channelName = channel.getChannelName() == null ? channel.getChannelCode() : channel.getChannelName();
|
||||
@@ -180,19 +179,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
{
|
||||
message = message.substring(0, 100);
|
||||
}
|
||||
String operator = "system";
|
||||
try
|
||||
{
|
||||
String name = SecurityUtils.getUsername();
|
||||
if (name != null && !name.isBlank())
|
||||
{
|
||||
operator = name;
|
||||
}
|
||||
}
|
||||
catch (Exception ignored)
|
||||
{
|
||||
operator = "system";
|
||||
}
|
||||
String operator = operator();
|
||||
payBillMapper.insertMissingPayBills(List.of(billId), operator);
|
||||
payBillMapper.markCalcStatus(billId, 2, message, operator);
|
||||
}
|
||||
@@ -371,6 +358,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
return null;
|
||||
}
|
||||
List<Long> linkedZoneIds = zoneGroupIds(linked, countryCode, countryName);
|
||||
addRemoteZoneIds(linkedZoneIds, linked, countryCode, countryName);
|
||||
if (!linkedZoneIds.isEmpty())
|
||||
{
|
||||
return decideZone(zoneNames, linkedZoneIds, postcode);
|
||||
@@ -394,6 +382,11 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
}
|
||||
if (groups.isEmpty())
|
||||
{
|
||||
PayZoneMatcher.Decision mainland = PayZoneMatcher.resolve(zoneNames, new ArrayList<>(), postcode);
|
||||
if (mainland.getZoneName() != null)
|
||||
{
|
||||
return mainland.getZoneName();
|
||||
}
|
||||
throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,没有找到对应的邮编分区");
|
||||
}
|
||||
List<Long> groupIds = new ArrayList<>();
|
||||
@@ -440,7 +433,35 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出用来选派送费的普通分区。偏远、附加费邮编和不可达不参与选区。
|
||||
* 偏远邮编同时用来选价卡地区。对上高地、岛屿这类邮编时走对应价格列,对不上则由大陆列承接。
|
||||
*
|
||||
* @param ids 已经放入的分区组
|
||||
* @param linked 已对上的邮编组
|
||||
* @param countryCode 目的国二字码
|
||||
* @param countryName 目的国名称
|
||||
*/
|
||||
private static void addRemoteZoneIds(List<Long> ids, List<PayPostcodeGroup> linked, String countryCode, String countryName)
|
||||
{
|
||||
if (linked == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (PayPostcodeGroup group : linked)
|
||||
{
|
||||
if (group == null || group.getGroupId() == null || ids.contains(group.getGroupId()) || !PayRemoteBook.remoteGroup(group))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if ("FEE".equals(group.getConfigKind()) || !sameCountry(group, countryCode, countryName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ids.add(group.getGroupId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出用来选派送费的普通分区。附加费邮编和不可达不参与选区。
|
||||
*
|
||||
* @param linked 已对上的邮编组
|
||||
* @param countryCode 目的国二字码
|
||||
@@ -732,18 +753,10 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
|
||||
return text.length() <= 100 ? text : text.substring(0, 100);
|
||||
}
|
||||
|
||||
/** 当前登录人。没有登录信息时记 system。 */
|
||||
/** 当前操作人。后台重算用提交时记下的账号,没有登录信息时记 system。 */
|
||||
private static String operator()
|
||||
{
|
||||
try
|
||||
{
|
||||
String name = SecurityUtils.getUsername();
|
||||
return name == null || name.isBlank() ? "system" : name;
|
||||
}
|
||||
catch (Exception ignored)
|
||||
{
|
||||
return "system";
|
||||
}
|
||||
return PayFeeMoney.operatorName();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-1
@@ -193,7 +193,8 @@ public class PayOrderListServiceImpl implements IPayOrderListService
|
||||
task.setTotal(task.getLines().size());
|
||||
task.setPercent(task.getTotal() == 0 ? 100 : finished * 100 / task.getTotal());
|
||||
payOrderRecalcAsyncRunner.save(task);
|
||||
payOrderRecalcAsyncRunner.run(task.getTaskId(), SecurityContextHolder.getContext().getAuthentication());
|
||||
String[] actor = PayFeeMoney.capture();
|
||||
payOrderRecalcAsyncRunner.run(task.getTaskId(), SecurityContextHolder.getContext().getAuthentication(), actor[0], actor[1]);
|
||||
return task.getTaskId();
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -56,6 +56,7 @@ import com.bms.price.domain.PrcPayBill;
|
||||
import com.bms.price.domain.PrcPayBillFee;
|
||||
import com.bms.price.domain.PrcPriceSet;
|
||||
import com.bms.price.domain.PrcSurcharge;
|
||||
import com.bms.price.pay.PayFeeMoney;
|
||||
import com.bms.price.domain.BatchAddIncomeBillFeeTask;
|
||||
import com.bms.price.domain.ChargeWeightImportTask;
|
||||
import com.bms.price.domain.vo.AddIncomeBillFeeRequest;
|
||||
@@ -1217,7 +1218,8 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService
|
||||
localRebillAsyncRunner.put(taskId, BatchAddIncomeBillFeeTask.STATUS_PENDING, 0, "queued", null,
|
||||
billIds.size(), 0, 0);
|
||||
// 完成时每批写一条 ES 操作日志(LOCAL_REBILL_DONE);失败订单写入 detail.failDetails。
|
||||
localRebillAsyncRunner.run(taskId, billIds, request);
|
||||
String[] actor = PayFeeMoney.capture();
|
||||
localRebillAsyncRunner.run(taskId, billIds, request, actor[0], actor[1]);
|
||||
return taskId;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import com.bms.price.domain.PayOrderCostResult;
|
||||
import com.bms.price.domain.PayOrderRecalcLine;
|
||||
import com.bms.price.domain.PayOrderRecalcTask;
|
||||
import com.bms.price.domain.PrcPayBillFeeLog;
|
||||
import com.bms.price.pay.PayFeeMoney;
|
||||
import com.bms.price.service.IPayOrderListService;
|
||||
import com.bms.price.service.PayBillFeeLogService;
|
||||
|
||||
@@ -48,11 +49,12 @@ public class PayOrderRecalcAsyncRunner
|
||||
private final Map<String, AtomicBoolean> cancelFlags = new ConcurrentHashMap<>();
|
||||
|
||||
@Async("threadPoolTaskExecutor")
|
||||
public void run(String taskId, Authentication authentication)
|
||||
public void run(String taskId, Authentication authentication, String operatorName, String operatorUserId)
|
||||
{
|
||||
SecurityContext previous = SecurityContextHolder.getContext();
|
||||
List<PrcPayBillFeeLog> feeLogs = new ArrayList<>();
|
||||
boolean drained = false;
|
||||
PayFeeMoney.bind(operatorName, operatorUserId);
|
||||
try
|
||||
{
|
||||
if (authentication != null)
|
||||
@@ -156,6 +158,7 @@ public class PayOrderRecalcAsyncRunner
|
||||
{
|
||||
drain(feeLogs);
|
||||
}
|
||||
PayFeeMoney.clear();
|
||||
SecurityContextHolder.setContext(previous);
|
||||
cancelFlags.remove(taskId);
|
||||
}
|
||||
|
||||
+16
-1
@@ -28,6 +28,7 @@ import com.bms.price.config.BillingProperties;
|
||||
import com.bms.price.domain.BatchAddIncomeBillFeeTask;
|
||||
import com.bms.price.domain.PrcOrderBill;
|
||||
import com.bms.price.domain.vo.LocalRebillRequest;
|
||||
import com.bms.price.pay.PayFeeMoney;
|
||||
import com.bms.price.domain.vo.TmsPriceQuoteResult;
|
||||
import com.bms.price.enums.BillBillingFailStatus;
|
||||
import com.bms.price.mapper.PrcOrderBillMapper;
|
||||
@@ -76,11 +77,17 @@ public class PrcOrderBillLocalRebillAsyncRunner
|
||||
@Async("threadPoolTaskExecutor")
|
||||
public void run(String taskId, List<Long> billIds)
|
||||
{
|
||||
run(taskId, billIds, null);
|
||||
run(taskId, billIds, null, null, null);
|
||||
}
|
||||
|
||||
@Async("threadPoolTaskExecutor")
|
||||
public void run(String taskId, List<Long> billIds, LocalRebillRequest request)
|
||||
{
|
||||
run(taskId, billIds, request, null, null);
|
||||
}
|
||||
|
||||
@Async("threadPoolTaskExecutor")
|
||||
public void run(String taskId, List<Long> billIds, LocalRebillRequest request, String operatorName, String operatorUserId)
|
||||
{
|
||||
int total = billIds == null ? 0 : billIds.size();
|
||||
AtomicInteger success = new AtomicInteger(0);
|
||||
@@ -115,6 +122,9 @@ public class PrcOrderBillLocalRebillAsyncRunner
|
||||
for (int w = 0; w < threads; w++)
|
||||
{
|
||||
workers.add(() -> {
|
||||
PayFeeMoney.bind(operatorName, operatorUserId);
|
||||
try
|
||||
{
|
||||
while (!isCancelRequested(taskId))
|
||||
{
|
||||
int i = nextIndex.getAndIncrement();
|
||||
@@ -161,6 +171,11 @@ public class PrcOrderBillLocalRebillAsyncRunner
|
||||
}
|
||||
}
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
finally
|
||||
{
|
||||
PayFeeMoney.clear();
|
||||
}
|
||||
});
|
||||
}
|
||||
invokeAllQuiet(pool, workers);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.bms.receivable.domain.vo;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
/** 当前账单内的明细筛选条件;账单范围和数据权限由后端独立传入。 */
|
||||
@Data
|
||||
public class ArBillDetailQuery {
|
||||
/** 完整订单号、运单号或转单号,按等值匹配。 */
|
||||
@Size(max = 64, message = "单号不能超过64个字符")
|
||||
private String orderKeyword;
|
||||
|
||||
/** 产品代码或名称,按包含关系匹配。 */
|
||||
@Size(max = 100, message = "产品搜索条件不能超过100个字符")
|
||||
private String productKeyword;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.bms.receivable.domain.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 不传模板编号时兼容原接口,使用当前生效的默认模板。 */
|
||||
@Data
|
||||
public class ArBillExportRequest {
|
||||
private Long templateId;
|
||||
}
|
||||
+24
@@ -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;
|
||||
}
|
||||
}
|
||||
+372
@@ -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("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* 只为当前内存中的一批明细查询费用,避免一次加载整张账单的费用数据。
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
+25
@@ -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());
|
||||
}
|
||||
}
|
||||
+596
@@ -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;
|
||||
}
|
||||
}
|
||||
+352
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,12 @@ import java.util.Map;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.bms.receivable.domain.ArBillDetail;
|
||||
import com.bms.receivable.domain.vo.ArBillDetailQuery;
|
||||
|
||||
public interface ArBillDetailMapper {
|
||||
List<ArBillDetail> selectByBillIdScoped(@Param("arBillId") Long arBillId, @Param("scope") ArBillRowScope scope);
|
||||
List<ArBillDetail> selectByBillIdScoped(@Param("arBillId") Long arBillId,
|
||||
@Param("query") ArBillDetailQuery query,
|
||||
@Param("scope") ArBillRowScope scope);
|
||||
|
||||
List<ArBillDetail> selectByBillId(Long arBillId);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
+8
@@ -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);
|
||||
|
||||
/**
|
||||
* 查询指定业务类型当前生效的默认模板。
|
||||
*/
|
||||
|
||||
@@ -15,7 +15,9 @@ import com.bms.receivable.domain.vo.ArBillGenerateRequest;
|
||||
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.ArBillDetailQuery;
|
||||
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;
|
||||
|
||||
@@ -32,7 +34,7 @@ public interface IArBillService
|
||||
|
||||
ArBill selectArBillById(Long arBillId);
|
||||
|
||||
List<ArBillDetail> selectArBillDetails(Long arBillId);
|
||||
List<ArBillDetail> selectArBillDetails(Long arBillId, ArBillDetailQuery query);
|
||||
|
||||
List<ArBillDetailFee> selectArBillDetailFees(Long arBillId, Long detailId);
|
||||
|
||||
@@ -72,7 +74,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);
|
||||
|
||||
|
||||
+43
-936
File diff suppressed because it is too large
Load Diff
@@ -10,13 +10,29 @@
|
||||
p.customer_name as customerName,
|
||||
p.product_name as productName,
|
||||
p.country_name as countryName,
|
||||
p.dest_postcode as destPostcode,
|
||||
p.product_floor as channelName,
|
||||
p.charge_weight as chargeWeight,
|
||||
ifnull(b.pay_total, p.pay_total) as payTotal,
|
||||
ifnull(nullif(trim(b.currency), ''), 'CNY') as currency,
|
||||
b.pay_calc_status as payCalcStatus,
|
||||
b.pay_calc_msg as payCalcMsg,
|
||||
b.update_by as updateBy,
|
||||
case
|
||||
when lower(trim(b.update_by)) = 'system' then '系统自动'
|
||||
else ifnull((
|
||||
select case
|
||||
when nullif(trim(u.nick_name), '') is not null then u.nick_name
|
||||
else u.user_name
|
||||
end
|
||||
from sys_user u
|
||||
where u.del_flag = '0'
|
||||
and (
|
||||
(b.update_by regexp '^[0-9]+$' and u.user_id = cast(b.update_by as unsigned))
|
||||
or (ifnull(b.update_by, '') not regexp '^[0-9]+$' and u.user_name = b.update_by COLLATE utf8mb4_general_ci)
|
||||
)
|
||||
limit 1
|
||||
), b.update_by)
|
||||
end as updateBy,
|
||||
b.update_time as updateTime,
|
||||
p.biz_date as bizDate
|
||||
from prc_order_bill p
|
||||
|
||||
@@ -42,7 +42,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
select log_id, fee_id, bill_id, fee_name, amount, currency,
|
||||
before_fee_name, before_amount, before_currency,
|
||||
after_fee_name, after_amount, after_currency,
|
||||
operation_type, remark, create_by, create_time
|
||||
operation_type, remark,
|
||||
case when lower(trim(create_by)) = 'system' then '系统自动' else create_by end as create_by,
|
||||
create_time
|
||||
from prc_pay_bill_fee_log
|
||||
where bill_id = #{billId}
|
||||
order by log_id desc
|
||||
|
||||
@@ -47,29 +47,32 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
|
||||
</sql>
|
||||
|
||||
<sql id="feeUserName">
|
||||
(
|
||||
select case
|
||||
when nullif(trim(u.nick_name), '') is not null then u.nick_name
|
||||
else u.user_name
|
||||
end
|
||||
from sys_user u
|
||||
where u.del_flag = '0'
|
||||
and (
|
||||
(${column} regexp '^[0-9]+$' and u.user_id = cast(${column} as unsigned))
|
||||
or (ifnull(${column}, '') not regexp '^[0-9]+$' and u.user_name = ${column})
|
||||
)
|
||||
limit 1
|
||||
)
|
||||
<sql id="feeActorName">
|
||||
case
|
||||
when lower(trim(${column})) = 'system' then '系统自动'
|
||||
else ifnull((
|
||||
select case
|
||||
when nullif(trim(u.nick_name), '') is not null then u.nick_name
|
||||
else u.user_name
|
||||
end
|
||||
from sys_user u
|
||||
where u.del_flag = '0'
|
||||
and (
|
||||
(${column} regexp '^[0-9]+$' and u.user_id = cast(${column} as unsigned))
|
||||
or (ifnull(${column}, '') not regexp '^[0-9]+$' and u.user_name = ${column} COLLATE utf8mb4_general_ci)
|
||||
)
|
||||
limit 1
|
||||
), ${column})
|
||||
end
|
||||
</sql>
|
||||
|
||||
<select id="selectByBillId" parameterType="Long" resultMap="PrcPayBillFeeResult">
|
||||
select f.fee_id, f.bill_id, f.pay_bill_id, f.fee_type, <include refid="feeItemName"/> as fee_name,
|
||||
f.sc_id, f.fee_level, f.amount, f.currency, f.round_mode, f.remark,
|
||||
f.fee_source, f.source_id, f.is_deleted, f.statement_line_id,
|
||||
ifnull(<include refid="feeUserName"><property name="column" value="f.create_by"/></include>, f.create_by) as create_by,
|
||||
<include refid="feeActorName"><property name="column" value="f.create_by"/></include> as create_by,
|
||||
f.create_time,
|
||||
ifnull(<include refid="feeUserName"><property name="column" value="f.update_by"/></include>, f.update_by) as update_by,
|
||||
<include refid="feeActorName"><property name="column" value="f.update_by"/></include> as update_by,
|
||||
f.update_time
|
||||
from prc_pay_bill_fee f
|
||||
<include refid="feeItemJoin"/>
|
||||
@@ -82,9 +85,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
select f.fee_id, f.bill_id, f.pay_bill_id, f.fee_type, <include refid="feeItemName"/> as fee_name,
|
||||
f.sc_id, f.fee_level, f.amount, f.currency, f.round_mode, f.remark,
|
||||
f.fee_source, f.source_id, f.is_deleted, f.statement_line_id,
|
||||
ifnull(<include refid="feeUserName"><property name="column" value="f.create_by"/></include>, f.create_by) as create_by,
|
||||
<include refid="feeActorName"><property name="column" value="f.create_by"/></include> as create_by,
|
||||
f.create_time,
|
||||
ifnull(<include refid="feeUserName"><property name="column" value="f.update_by"/></include>, f.update_by) as update_by,
|
||||
<include refid="feeActorName"><property name="column" value="f.update_by"/></include> as update_by,
|
||||
f.update_time
|
||||
from prc_pay_bill_fee f
|
||||
<include refid="feeItemJoin"/>
|
||||
|
||||
@@ -51,7 +51,18 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
product_code, product_name, goods_description, country_code, country_name, dest_postcode,
|
||||
actual_weight, receive_weight, volume_weight, charge_weight, freight_rate, registration_fee, pkg_length, pkg_width, pkg_height,
|
||||
currency, total_amount, product_amount, redline_amount, billing_fail_status, remark, create_by, create_time
|
||||
from ar_bill_detail where ar_bill_id = #{arBillId} AND EXISTS (SELECT 1 FROM ar_bill b WHERE b.ar_bill_id = ar_bill_detail.ar_bill_id <include refid="com.bms.receivable.mapper.ArBillScopeMapper.billScope"/>)
|
||||
from ar_bill_detail
|
||||
where ar_bill_id = #{arBillId}
|
||||
<if test="query != null and query.orderKeyword != null and query.orderKeyword != ''">
|
||||
and (order_no = #{query.orderKeyword}
|
||||
or tracking_no = #{query.orderKeyword}
|
||||
or transfer_no = #{query.orderKeyword})
|
||||
</if>
|
||||
<if test="query != null and query.productKeyword != null and query.productKeyword != ''">
|
||||
and (product_code like concat('%', #{query.productKeyword}, '%')
|
||||
or product_name like concat('%', #{query.productKeyword}, '%'))
|
||||
</if>
|
||||
AND EXISTS (SELECT 1 FROM ar_bill b WHERE b.ar_bill_id = ar_bill_detail.ar_bill_id <include refid="com.bms.receivable.mapper.ArBillScopeMapper.billScope"/>)
|
||||
order by detail_no
|
||||
</select>
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
+22
-2
@@ -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 <= #{effectiveDate})
|
||||
and (effective_end is null or effective_end >= #{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>
|
||||
|
||||
BIN
Binary file not shown.
@@ -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) {
|
||||
|
||||
@@ -19,6 +19,20 @@
|
||||
|
||||
<!-- 账单明细独立分页;费用明细在展开行时再懒加载。 -->
|
||||
<div class="section-title">账单明细({{ detail.orderCount || 0 }})</div>
|
||||
<el-form :model="detailSearchForm" label-width="44px" size="small" class="detail-search-form" @submit.prevent>
|
||||
<el-form-item label="单号">
|
||||
<el-input v-model="detailSearchForm.orderKeyword" placeholder="订单号、运单号或转单号" clearable
|
||||
:maxlength="64" @keyup.enter="handleDetailSearch" />
|
||||
</el-form-item>
|
||||
<el-form-item label="产品">
|
||||
<el-input v-model="detailSearchForm.productKeyword" placeholder="产品代码或名称" clearable
|
||||
:maxlength="100" @keyup.enter="handleDetailSearch" />
|
||||
</el-form-item>
|
||||
<el-form-item class="detail-search-actions" label-width="0">
|
||||
<el-button type="primary" icon="Search" @click="handleDetailSearch">搜索</el-button>
|
||||
<el-button icon="Refresh" @click="resetDetailSearch">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-table v-loading="detailListLoading" :data="detailRows" row-key="detailId" border size="small" @expand-change="handleExpandChange">
|
||||
<el-table-column type="expand">
|
||||
<template #default="{ row }">
|
||||
@@ -48,18 +62,18 @@
|
||||
<el-table-column prop="redlineAmount" label="整单红线价" width="130" align="right"><template #default="{ row }">{{ amount4(row.redlineAmount) }}</template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="detailTotal > 0"
|
||||
v-if="detailTotal > 0 || appliedDetailQuery.orderKeyword || appliedDetailQuery.productKeyword"
|
||||
class="detail-pagination"
|
||||
v-model:current-page="detailPageNum"
|
||||
v-model:page-size="detailPageSize"
|
||||
:current-page="detailPageNum"
|
||||
:page-size="detailPageSize"
|
||||
:page-sizes="[10, 20, 50]"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
:total="detailTotal"
|
||||
@current-change="loadDetails"
|
||||
@current-change="handleDetailPageChange"
|
||||
@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" />
|
||||
@@ -86,8 +100,10 @@ const detailPageNum = ref(1)
|
||||
// 详情默认每页 10 条,避免几十万条账单明细一次性进入浏览器内存。
|
||||
const detailPageSize = ref(10)
|
||||
const detailListLoading = ref(false)
|
||||
const detailSearchForm = reactive({ orderKeyword: '', productKeyword: '' })
|
||||
// 翻页沿用最后一次搜索的条件,输入中的文本只在点击搜索或回车时应用。
|
||||
const appliedDetailQuery = ref({ orderKeyword: '', productKeyword: '' })
|
||||
let detailRequestSerial = 0
|
||||
const exporting = computed(() => props.detail?.exports?.some(item => item.exportStatus === AR_EXPORT_STATUS.PROCESSING))
|
||||
|
||||
// 切换账单时重置分页和请求序号,旧账单的慢响应不能覆盖新账单。
|
||||
watch(() => props.detail?.arBillId, billId => {
|
||||
@@ -95,6 +111,9 @@ watch(() => props.detail?.arBillId, billId => {
|
||||
detailPageNum.value = 1
|
||||
detailTotal.value = 0
|
||||
detailRows.value = []
|
||||
detailListLoading.value = false
|
||||
Object.assign(detailSearchForm, { orderKeyword: '', productKeyword: '' })
|
||||
appliedDetailQuery.value = { orderKeyword: '', productKeyword: '' }
|
||||
if (billId) loadDetails()
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -104,16 +123,45 @@ function loadDetails() {
|
||||
if (!billId) return
|
||||
const serial = ++detailRequestSerial
|
||||
detailListLoading.value = true
|
||||
listArBillDetails(billId, { pageNum: detailPageNum.value, pageSize: detailPageSize.value }).then(res => {
|
||||
listArBillDetails(billId, {
|
||||
...appliedDetailQuery.value,
|
||||
pageNum: detailPageNum.value,
|
||||
pageSize: detailPageSize.value
|
||||
}).then(res => {
|
||||
if (serial !== detailRequestSerial) return
|
||||
detailRows.value = (res.rows || []).map(row => ({ ...row, fees: [], feesLoaded: false, feeLoading: false }))
|
||||
detailTotal.value = Number(res.total) || 0
|
||||
}).catch(() => {
|
||||
if (serial !== detailRequestSerial) return
|
||||
detailRows.value = []
|
||||
detailTotal.value = 0
|
||||
}).finally(() => {
|
||||
if (serial === detailRequestSerial) detailListLoading.value = false
|
||||
})
|
||||
}
|
||||
|
||||
function handleDetailSearch() {
|
||||
appliedDetailQuery.value = {
|
||||
orderKeyword: detailSearchForm.orderKeyword.trim(),
|
||||
productKeyword: detailSearchForm.productKeyword.trim()
|
||||
}
|
||||
detailPageNum.value = 1
|
||||
loadDetails()
|
||||
}
|
||||
|
||||
function resetDetailSearch() {
|
||||
Object.assign(detailSearchForm, { orderKeyword: '', productKeyword: '' })
|
||||
handleDetailSearch()
|
||||
}
|
||||
|
||||
function handleDetailPageChange(page) {
|
||||
if (page === detailPageNum.value) return
|
||||
detailPageNum.value = page
|
||||
loadDetails()
|
||||
}
|
||||
|
||||
function handleDetailSizeChange(size) {
|
||||
if (size === detailPageSize.value) return
|
||||
detailPageSize.value = size
|
||||
detailPageNum.value = 1
|
||||
loadDetails()
|
||||
@@ -152,6 +200,9 @@ function mask(value) { if (!value) return '-'; return value.length <= 4 ? '****'
|
||||
.section-title::before { content: ''; width: 3px; height: 15px; border-radius: 2px; background: var(--el-color-primary); }
|
||||
.export-title { justify-content: space-between; }
|
||||
.export-title::before { margin-right: auto; }
|
||||
.detail-search-form { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.detail-search-form :deep(.el-form-item) { flex: 1 1 260px; max-width: 360px; margin: 0; }
|
||||
.detail-search-form :deep(.detail-search-actions) { flex: 0 0 auto; max-width: none; }
|
||||
.detail-pagination { justify-content: flex-end; margin: 12px 0 4px; }
|
||||
.fee-panel { min-height: 54px; padding: 4px 12px 8px 42px; background: #fafafa; }
|
||||
.fee-table { background: #fafafa; }
|
||||
|
||||
@@ -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>
|
||||
@@ -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
|
||||
tableRef.value?.refresh()
|
||||
// 导出同样是异步任务;打开详情展示“生成中”状态及完成后的下载入口。
|
||||
viewBill(row)
|
||||
if (exportTask?.exportId) {
|
||||
exportTasks.set(exportTask.exportId, exportTask)
|
||||
startExportPolling(exportTask.exportId)
|
||||
}
|
||||
}).finally(() => {
|
||||
exportSubmittingCount.value = Math.max(0, exportSubmittingCount.value - 1)
|
||||
})
|
||||
exportBillTarget.value = row
|
||||
exportOpen.value = true
|
||||
}
|
||||
|
||||
function handleExportSuccess({ bill, exportTask }) {
|
||||
tableRef.value?.refresh()
|
||||
viewBill(bill)
|
||||
if (exportTask?.exportId) {
|
||||
exportTasks.set(exportTask.exportId, exportTask)
|
||||
startExportPolling(exportTask.exportId)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadActiveGenerateTasks)
|
||||
|
||||
@@ -42,6 +42,9 @@
|
||||
<el-table-column prop="customerName" label="客户" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column prop="productName" label="产品" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column prop="countryName" label="目的国" width="110" show-overflow-tooltip />
|
||||
<el-table-column prop="destPostcode" label="邮编" width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.destPostcode || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="channelName" label="渠道" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column prop="chargeWeight" label="计费重" width="90" align="right" />
|
||||
<el-table-column prop="payTotal" label="应付总额" width="110" align="right">
|
||||
@@ -59,7 +62,7 @@
|
||||
</el-table-column>
|
||||
<el-table-column prop="bizDate" label="计费时间" width="170" align="center" />
|
||||
<el-table-column prop="updateBy" label="更新人" width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.updateBy || '-' }}</template>
|
||||
<template #default="{ row }">{{ actorName(row.updateBy) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updateTime" label="更新时间" width="170" align="center">
|
||||
<template #default="{ row }">{{ row.updateTime || '-' }}</template>
|
||||
@@ -116,10 +119,12 @@
|
||||
<template #default="{ row }">{{ sourceText(row.feeSource) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建人" min-width="1" header-align="center" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.createBy || '-' }}</template>
|
||||
<template #default="{ row }">{{ actorName(row.createBy) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createTime" label="创建时间" min-width="1" header-align="center" show-overflow-tooltip />
|
||||
<el-table-column prop="updateBy" label="更新人" min-width="1" header-align="center" show-overflow-tooltip />
|
||||
<el-table-column label="更新人" min-width="1" header-align="center" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ actorName(row.updateBy) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="updateTime" label="更新时间" min-width="1" header-align="center" show-overflow-tooltip />
|
||||
<el-table-column label="操作" min-width="1" header-align="center" align="center" class-name="fee-op">
|
||||
<template #default="{ row }">
|
||||
@@ -159,7 +164,9 @@
|
||||
<dict-tag :options="bms_pay_fee_log_type" :value="row.operationType" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createBy" label="操作人" width="120" header-align="center" show-overflow-tooltip />
|
||||
<el-table-column label="操作人" width="120" header-align="center" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ actorName(row.createBy) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createTime" label="操作时间" width="170" header-align="center" align="center" />
|
||||
</el-table>
|
||||
<pagination v-show="logTotal > 0" :total="logTotal" v-model:page="logQuery.pageNum" v-model:limit="logQuery.pageSize" @pagination="loadLogs" />
|
||||
@@ -338,6 +345,14 @@ function sourceText(value) {
|
||||
return sources[value] || value || '-'
|
||||
}
|
||||
|
||||
function actorName(value) {
|
||||
const text = value == null ? '' : String(value).trim()
|
||||
if (!text) {
|
||||
return '-'
|
||||
}
|
||||
return text.toLowerCase() === 'system' ? '系统自动' : text
|
||||
}
|
||||
|
||||
function logLines(row, side) {
|
||||
const name = row?.[side + 'FeeName']
|
||||
const amount = row?.[side + 'Amount']
|
||||
|
||||
Reference in New Issue
Block a user