Merge branch 'test' of https://git.lionquexpress.com/wuweihua/BMS into test
This commit is contained in:
@@ -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.
Reference in New Issue
Block a user