16 changed files with 1141 additions and 0 deletions
-
67src/main/java/com/xujie/modules/inspection/expense/controller/ExpenseReportController.java
-
21src/main/java/com/xujie/modules/inspection/expense/data/ExpenseDetail.java
-
13src/main/java/com/xujie/modules/inspection/expense/data/ExpenseDocument.java
-
17src/main/java/com/xujie/modules/inspection/expense/data/ExpenseExportQuery.java
-
39src/main/java/com/xujie/modules/inspection/expense/data/ExpenseHeader.java
-
10src/main/java/com/xujie/modules/inspection/expense/data/ExpenseOption.java
-
18src/main/java/com/xujie/modules/inspection/expense/data/ExpenseQuery.java
-
26src/main/java/com/xujie/modules/inspection/expense/data/ExpenseTrip.java
-
32src/main/java/com/xujie/modules/inspection/expense/mapper/ExpenseReportMapper.java
-
16src/main/java/com/xujie/modules/inspection/expense/service/ExpenseReportService.java
-
335src/main/java/com/xujie/modules/inspection/expense/service/ExpenseReportServiceImpl.java
-
42src/main/java/com/xujie/modules/inspection/expense/support/ExpenseLocalDateTimeTypeHandler.java
-
42src/main/java/com/xujie/modules/inspection/expense/support/ExpenseLocalDateTypeHandler.java
-
330src/main/java/com/xujie/modules/inspection/expense/support/ExpenseWorkbookWriter.java
-
133src/main/resources/mapper/inspection/ExpenseReportMapper.xml
-
BINsrc/main/resources/static/excel/费用管理模板.xlsx
@ -0,0 +1,67 @@ |
|||
package com.xujie.modules.inspection.expense.controller; |
|||
|
|||
import com.xujie.common.utils.R; |
|||
import com.xujie.modules.inspection.expense.data.*; |
|||
import com.xujie.modules.inspection.expense.service.ExpenseReportService; |
|||
import org.apache.shiro.authz.annotation.RequiresPermissions; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.http.HttpHeaders; |
|||
import org.springframework.http.MediaType; |
|||
import org.springframework.http.ResponseEntity; |
|||
import org.springframework.web.bind.annotation.*; |
|||
import java.net.URLEncoder; |
|||
import java.nio.charset.StandardCharsets; |
|||
|
|||
/** 新版费用接口,旧 /inspection/fee 保持原有调用方式 - rqrq。 */ |
|||
@RestController |
|||
@RequestMapping("/inspection/expenseReport") |
|||
public class ExpenseReportController { |
|||
@Autowired private ExpenseReportService service; |
|||
|
|||
@PostMapping("/list") |
|||
@RequiresPermissions("inspection:expenseReport:list") |
|||
public R list(@RequestBody ExpenseQuery query) { |
|||
return R.ok().put("page", service.search(query)); |
|||
} |
|||
|
|||
@PostMapping("/detail") |
|||
@RequiresPermissions("inspection:expenseReport:list") |
|||
public R detail(@RequestBody ExpenseQuery query) { |
|||
return R.ok().put("row", service.getDocument(query)); |
|||
} |
|||
|
|||
@PostMapping("/save") |
|||
@RequiresPermissions("inspection:expenseReport:save") |
|||
public R save(@RequestBody ExpenseDocument document) { |
|||
return R.ok().put("row", service.save(document)); |
|||
} |
|||
|
|||
@PostMapping("/delete") |
|||
@RequiresPermissions("inspection:expenseReport:delete") |
|||
public R delete(@RequestBody ExpenseQuery query) { |
|||
service.delete(query); |
|||
return R.ok(); |
|||
} |
|||
|
|||
@PostMapping("/types") |
|||
@RequiresPermissions("inspection:expenseReport:list") |
|||
public R types(@RequestBody ExpenseQuery query) { |
|||
return R.ok().put("rows", service.getTypes(query)); |
|||
} |
|||
|
|||
@PostMapping("/users") |
|||
@RequiresPermissions("inspection:expenseReport:list") |
|||
public R users(@RequestBody ExpenseQuery query) { |
|||
return R.ok().put("rows", service.getUsers(query)); |
|||
} |
|||
|
|||
@PostMapping("/export") |
|||
@RequiresPermissions("inspection:expenseReport:export") |
|||
public ResponseEntity<byte[]> export(@RequestBody ExpenseExportQuery query) { |
|||
byte[] bytes = service.export(query); |
|||
String filename = URLEncoder.encode("费用报销单.xlsx", StandardCharsets.UTF_8).replace("+", "%20"); |
|||
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename) |
|||
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) |
|||
.contentLength(bytes.length).body(bytes); |
|||
} |
|||
} |
|||
@ -0,0 +1,21 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import lombok.Data; |
|||
import java.math.BigDecimal; |
|||
import java.time.LocalDateTime; |
|||
|
|||
/** 共用费用明细 srm_fee_detail,主键 site + fee_no + item_no - rqrq。 */ |
|||
@Data |
|||
public class ExpenseDetail { |
|||
private String site; |
|||
private String feeNo; |
|||
private Integer itemNo; |
|||
/** 字典 fee_type 的业务值,四个固定类型使用中文值兼容旧界面 - rqrq。 */ |
|||
private String feeType; |
|||
private String feeTypeName; |
|||
private BigDecimal amount; |
|||
private String remark; |
|||
/** 整单编辑时保留原创建审计信息,不接受前端覆盖 - rqrq。 */ |
|||
private String createBy; |
|||
private LocalDateTime createDate; |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import lombok.Data; |
|||
import java.util.List; |
|||
|
|||
/** 一次保存主记录和两种子记录;申请单关联通过原有独立页签维护 - rqrq。 */ |
|||
@Data |
|||
public class ExpenseDocument { |
|||
private ExpenseHeader header; |
|||
private List<ExpenseDetail> details; |
|||
private List<ExpenseTrip> trips; |
|||
private List<String> requestNos; |
|||
} |
|||
@ -0,0 +1,17 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import lombok.Data; |
|||
import java.time.LocalDate; |
|||
import java.util.List; |
|||
|
|||
/** 多选联合导出;表头内容由导出弹窗确认 - rqrq。 */ |
|||
@Data |
|||
public class ExpenseExportQuery { |
|||
private String site; |
|||
private List<String> feeNos; |
|||
private LocalDate reportDate; |
|||
private LocalDate tripStartDate; |
|||
private LocalDate tripEndDate; |
|||
/** 兼容旧版导出请求;新版不再将出差事由写入 Excel,由报销人手工填写 - rqrq。 */ |
|||
private String tripReason; |
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import com.baomidou.mybatisplus.annotation.TableName; |
|||
import com.baomidou.mybatisplus.annotation.TableField; |
|||
import com.fasterxml.jackson.annotation.JsonFormat; |
|||
import lombok.Data; |
|||
import java.math.BigDecimal; |
|||
import java.time.LocalDate; |
|||
import java.time.LocalDateTime; |
|||
|
|||
/** 新版费用视图,共用 srm_fee_header,主键 site + fee_no - rqrq。 */ |
|||
@Data |
|||
@TableName("srm_fee_header") |
|||
public class ExpenseHeader { |
|||
private String site; |
|||
private String feeNo; |
|||
@JsonFormat(pattern = "yyyy-MM-dd") |
|||
private LocalDate feeDate; |
|||
private String applyUser; |
|||
/** 查询用户姓名,避免导出显示账号 - rqrq。 */ |
|||
@TableField(exist = false) |
|||
private String applyUserName; |
|||
private String startPlace; |
|||
private String endPlace; |
|||
private BigDecimal tripDays; |
|||
private String tripReason; |
|||
private String remark; |
|||
/** 仅费用明细金额合计,行程附件金额不参与 - rqrq。 */ |
|||
private BigDecimal totalAmount; |
|||
/** 乐观锁版本,拒绝覆盖他人已保存的修改 - rqrq。 */ |
|||
@TableField(exist = false) |
|||
private String version; |
|||
private String createdBy; |
|||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") |
|||
private LocalDateTime createdDate; |
|||
private String updateBy; |
|||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") |
|||
private LocalDateTime updateDate; |
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import lombok.Data; |
|||
|
|||
/** 新版费用类型/申请人下拉,编码入库、名称显示 - rqrq。 */ |
|||
@Data |
|||
public class ExpenseOption { |
|||
private String value; |
|||
private String label; |
|||
} |
|||
@ -0,0 +1,18 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import com.xujie.common.utils.QueryPage; |
|||
import lombok.Data; |
|||
import lombok.EqualsAndHashCode; |
|||
import java.time.LocalDate; |
|||
|
|||
/** 新版费用查询/定位参数;site 必须显式传入 - rqrq。 */ |
|||
@Data |
|||
@EqualsAndHashCode(callSuper = true) |
|||
public class ExpenseQuery extends QueryPage { |
|||
private String site; |
|||
private String feeNo; |
|||
private String applyUser; |
|||
private LocalDate dateStart; |
|||
private LocalDate dateEnd; |
|||
private String version; |
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
package com.xujie.modules.inspection.expense.data; |
|||
|
|||
import com.fasterxml.jackson.annotation.JsonFormat; |
|||
import lombok.Data; |
|||
import java.math.BigDecimal; |
|||
import java.time.LocalDate; |
|||
import java.time.LocalDateTime; |
|||
|
|||
/** 新增行程附件 srm_fee_trip_detail,主键 site + fee_no + item_no;独立金额 - rqrq。 */ |
|||
@Data |
|||
public class ExpenseTrip { |
|||
private String site; |
|||
private String feeNo; |
|||
private Integer itemNo; |
|||
@JsonFormat(pattern = "yyyy-MM-dd") |
|||
private LocalDate tripDate; |
|||
private String startPlace; |
|||
private String endPlace; |
|||
private String expenseDesc; |
|||
private String vehicle; |
|||
private Integer billCount; |
|||
private BigDecimal mileage; |
|||
private BigDecimal amount; |
|||
private String createBy; |
|||
private LocalDateTime createDate; |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
package com.xujie.modules.inspection.expense.mapper; |
|||
|
|||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
|||
import com.baomidou.mybatisplus.core.metadata.IPage; |
|||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; |
|||
import com.xujie.modules.inspection.expense.data.*; |
|||
import org.apache.ibatis.annotations.Mapper; |
|||
import org.apache.ibatis.annotations.Param; |
|||
import java.util.List; |
|||
|
|||
/** 新版费用专用 Mapper,共用原费用表并增加行程子表 - rqrq。 */ |
|||
@Mapper |
|||
public interface ExpenseReportMapper extends BaseMapper<ExpenseHeader> { |
|||
IPage<ExpenseHeader> search(Page<ExpenseHeader> page, @Param("query") ExpenseQuery query); |
|||
ExpenseHeader getHeader(@Param("site") String site, @Param("feeNo") String feeNo); |
|||
List<ExpenseHeader> exportHeaders(@Param("site") String site, @Param("feeNos") List<String> feeNos); |
|||
List<ExpenseDetail> getDetails(@Param("site") String site, @Param("feeNos") List<String> feeNos); |
|||
List<ExpenseTrip> getTrips(@Param("site") String site, @Param("feeNos") List<String> feeNos); |
|||
List<String> getRequestNos(@Param("site") String site, @Param("feeNo") String feeNo); |
|||
List<ExpenseOption> getTypes(@Param("site") String site); |
|||
List<ExpenseOption> getUsers(@Param("site") String site); |
|||
int insertHeader(ExpenseHeader header); |
|||
int updateHeader(ExpenseHeader header); |
|||
int deleteHeader(ExpenseQuery query); |
|||
int deleteDetails(@Param("site") String site, @Param("feeNo") String feeNo); |
|||
int deleteTrips(@Param("site") String site, @Param("feeNo") String feeNo); |
|||
int deleteRequests(@Param("site") String site, @Param("feeNo") String feeNo); |
|||
int insertDetails(@Param("site") String site, @Param("feeNo") String feeNo, |
|||
@Param("rows") List<ExpenseDetail> rows, @Param("operator") String operator); |
|||
int insertTrips(@Param("site") String site, @Param("feeNo") String feeNo, |
|||
@Param("rows") List<ExpenseTrip> rows, @Param("operator") String operator); |
|||
} |
|||
@ -0,0 +1,16 @@ |
|||
package com.xujie.modules.inspection.expense.service; |
|||
|
|||
import com.xujie.common.utils.PageUtils; |
|||
import com.xujie.modules.inspection.expense.data.*; |
|||
import java.util.List; |
|||
|
|||
/** 新版费用独立业务入口 - rqrq。 */ |
|||
public interface ExpenseReportService { |
|||
PageUtils search(ExpenseQuery query); |
|||
ExpenseDocument getDocument(ExpenseQuery query); |
|||
ExpenseHeader save(ExpenseDocument document); |
|||
void delete(ExpenseQuery query); |
|||
List<ExpenseOption> getTypes(ExpenseQuery query); |
|||
List<ExpenseOption> getUsers(ExpenseQuery query); |
|||
byte[] export(ExpenseExportQuery query); |
|||
} |
|||
@ -0,0 +1,335 @@ |
|||
package com.xujie.modules.inspection.expense.service; |
|||
|
|||
import com.xujie.common.utils.PageUtils; |
|||
import com.xujie.common.utils.ShiroUtils; |
|||
import com.xujie.modules.inspection.expense.data.*; |
|||
import com.xujie.modules.inspection.expense.mapper.ExpenseReportMapper; |
|||
import com.xujie.modules.inspection.expense.support.ExpenseWorkbookWriter; |
|||
import com.xujie.modules.srm.mapper.SrmSupplierMapper; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.stereotype.Service; |
|||
import org.springframework.transaction.annotation.Isolation; |
|||
import org.springframework.transaction.annotation.Transactional; |
|||
import org.springframework.util.StringUtils; |
|||
import java.math.BigDecimal; |
|||
import java.math.RoundingMode; |
|||
import java.util.*; |
|||
import java.util.stream.Collectors; |
|||
|
|||
/** 新版费用业务:独立接口,共用原费用数据 - rqrq。 */ |
|||
@Slf4j |
|||
@Service |
|||
public class ExpenseReportServiceImpl implements ExpenseReportService { |
|||
public static final List<String> REPORT_TYPES = Arrays.asList("交通费", "住宿费", "住宿节约补助", "补助"); |
|||
private static final BigDecimal MAX_AMOUNT = new BigDecimal("999999999999.99"); |
|||
@Autowired private ExpenseReportMapper mapper; |
|||
@Autowired private SrmSupplierMapper numberMapper; |
|||
@Autowired private ExpenseWorkbookWriter workbookWriter; |
|||
|
|||
@Override |
|||
public PageUtils search(ExpenseQuery query) { |
|||
validateQuery(query, false); |
|||
if (query.getDateStart() != null && query.getDateEnd() != null |
|||
&& query.getDateStart().isAfter(query.getDateEnd())) { |
|||
throw new RuntimeException("开始日期不能晚于结束日期"); |
|||
} |
|||
return new PageUtils(mapper.search(query.toMybatisPage(), query)); |
|||
} |
|||
|
|||
@Override |
|||
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) |
|||
public ExpenseDocument getDocument(ExpenseQuery query) { |
|||
validateQuery(query, true); |
|||
ExpenseHeader header = requireHeader(query.getSite(), query.getFeeNo()); |
|||
ExpenseDocument document = new ExpenseDocument(); |
|||
document.setHeader(header); |
|||
document.setDetails(mapper.getDetails(query.getSite(), Collections.singletonList(query.getFeeNo()))); |
|||
document.setTrips(mapper.getTrips(query.getSite(), Collections.singletonList(query.getFeeNo()))); |
|||
document.setRequestNos(mapper.getRequestNos(query.getSite(), query.getFeeNo())); |
|||
return document; |
|||
} |
|||
|
|||
/** |
|||
* 保存费用主记录及两种明细 - rqrq。 |
|||
* 目标:同一事务内保存整单,金额先逐行 HALF_UP 到两位,再汇总费用明细。 |
|||
* 前置:显式 site、必填业务字段、合法费用类型;编辑必须带读取时的行版本。 |
|||
* 步骤:校验整单、校验类型/申请人、生成单号或锁定主行、分批替换两种明细。 |
|||
* 事务:任意校验或 SQL 失败全部回滚;不替换申请单关联,原页签独立维护该关系。 |
|||
* 失败策略:旧页面/其他用户已修改主记录时,拒绝覆盖并提示刷新。 |
|||
*/ |
|||
@Override |
|||
@Transactional(rollbackFor = Exception.class) |
|||
public ExpenseHeader save(ExpenseDocument document) { |
|||
// 1) 先校验完整入参,防止缺失数组被误认为删除全部子记录 - rqrq。 |
|||
if (document == null || document.getHeader() == null |
|||
|| document.getDetails() == null || document.getTrips() == null) { |
|||
throw new RuntimeException("费用主记录、费用明细和行程明细必须完整提交"); |
|||
} |
|||
ExpenseHeader h = document.getHeader(); |
|||
h.setSite(required(h.getSite(), 50, "站点")); |
|||
log.info("开始保存新版费用 - rqrq,site={}, feeNo={}", h.getSite(), h.getFeeNo()); |
|||
boolean creating = !StringUtils.hasText(h.getFeeNo()); |
|||
ExpenseHeader original = creating ? null : requireHeader(h.getSite(), required(h.getFeeNo(), 50, "费用单号")); |
|||
if (h.getFeeDate() == null) { |
|||
throw new RuntimeException("费用日期不能为空"); |
|||
} |
|||
h.setApplyUser(required(h.getApplyUser(), 50, "申请人")); |
|||
h.setStartPlace(required(h.getStartPlace(), 200, "起始地点")); |
|||
h.setEndPlace(required(h.getEndPlace(), 200, "终点地点")); |
|||
h.setTripReason(required(h.getTripReason(), 500, "出差事由")); |
|||
h.setRemark(optional(h.getRemark(), 250, "备注")); |
|||
if (h.getTripDays() == null || h.getTripDays().signum() <= 0 || h.getTripDays().compareTo(new BigDecimal("9999.99")) > 0) { |
|||
throw new RuntimeException("天数必须大于 0 且不超过 9999.99"); |
|||
} |
|||
h.setTripDays(h.getTripDays().setScale(2, RoundingMode.HALF_UP)); |
|||
if (h.getTripDays().signum() <= 0) { |
|||
throw new RuntimeException("天数保留两位小数后必须大于 0"); |
|||
} |
|||
if (document.getDetails().size() > 1000 || document.getTrips().size() > 1000) { |
|||
throw new RuntimeException("单张费用单每种明细最多 1000 行"); |
|||
} |
|||
|
|||
// 2) 只允许新增时选择有效用户;编辑保留已离职申请人,避免历史单据无法补资料 - rqrq。 |
|||
boolean validUser = mapper.getUsers(h.getSite()).stream().anyMatch(u -> u.getValue().equals(h.getApplyUser())); |
|||
if (!validUser && (original == null || !Objects.equals(original.getApplyUser(), h.getApplyUser()))) { |
|||
throw new RuntimeException("申请人不存在、已停用或不属于当前站点"); |
|||
} |
|||
List<ExpenseOption> options = typeOptions(h.getSite()); |
|||
// key 为去除首尾空格后的字典业务值;只接受启用类型或本行原来使用的历史类型 - rqrq。 |
|||
Map<String, String> typeNames = options.stream().collect(Collectors.toMap(ExpenseOption::getValue, |
|||
ExpenseOption::getLabel, (first, next) -> first, LinkedHashMap::new)); |
|||
Map<Integer, ExpenseDetail> existing = new HashMap<>(); |
|||
Map<Integer, ExpenseTrip> existingTrips = new HashMap<>(); |
|||
if (!creating) { |
|||
mapper.getDetails(h.getSite(), Collections.singletonList(h.getFeeNo())) |
|||
.forEach(d -> existing.put(d.getItemNo(), d)); |
|||
mapper.getTrips(h.getSite(), Collections.singletonList(h.getFeeNo())) |
|||
.forEach(t -> existingTrips.put(t.getItemNo(), t)); |
|||
} |
|||
BigDecimal total = BigDecimal.ZERO.setScale(2); |
|||
int line = 0; |
|||
for (ExpenseDetail d : document.getDetails()) { |
|||
if (d == null) { |
|||
throw new RuntimeException("费用明细不能包含空记录"); |
|||
} |
|||
String type = required(d.getFeeType(), 25, "费用类型"); |
|||
ExpenseDetail previous = existing.get(d.getItemNo()); |
|||
boolean historicalType = previous != null && type.equals(trim(previous.getFeeType())); |
|||
if (!typeNames.containsKey(type) && !historicalType) { |
|||
throw new RuntimeException("费用类型未维护或已停用:" + type); |
|||
} |
|||
// 先按分舍入,再相加;不信任前端提交的主记录合计 - rqrq。 |
|||
d.setAmount(amount(d.getAmount(), "费用金额")); |
|||
d.setFeeType(type); |
|||
d.setRemark(optional(d.getRemark(), 250, "费用备注")); |
|||
// 原有行保留创建人和时间;新行的创建信息交由服务端产生 - rqrq。 |
|||
d.setCreateBy(previous == null ? null : previous.getCreateBy()); |
|||
d.setCreateDate(previous == null ? null : previous.getCreateDate()); |
|||
d.setItemNo(++line); |
|||
total = total.add(d.getAmount()); |
|||
} |
|||
h.setTotalAmount(amount(total, "总金额")); |
|||
line = 0; |
|||
for (ExpenseTrip t : document.getTrips()) { |
|||
if (t == null || t.getTripDate() == null) { |
|||
throw new RuntimeException("行程日期不能为空"); |
|||
} |
|||
t.setStartPlace(required(t.getStartPlace(), 200, "行程出发地")); |
|||
t.setEndPlace(required(t.getEndPlace(), 200, "行程到达地")); |
|||
t.setExpenseDesc(required(t.getExpenseDesc(), 500, "行程费用说明")); |
|||
t.setVehicle(required(t.getVehicle(), 50, "交通工具")); |
|||
if (t.getBillCount() == null || t.getBillCount() < 0 || t.getBillCount() > 1000000) { |
|||
throw new RuntimeException("票据数必须是 0~1000000 的整数"); |
|||
} |
|||
t.setMileage(amount(t.getMileage(), "里程")); |
|||
t.setAmount(amount(t.getAmount(), "行程金额")); |
|||
ExpenseTrip previousTrip = existingTrips.get(t.getItemNo()); |
|||
t.setCreateBy(previousTrip == null ? null : previousTrip.getCreateBy()); |
|||
t.setCreateDate(previousTrip == null ? null : previousTrip.getCreateDate()); |
|||
t.setItemNo(++line); |
|||
} |
|||
|
|||
// 3) 主行先写入并持有事务锁;rowversion 自动兼容原页面对主表的更新 - rqrq。 |
|||
String operator = ShiroUtils.getUserEntity().getUsername(); |
|||
h.setUpdateBy(operator); |
|||
if (creating) { |
|||
// 共用原有 FEE 单号序列,不另起重复的号码体系 - rqrq。 |
|||
numberMapper.updateTransNo(h.getSite(), "FEE"); |
|||
h.setFeeNo(required(numberMapper.getTransNo(h.getSite(), "FEE"), 50, "费用单号")); |
|||
h.setCreatedBy(operator); |
|||
mapper.insertHeader(h); |
|||
} else { |
|||
validateVersion(h.getVersion()); |
|||
if (mapper.updateHeader(h) != 1) { |
|||
throw new RuntimeException("费用记录已被修改或删除,请刷新后重新编辑"); |
|||
} |
|||
} |
|||
|
|||
// 4) 两种明细分别保存;每批 100 行,低于 SQL Server 的 2100 参数限制 - rqrq。 |
|||
mapper.deleteDetails(h.getSite(), h.getFeeNo()); |
|||
mapper.deleteTrips(h.getSite(), h.getFeeNo()); |
|||
for (int i = 0; i < document.getDetails().size(); i += 100) { |
|||
mapper.insertDetails(h.getSite(), h.getFeeNo(), document.getDetails().subList(i, |
|||
Math.min(i + 100, document.getDetails().size())), operator); |
|||
} |
|||
for (int i = 0; i < document.getTrips().size(); i += 100) { |
|||
mapper.insertTrips(h.getSite(), h.getFeeNo(), document.getTrips().subList(i, |
|||
Math.min(i + 100, document.getTrips().size())), operator); |
|||
} |
|||
log.info("保存新版费用完成 - rqrq,site={}, feeNo={}", h.getSite(), h.getFeeNo()); |
|||
return requireHeader(h.getSite(), h.getFeeNo()); |
|||
} |
|||
|
|||
/** |
|||
* 删除整单 - rqrq。前置:site、单号、读取时版本;先匹配版本删除主行,再删旧子记录。 |
|||
* 行程由外键级联删除,原页面删除主记录时也适用;其余删除失败均回滚整笔事务。 |
|||
*/ |
|||
@Override |
|||
@Transactional(rollbackFor = Exception.class) |
|||
public void delete(ExpenseQuery query) { |
|||
validateQuery(query, true); |
|||
validateVersion(query.getVersion()); |
|||
log.info("开始删除费用 - rqrq,site={}, feeNo={}", query.getSite(), query.getFeeNo()); |
|||
if (mapper.deleteHeader(query) != 1) { |
|||
throw new RuntimeException("费用记录已被修改或删除,请刷新后重试"); |
|||
} |
|||
mapper.deleteDetails(query.getSite(), query.getFeeNo()); |
|||
mapper.deleteRequests(query.getSite(), query.getFeeNo()); |
|||
log.info("删除费用完成 - rqrq,feeNo={}", query.getFeeNo()); |
|||
} |
|||
|
|||
@Override |
|||
public List<ExpenseOption> getTypes(ExpenseQuery query) { |
|||
validateQuery(query, false); |
|||
return typeOptions(query.getSite()); |
|||
} |
|||
|
|||
@Override |
|||
public List<ExpenseOption> getUsers(ExpenseQuery query) { |
|||
validateQuery(query, false); |
|||
return mapper.getUsers(query.getSite()); |
|||
} |
|||
|
|||
/** |
|||
* 多选费用模板导出 - rqrq。 |
|||
* 目标:第一张表每张费用单一行,第二张表合并行程但不重复计入费用。 |
|||
* 前置:同站点、同申请人、同年度;完整日期/地点/天数,明确的填报日期及出差区间。 |
|||
* 步骤:校验选择、批量读取三组数据、校验表头与范围、交给模板写入器扩行和重算。 |
|||
* 事务:只读可重复读保证本次查询中已读记录不被改写;不修改数据库或原模板。 |
|||
* 失败策略:任何单据缺失/范围错误/模板格式错误时整次失败,不静默导出部分单据。 |
|||
*/ |
|||
@Override |
|||
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) |
|||
public byte[] export(ExpenseExportQuery query) { |
|||
if (query == null) { |
|||
throw new RuntimeException("导出参数不能为空"); |
|||
} |
|||
query.setSite(required(query.getSite(), 50, "站点")); |
|||
if (query.getFeeNos() == null || query.getFeeNos().isEmpty() || query.getFeeNos().size() > 500) { |
|||
throw new RuntimeException("请选择 1~500 张费用单"); |
|||
} |
|||
// 单号按完整文本去重,避免重复选择导致费用翻倍 - rqrq。 |
|||
List<String> nos = query.getFeeNos().stream().map(n -> required(n, 50, "费用单号")).distinct().collect(Collectors.toList()); |
|||
if (query.getReportDate() == null || query.getTripStartDate() == null || query.getTripEndDate() == null |
|||
|| query.getTripStartDate().isAfter(query.getTripEndDate())) { |
|||
throw new RuntimeException("请填写有效的填报日期和出差起止日期"); |
|||
} |
|||
// 出差事由由报销人在导出的 Excel 模板内手工填写,旧请求即使携带该参数也不再参与校验或写入 - rqrq。 |
|||
log.info("开始导出费用 - rqrq,site={}, 单数={}", query.getSite(), nos.size()); |
|||
List<ExpenseHeader> headers = mapper.exportHeaders(query.getSite(), nos); |
|||
if (headers.size() != nos.size()) { |
|||
throw new RuntimeException("部分费用单不存在或不属于当前站点,请刷新后重新选择"); |
|||
} |
|||
ExpenseHeader first = headers.get(0); |
|||
for (ExpenseHeader h : headers) { |
|||
if (h.getFeeDate() == null || !StringUtils.hasText(h.getApplyUser()) || !StringUtils.hasText(h.getStartPlace()) |
|||
|| !StringUtils.hasText(h.getEndPlace()) || h.getTripDays() == null || h.getTripDays().signum() <= 0) { |
|||
throw new RuntimeException("费用单 " + h.getFeeNo() + " 缺少日期、申请人、地点或天数,请先补齐"); |
|||
} |
|||
if (!Objects.equals(first.getApplyUser(), h.getApplyUser())) { |
|||
throw new RuntimeException("同一份报销单只能选择同一申请人的记录"); |
|||
} |
|||
if (h.getFeeDate().getYear() != first.getFeeDate().getYear()) { |
|||
throw new RuntimeException("模板费用日期仅显示月日,请将不同年度的记录分别导出"); |
|||
} |
|||
if (h.getFeeDate().isBefore(query.getTripStartDate()) || h.getFeeDate().isAfter(query.getTripEndDate())) { |
|||
throw new RuntimeException("出差起止日期必须覆盖所选费用日期"); |
|||
} |
|||
} |
|||
// 两张子表分别批量读取,避免一对多相乘造成金额重复,也不逐单查询 - rqrq。 |
|||
List<ExpenseDetail> details = mapper.getDetails(query.getSite(), nos); |
|||
List<ExpenseTrip> trips = mapper.getTrips(query.getSite(), nos); |
|||
if (trips.size() > 20000) { |
|||
throw new RuntimeException("行程超过 20000 行,请分批导出"); |
|||
} |
|||
byte[] result = workbookWriter.write(query, headers, details, trips); |
|||
log.info("导出费用完成 - rqrq,费用行={}, 行程行={}", headers.size(), trips.size()); |
|||
return result; |
|||
} |
|||
|
|||
private List<ExpenseOption> typeOptions(String site) { |
|||
// 四种模板类型固定可用;字典补充其他类型,避免删除字典后模板类型消失 - rqrq。 |
|||
Map<String, ExpenseOption> options = new LinkedHashMap<>(); |
|||
for (String type : REPORT_TYPES) { |
|||
ExpenseOption option = new ExpenseOption(); |
|||
option.setValue(type); |
|||
option.setLabel(type); |
|||
options.put(type, option); |
|||
} |
|||
for (ExpenseOption option : mapper.getTypes(site)) { |
|||
options.putIfAbsent(option.getValue(), option); |
|||
} |
|||
return new ArrayList<>(options.values()); |
|||
} |
|||
|
|||
private ExpenseHeader requireHeader(String site, String feeNo) { |
|||
ExpenseHeader header = mapper.getHeader(site, feeNo); |
|||
if (header == null) { |
|||
throw new RuntimeException("费用单不存在:" + feeNo); |
|||
} |
|||
return header; |
|||
} |
|||
|
|||
private void validateQuery(ExpenseQuery query, boolean needNo) { |
|||
if (query == null) { |
|||
throw new RuntimeException("请求参数不能为空"); |
|||
} |
|||
query.setSite(required(query.getSite(), 50, "站点")); |
|||
if (needNo) { |
|||
query.setFeeNo(required(query.getFeeNo(), 50, "费用单号")); |
|||
} |
|||
} |
|||
|
|||
private void validateVersion(String version) { |
|||
if (version == null || !version.matches("[0-9A-Fa-f]{16}")) { |
|||
throw new RuntimeException("费用记录版本无效,请刷新后重试"); |
|||
} |
|||
} |
|||
|
|||
public static BigDecimal amount(BigDecimal value, String label) { |
|||
if (value == null || value.signum() < 0 || value.compareTo(MAX_AMOUNT) > 0) { |
|||
throw new RuntimeException(label + "不能为空、不能为负数,且不能超过 " + MAX_AMOUNT); |
|||
} |
|||
return value.setScale(2, RoundingMode.HALF_UP); |
|||
} |
|||
|
|||
private String required(String value, int max, String label) { |
|||
if (!StringUtils.hasText(value)) { |
|||
throw new RuntimeException(label + "不能为空"); |
|||
} |
|||
return optional(value, max, label); |
|||
} |
|||
|
|||
private String optional(String value, int max, String label) { |
|||
String text = trim(value); |
|||
if (text.length() > max) { |
|||
throw new RuntimeException(label + "最多 " + max + " 个字符"); |
|||
} |
|||
return text; |
|||
} |
|||
|
|||
private String trim(String value) { |
|||
return value == null ? "" : value.trim(); |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
package com.xujie.modules.inspection.expense.support; |
|||
|
|||
import org.apache.ibatis.type.BaseTypeHandler; |
|||
import org.apache.ibatis.type.JdbcType; |
|||
|
|||
import java.sql.CallableStatement; |
|||
import java.sql.PreparedStatement; |
|||
import java.sql.ResultSet; |
|||
import java.sql.SQLException; |
|||
import java.sql.Timestamp; |
|||
import java.time.LocalDateTime; |
|||
|
|||
/** |
|||
* 费用模块的审计时间兼容映射 - rqrq。 |
|||
* 使用旧 SQL Server 驱动支持的 getTimestamp/setTimestamp,保留原创建时间及 SQL NULL。 |
|||
* 仅由 ExpenseReportMapper 显式引用,不改变其他模块的日期时间映射。 |
|||
*/ |
|||
public class ExpenseLocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> { |
|||
@Override |
|||
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) |
|||
throws SQLException { |
|||
ps.setTimestamp(i, Timestamp.valueOf(parameter)); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { |
|||
Timestamp timestamp = rs.getTimestamp(columnName); |
|||
return timestamp == null ? null : timestamp.toLocalDateTime(); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException { |
|||
Timestamp timestamp = rs.getTimestamp(columnIndex); |
|||
return timestamp == null ? null : timestamp.toLocalDateTime(); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { |
|||
Timestamp timestamp = cs.getTimestamp(columnIndex); |
|||
return timestamp == null ? null : timestamp.toLocalDateTime(); |
|||
} |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
package com.xujie.modules.inspection.expense.support; |
|||
|
|||
import org.apache.ibatis.type.BaseTypeHandler; |
|||
import org.apache.ibatis.type.JdbcType; |
|||
|
|||
import java.sql.CallableStatement; |
|||
import java.sql.Date; |
|||
import java.sql.PreparedStatement; |
|||
import java.sql.ResultSet; |
|||
import java.sql.SQLException; |
|||
import java.time.LocalDate; |
|||
|
|||
/** |
|||
* 费用模块的日期兼容映射 - rqrq。 |
|||
* 项目 sqljdbc6-4.1 不支持 JDBC 4.2 的 LocalDate getObject/setObject;改用 getDate/setDate。 |
|||
* 仅由 ExpenseReportMapper 显式引用,不注册为全局处理器;SQL NULL 保持为 null。 |
|||
*/ |
|||
public class ExpenseLocalDateTypeHandler extends BaseTypeHandler<LocalDate> { |
|||
@Override |
|||
public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType) |
|||
throws SQLException { |
|||
ps.setDate(i, Date.valueOf(parameter)); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException { |
|||
Date date = rs.getDate(columnName); |
|||
return date == null ? null : date.toLocalDate(); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDate getNullableResult(ResultSet rs, int columnIndex) throws SQLException { |
|||
Date date = rs.getDate(columnIndex); |
|||
return date == null ? null : date.toLocalDate(); |
|||
} |
|||
|
|||
@Override |
|||
public LocalDate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { |
|||
Date date = cs.getDate(columnIndex); |
|||
return date == null ? null : date.toLocalDate(); |
|||
} |
|||
} |
|||
@ -0,0 +1,330 @@ |
|||
package com.xujie.modules.inspection.expense.support; |
|||
|
|||
import com.xujie.modules.inspection.expense.data.*; |
|||
import com.xujie.modules.inspection.expense.service.ExpenseReportServiceImpl; |
|||
import org.apache.poi.ss.usermodel.*; |
|||
import org.apache.poi.ss.util.CellRangeAddress; |
|||
import org.apache.poi.ss.util.CellReference; |
|||
import org.springframework.core.io.ClassPathResource; |
|||
import org.springframework.stereotype.Component; |
|||
import java.io.ByteArrayOutputStream; |
|||
import java.io.InputStream; |
|||
import java.math.BigDecimal; |
|||
import java.math.RoundingMode; |
|||
import java.time.LocalDate; |
|||
import java.util.*; |
|||
|
|||
/** 按现有费用模板生成双页签文件;原始资源只读、每次独立 Workbook - rqrq。 */ |
|||
@Component |
|||
public class ExpenseWorkbookWriter { |
|||
private static final String TEMPLATE = "static/excel/费用管理模板.xlsx"; |
|||
|
|||
/** |
|||
* 填充模板 - rqrq。 |
|||
* 前置:Service 已校验同站点/同申请人及日期;本方法额外校验模板锚点与金额。 |
|||
* 步骤:两页独立扩行、复制格式/合并区域、填值、重建公式及打印区域、计算缓存。 |
|||
* 一致性:全程内存操作,仅全部完成后返回文件;不回写源模板或数据库。 |
|||
* 失败策略:模板布局变化、金额非法或公式错误立即失败,不输出缺行或错误合计。 |
|||
*/ |
|||
public byte[] write(ExpenseExportQuery query, List<ExpenseHeader> headers, |
|||
List<ExpenseDetail> details, List<ExpenseTrip> trips) { |
|||
try (InputStream input = new ClassPathResource(TEMPLATE).getInputStream(); |
|||
Workbook workbook = WorkbookFactory.create(input); |
|||
ByteArrayOutputStream output = new ByteArrayOutputStream()) { |
|||
if (workbook.getNumberOfSheets() != 2) { |
|||
throw new RuntimeException("费用管理模板必须包含费用报告、差旅行程详情两个页签"); |
|||
} |
|||
Sheet report = workbook.getSheetAt(0); |
|||
Sheet routes = workbook.getSheetAt(1); |
|||
// 固定表头必须与已确认模板一致,避免替换模板后把数据写入错误位置 - rqrq。 |
|||
checkLabel(report, 4, 8, "交通费"); |
|||
checkLabel(report, 4, 10, "住宿费"); |
|||
checkLabel(report, 4, 12, "住宿节约补助"); |
|||
checkLabel(report, 4, 14, "补助"); |
|||
checkLabel(report, 8, 0, "合"); |
|||
checkLabel(routes, 2, 7, "Sub-total"); |
|||
checkLabel(routes, 6, 0, "Grand Total"); |
|||
|
|||
// 1) 金额先逐条舍入,key 是费用单号;四个槽位与模板四列一一对应 - rqrq。 |
|||
Map<String, BigDecimal[]> fees = new HashMap<>(); |
|||
for (ExpenseDetail d : details) { |
|||
String type = d.getFeeType() == null ? "" : d.getFeeType().trim(); |
|||
int index = ExpenseReportServiceImpl.REPORT_TYPES.indexOf(type); |
|||
if (index < 0) { |
|||
continue; // 其他费用保留在系统中,此模板明确只取四类 - rqrq。 |
|||
} |
|||
BigDecimal[] values = fees.computeIfAbsent(d.getFeeNo(), key -> new BigDecimal[]{ |
|||
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO}); |
|||
values[index] = values[index].add(ExpenseReportServiceImpl.amount(d.getAmount(), |
|||
"费用单 " + d.getFeeNo() + " 第 " + d.getItemNo() + " 行金额")); |
|||
} |
|||
BigDecimal grandTotal = fees.values().stream().flatMap(Arrays::stream).reduce(BigDecimal.ZERO, BigDecimal::add); |
|||
ExpenseReportServiceImpl.amount(grandTotal, "导出合计"); |
|||
|
|||
// 2) 第一页按主记录扩行;空余两行保留,SUM 会自动忽略空值 - rqrq。 |
|||
int reportRows = Math.max(2, headers.size()); |
|||
expand(report, 6, 2, reportRows, 18); |
|||
int totalRow = 6 + reportRows; |
|||
CellStyle money = style(workbook, cell(report, 6, 8).getCellStyle(), "#,##0.00"); |
|||
CellStyle days = style(workbook, cell(report, 6, 7).getCellStyle(), "0.##"); |
|||
for (int i = 0; i < reportRows; i++) { |
|||
int row = 6 + i; |
|||
for (int col : new int[]{8, 10, 12, 14, 16}) { |
|||
cell(report, row, col).setCellStyle(money); |
|||
} |
|||
cell(report, row, 7).setCellStyle(days); |
|||
text(report, row, 4, "-"); |
|||
// 同时为预留行补公式,导出后手工填写四项金额也会产生小计 - rqrq。 |
|||
int excelRow = row + 1; |
|||
cell(report, row, 16).setCellFormula("IF(COUNT(I" + excelRow + ",K" + excelRow |
|||
+ ",M" + excelRow + ",O" + excelRow + ")=0,\"\",ROUND(SUM(I" + excelRow |
|||
+ ",K" + excelRow + ",M" + excelRow + ",O" + excelRow + "),2))"); |
|||
if (i >= headers.size()) { |
|||
continue; |
|||
} |
|||
ExpenseHeader h = headers.get(i); |
|||
number(report, row, 0, h.getFeeDate().getMonthValue()); |
|||
number(report, row, 1, h.getFeeDate().getDayOfMonth()); |
|||
text(report, row, 2, h.getStartPlace()); |
|||
text(report, row, 5, h.getEndPlace()); |
|||
decimal(report, row, 7, h.getTripDays()); |
|||
report.getRow(row).setHeightInPoints(Math.max(report.getRow(row).getHeightInPoints(), |
|||
14f * Math.max(1, (Math.max(h.getStartPlace().length(), h.getEndPlace().length()) + 9) / 10))); |
|||
BigDecimal[] values = fees.getOrDefault(h.getFeeNo(), new BigDecimal[]{ |
|||
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO}); |
|||
for (int k = 0; k < 4; k++) { |
|||
decimal(report, row, 8 + k * 2, values[k]); |
|||
} |
|||
} |
|||
for (int col : new int[]{7, 8, 10, 12, 14, 16}) { |
|||
String letter = CellReference.convertNumToColString(col); |
|||
cell(report, totalRow, col).setCellFormula(dynamicSum(letter, 7)); |
|||
cell(report, totalRow, col).setCellStyle(col == 7 ? days : money); |
|||
} |
|||
fillDate(report, 1, new int[]{5, 7, 9}, query.getReportDate()); |
|||
fillDate(report, 3, new int[]{3, 5, 7}, query.getTripStartDate()); |
|||
fillDate(report, 3, new int[]{9, 11, 13}, query.getTripEndDate()); |
|||
// 出差事由由报销人在导出的模板中手工填写,不再汇总所选费用单的事由 - rqrq。 |
|||
cell(report, 2, 2).setBlank(); |
|||
// 出差总天数按填写的天数相加,区间内未报销日期不自动算作一天 - rqrq。 |
|||
cell(report, 3, 16).setCellFormula("H" + (totalRow + 1)); |
|||
cell(report, 3, 16).setCellStyle(days); |
|||
text(report, totalRow + 2, 14, headers.get(0).getApplyUserName()); |
|||
writeUppercase(report, totalRow + 1, totalRow, money, grandTotal); |
|||
print(workbook, report, 0, 17, totalRow + 2, 4, 5); |
|||
|
|||
// 3) 第二页每条行程一行;金额直接来自附件,与第一页四项费用不互相累计 - rqrq。 |
|||
int tripRows = Math.max(2, trips.size()); |
|||
expand(routes, 4, 2, tripRows, 8); |
|||
int tripTotal = 4 + tripRows; |
|||
// 原模板合并表头内部有残留出租车文字及 SUM(E4:F4),应清空隐藏子单元格 - rqrq。 |
|||
cell(routes, 3, 4).setBlank(); |
|||
cell(routes, 3, 7).setBlank(); |
|||
CellStyle date = style(workbook, cell(routes, 4, 0).getCellStyle(), "yyyy-mm-dd"); |
|||
CellStyle tripMoney = style(workbook, cell(routes, 4, 7).getCellStyle(), "#,##0.00"); |
|||
CellStyle mileage = style(workbook, cell(routes, 4, 6).getCellStyle(), "0.##"); |
|||
for (int i = 0; i < tripRows; i++) { |
|||
int row = 4 + i; |
|||
cell(routes, row, 0).setCellStyle(date); |
|||
cell(routes, row, 7).setCellStyle(tripMoney); |
|||
cell(routes, row, 6).setCellStyle(mileage); |
|||
if (i >= trips.size()) { |
|||
continue; |
|||
} |
|||
ExpenseTrip t = trips.get(i); |
|||
cell(routes, row, 0).setCellValue(t.getTripDate()); |
|||
text(routes, row, 1, t.getStartPlace()); |
|||
text(routes, row, 2, t.getEndPlace()); |
|||
text(routes, row, 3, t.getExpenseDesc()); |
|||
text(routes, row, 4, t.getVehicle()); |
|||
number(routes, row, 5, t.getBillCount()); |
|||
decimal(routes, row, 6, t.getMileage()); |
|||
decimal(routes, row, 7, ExpenseReportServiceImpl.amount(t.getAmount(), "行程金额")); |
|||
routes.getRow(row).setHeightInPoints(Math.max(30, |
|||
14 * Math.max((t.getExpenseDesc().length() + 19) / 20, |
|||
(Math.max(t.getStartPlace().length(), t.getEndPlace().length()) + 9) / 10))); |
|||
} |
|||
cell(routes, tripTotal, 7).setCellFormula(dynamicSum("H", 5)); |
|||
cell(routes, tripTotal, 7).setCellStyle(tripMoney); |
|||
text(routes, tripTotal + 3, 6, headers.get(0).getApplyUserName()); |
|||
print(workbook, routes, 1, 7, tripTotal + 3, 2, 3); |
|||
|
|||
// 4) 常规公式后端算缓存,并保留公式供 Excel/WPS 打开及手工改动后重算 - rqrq。 |
|||
workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); |
|||
for (Sheet sheet : workbook) { |
|||
for (Row row : sheet) { |
|||
for (Cell c : row) { |
|||
if (c.getCellType() == CellType.FORMULA && c.getCachedFormulaResultType() == CellType.ERROR) { |
|||
throw new RuntimeException("模板公式计算失败:" + sheet.getSheetName() + "!" + c.getAddress()); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
workbook.setForceFormulaRecalculation(true); |
|||
workbook.write(output); |
|||
return output.toByteArray(); |
|||
} catch (java.io.IOException e) { |
|||
throw new RuntimeException("读取或生成费用管理模板失败", e); |
|||
} |
|||
} |
|||
|
|||
/** 原始数据区之外的内容整体下移,按样板行重新创建每条填写行的格式及横向合并 - rqrq。 */ |
|||
private void expand(Sheet sheet, int start, int initialRows, int rows, int width) { |
|||
Row model = sheet.getRow(start); |
|||
if (model == null) { |
|||
throw new RuntimeException("模板缺少填写样板行"); |
|||
} |
|||
short height = model.getHeight(); |
|||
CellStyle[] styles = new CellStyle[width]; |
|||
for (int col = 0; col < width; col++) { |
|||
styles[col] = cell(sheet, start, col).getCellStyle(); |
|||
} |
|||
List<CellRangeAddress> merges = new ArrayList<>(sheet.getMergedRegions()); |
|||
for (int i = sheet.getNumMergedRegions() - 1; i >= 0; i--) { |
|||
sheet.removeMergedRegion(i); |
|||
} |
|||
int footer = start + initialRows; |
|||
int offset = rows - initialRows; |
|||
if (offset > 0) { |
|||
sheet.shiftRows(footer, sheet.getLastRowNum(), offset, true, false); |
|||
} |
|||
for (int row = start; row < start + rows; row++) { |
|||
Row target = sheet.getRow(row); |
|||
if (target == null) { |
|||
target = sheet.createRow(row); |
|||
} |
|||
target.setHeight(height); |
|||
for (int col = 0; col < width; col++) { |
|||
Cell c = cell(sheet, row, col); |
|||
c.setBlank(); |
|||
c.setCellStyle(styles[col]); |
|||
} |
|||
} |
|||
for (CellRangeAddress merge : merges) { |
|||
if (merge.getFirstRow() == start && merge.getLastRow() == start) { |
|||
for (int row = start; row < start + rows; row++) { |
|||
sheet.addMergedRegion(new CellRangeAddress(row, row, merge.getFirstColumn(), merge.getLastColumn())); |
|||
} |
|||
} else if (merge.getFirstRow() >= footer) { |
|||
sheet.addMergedRegion(new CellRangeAddress(merge.getFirstRow() + offset, merge.getLastRow() + offset, |
|||
merge.getFirstColumn(), merge.getLastColumn())); |
|||
} else if (merge.getLastRow() < start) { |
|||
sheet.addMergedRegion(merge.copy()); |
|||
} |
|||
} |
|||
} |
|||
|
|||
/** 合计范围结束于公式所在行的上一行,用户在合计前插行也能自动纳入 - rqrq。 */ |
|||
private String dynamicSum(String column, int firstRow) { |
|||
return "ROUND(SUM(" + column + "$" + firstRow + ":INDEX(" + column + ":" + column + ",ROW()-1)),2)"; |
|||
} |
|||
|
|||
/** |
|||
* 大写金额用标准 MID/INT/MOD/IF 公式,不依赖 TEXT 的中文地区格式 - rqrq。 |
|||
* 通常保留原模板万、仟、佰、拾、元、角、分的分格;超出万位时才合并大写区域。 |
|||
*/ |
|||
private void writeUppercase(Sheet sheet, int row, int totalRow, CellStyle money, BigDecimal total) { |
|||
String ref = "Q" + (row + 1); |
|||
cell(sheet, row, 16).setCellFormula("Q" + (totalRow + 1)); |
|||
cell(sheet, row, 16).setCellStyle(money); |
|||
if (total.compareTo(new BigDecimal("100000")) < 0) { |
|||
// 保留原印刷表格的单位和边框,逐位替换不兼容的中文 TEXT 格式 - rqrq。 |
|||
int[] columns = {2, 4, 6, 8, 10}; |
|||
int[] divisors = {10000, 1000, 100, 10, 1}; |
|||
for (int i = 0; i < columns.length; i++) { |
|||
String value = "MOD(INT(" + ref + "/" + divisors[i] + "),10)"; |
|||
cell(sheet, row, columns[i]).setCellFormula("IF(" + ref + ">=" + divisors[i] + "," |
|||
+ digit(value) + "," + (i == 4 ? "\"零\"" : "\"*\"") + ")"); |
|||
} |
|||
cell(sheet, row, 12).setCellFormula(digit("MOD(INT(ROUND(" + ref + "*100,0)/10),10)")); |
|||
cell(sheet, row, 14).setCellFormula(digit("MOD(ROUND(" + ref + "*100,0),10)")); |
|||
return; |
|||
} |
|||
for (int col = 2; col <= 15; col++) { |
|||
cell(sheet, row, col).setBlank(); |
|||
} |
|||
sheet.addMergedRegion(new CellRangeAddress(row, row, 2, 15)); |
|||
String integer = "INT(" + ref + ")"; |
|||
String yi = "INT(" + integer + "/100000000)"; |
|||
String wan = "INT(MOD(" + integer + ",100000000)/10000)"; |
|||
String yuan = "MOD(" + integer + ",10000)"; |
|||
String jiao = "MOD(INT(ROUND(" + ref + "*100,0)/10),10)"; |
|||
String fen = "MOD(ROUND(" + ref + "*100,0),10)"; |
|||
String formula = "IF(" + integer + "=0,\"零\",IF(" + yi + ">0," + group(yi) + "&\"亿\",\"\")" |
|||
+ "&IF(" + wan + ">0,IF(AND(" + yi + ">0," + wan + "<1000),\"零\",\"\")&" + group(wan) + "&\"万\",\"\")" |
|||
+ "&IF(" + yuan + ">0,IF(OR(AND(" + wan + ">0," + yuan + "<1000),AND(" + yi + ">0," + wan + "=0)),\"零\",\"\")&" |
|||
+ group(yuan) + ",\"\"))&\"元\"&IF(" + jiao + ">0," + digit(jiao) + "&\"角\",IF(AND(" + integer |
|||
+ ">0," + fen + ">0),\"零\",\"\"))&IF(" + fen + ">0," + digit(fen) + "&\"分\",\"整\")"; |
|||
cell(sheet, row, 2).setCellFormula(formula); |
|||
CellStyle uppercase = sheet.getWorkbook().createCellStyle(); |
|||
uppercase.cloneStyleFrom(cell(sheet, row, 2).getCellStyle()); |
|||
uppercase.setAlignment(HorizontalAlignment.LEFT); |
|||
uppercase.setWrapText(true); |
|||
cell(sheet, row, 2).setCellStyle(uppercase); |
|||
sheet.getRow(row).setHeightInPoints(32); |
|||
} |
|||
|
|||
private String digit(String value) { |
|||
return "MID(\"零壹贰叁肆伍陆柒捌玖\"," + value + "+1,1)"; |
|||
} |
|||
|
|||
/** 四位中文数字组,按千百十个位补必要的零 - rqrq。 */ |
|||
private String group(String n) { |
|||
String a = "INT(" + n + "/1000)"; |
|||
String b = "INT(MOD(" + n + ",1000)/100)"; |
|||
String c = "INT(MOD(" + n + ",100)/10)"; |
|||
String d = "MOD(" + n + ",10)"; |
|||
return "IF(" + a + ">0," + digit(a) + "&\"仟\",\"\")&IF(" + b + ">0," + digit(b) |
|||
+ "&\"佰\",IF(AND(" + a + ">0,MOD(" + n + ",100)>0),\"零\",\"\"))&IF(" + c + ">0," |
|||
+ digit(c) + "&\"拾\",IF(AND(" + b + ">0," + d + ">0),\"零\",\"\"))&IF(" + d + ">0," + digit(d) + ",\"\")"; |
|||
} |
|||
|
|||
private void print(Workbook workbook, Sheet sheet, int index, int lastCol, int lastRow, int headerStart, int headerEnd) { |
|||
workbook.setPrintArea(index, 0, lastCol, 0, lastRow); |
|||
sheet.setRepeatingRows(new CellRangeAddress(headerStart, headerEnd, -1, -1)); |
|||
sheet.setFitToPage(true); |
|||
sheet.getPrintSetup().setFitWidth((short) 1); |
|||
sheet.getPrintSetup().setFitHeight((short) 0); |
|||
sheet.setAutobreaks(true); |
|||
} |
|||
|
|||
private void checkLabel(Sheet sheet, int row, int col, String label) { |
|||
if (!new DataFormatter().formatCellValue(cell(sheet, row, col)).contains(label)) { |
|||
throw new RuntimeException("费用模板布局不匹配:" + sheet.getSheetName() + ",预期列:" + label); |
|||
} |
|||
} |
|||
|
|||
private CellStyle style(Workbook workbook, CellStyle source, String format) { |
|||
CellStyle result = workbook.createCellStyle(); |
|||
result.cloneStyleFrom(source); |
|||
result.setDataFormat(workbook.createDataFormat().getFormat(format)); |
|||
result.setWrapText(true); |
|||
return result; |
|||
} |
|||
|
|||
private Cell cell(Sheet sheet, int row, int col) { |
|||
Row r = sheet.getRow(row); |
|||
if (r == null) { |
|||
r = sheet.createRow(row); |
|||
} |
|||
return r.getCell(col, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); |
|||
} |
|||
|
|||
private void text(Sheet sheet, int row, int col, String value) { |
|||
cell(sheet, row, col).setCellValue(value == null ? "" : value); |
|||
} |
|||
|
|||
private void number(Sheet sheet, int row, int col, Number value) { |
|||
cell(sheet, row, col).setCellValue(value == null ? 0 : value.doubleValue()); |
|||
} |
|||
|
|||
private void decimal(Sheet sheet, int row, int col, BigDecimal value) { |
|||
number(sheet, row, col, value == null ? null : value.setScale(2, RoundingMode.HALF_UP)); |
|||
} |
|||
|
|||
private void fillDate(Sheet sheet, int row, int[] columns, LocalDate date) { |
|||
number(sheet, row, columns[0], date.getYear()); |
|||
number(sheet, row, columns[1], date.getMonthValue()); |
|||
number(sheet, row, columns[2], date.getDayOfMonth()); |
|||
} |
|||
} |
|||
@ -0,0 +1,133 @@ |
|||
<?xml version="1.0" encoding="UTF-8"?> |
|||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
|||
<mapper namespace="com.xujie.modules.inspection.expense.mapper.ExpenseReportMapper"> |
|||
<!-- 日期读写显式走旧驱动支持的 JDBC 接口,避免默认 Java 8 日期处理器报不支持 - rqrq。 --> |
|||
<resultMap id="expenseHeader" type="com.xujie.modules.inspection.expense.data.ExpenseHeader" autoMapping="true"> |
|||
<result column="fee_date" property="feeDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler"/> |
|||
<result column="created_date" property="createdDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler"/> |
|||
<result column="update_date" property="updateDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler"/> |
|||
</resultMap> |
|||
<resultMap id="expenseDetail" type="com.xujie.modules.inspection.expense.data.ExpenseDetail" autoMapping="true"> |
|||
<result column="create_date" property="createDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler"/> |
|||
</resultMap> |
|||
<resultMap id="expenseTrip" type="com.xujie.modules.inspection.expense.data.ExpenseTrip" autoMapping="true"> |
|||
<result column="trip_date" property="tripDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler"/> |
|||
<result column="create_date" property="createDate" |
|||
typeHandler="com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler"/> |
|||
</resultMap> |
|||
<!-- 新页面共用旧表,行版本自动感知旧页面对主表的修改 - rqrq。 --> |
|||
<sql id="headerColumns"> |
|||
h.site, h.fee_no, CAST(h.fee_date AS date) fee_date, h.apply_user, |
|||
COALESCE(NULLIF(u.user_display, ''), h.apply_user) apply_user_name, |
|||
h.start_place, h.end_place, h.trip_days, h.trip_reason, h.remark, |
|||
COALESCE((SELECT SUM(ROUND(COALESCE(d.amount, 0), 2)) FROM srm_fee_detail d |
|||
WHERE d.site = h.site AND d.fee_no = h.fee_no), 0) total_amount, |
|||
<!-- rowversion 先转为二进制再输出十六进制,避免 timestamp 直接转字符返回控制字符 - rqrq。 --> |
|||
CONVERT(varchar(16), CAST(h.expense_row_version AS binary(8)), 2) version, |
|||
h.created_by, h.created_date, h.update_by, h.update_date |
|||
</sql> |
|||
<sql id="userJoin"> |
|||
OUTER APPLY (SELECT TOP 1 user_display FROM sys_user |
|||
WHERE username = h.apply_user ORDER BY CASE WHEN site = h.site THEN 0 ELSE 1 END, user_id) u |
|||
</sql> |
|||
<sql id="selectedNos"> |
|||
<foreach collection="feeNos" item="no" open="(" separator="," close=")">#{no}</foreach> |
|||
</sql> |
|||
<select id="search" resultMap="expenseHeader"> |
|||
SELECT <include refid="headerColumns"/> FROM srm_fee_header h <include refid="userJoin"/> |
|||
WHERE h.site = #{query.site} |
|||
<if test="query.feeNo != null and query.feeNo != ''">AND h.fee_no LIKE '%' + #{query.feeNo} + '%'</if> |
|||
<if test="query.applyUser != null and query.applyUser != ''">AND h.apply_user = #{query.applyUser}</if> |
|||
<if test="query.dateStart != null">AND h.fee_date >= #{query.dateStart,jdbcType=DATE,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler}</if> |
|||
<if test="query.dateEnd != null">AND h.fee_date < DATEADD(day, 1, #{query.dateEnd,jdbcType=DATE,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler})</if> |
|||
ORDER BY h.fee_date DESC, h.fee_no DESC |
|||
</select> |
|||
<select id="getHeader" resultMap="expenseHeader"> |
|||
SELECT <include refid="headerColumns"/> FROM srm_fee_header h <include refid="userJoin"/> |
|||
WHERE h.site = #{site} AND h.fee_no = #{feeNo} |
|||
</select> |
|||
<select id="exportHeaders" resultMap="expenseHeader"> |
|||
SELECT <include refid="headerColumns"/> FROM srm_fee_header h <include refid="userJoin"/> |
|||
WHERE h.site = #{site} AND h.fee_no IN <include refid="selectedNos"/> |
|||
ORDER BY h.fee_date, h.fee_no |
|||
</select> |
|||
<select id="getDetails" resultMap="expenseDetail"> |
|||
SELECT d.site, d.fee_no, d.item_no, d.fee_type, |
|||
COALESCE(t.dict_label, LTRIM(RTRIM(d.fee_type))) fee_type_name, d.amount, d.remark, |
|||
d.create_by, d.create_date |
|||
FROM srm_fee_detail d |
|||
OUTER APPLY (SELECT TOP 1 dict_label FROM sys_dict_data |
|||
WHERE dict_type = 'fee_type' AND LTRIM(RTRIM(dict_value)) = LTRIM(RTRIM(d.fee_type)) |
|||
AND site IN (#{site}, '*') |
|||
ORDER BY CASE WHEN site = #{site} THEN 0 ELSE 1 END, dict_code) t |
|||
WHERE d.site = #{site} AND d.fee_no IN <include refid="selectedNos"/> |
|||
ORDER BY d.fee_no, d.item_no |
|||
</select> |
|||
<select id="getTrips" resultMap="expenseTrip"> |
|||
SELECT site, fee_no, item_no, trip_date, start_place, end_place, expense_desc, |
|||
vehicle, bill_count, mileage, amount, create_by, create_date |
|||
FROM srm_fee_trip_detail WHERE site = #{site} AND fee_no IN <include refid="selectedNos"/> |
|||
ORDER BY trip_date, fee_no, item_no |
|||
</select> |
|||
<select id="getRequestNos" resultType="string"> |
|||
SELECT request_no FROM srm_inspect_request_fee WHERE site = #{site} AND fee_no = #{feeNo} |
|||
ORDER BY request_no |
|||
</select> |
|||
<!-- 各业务值以本站配置优先,未配置的值使用全厂配置;支持已维护的其他类型 - rqrq。 --> |
|||
<select id="getTypes" resultType="com.xujie.modules.inspection.expense.data.ExpenseOption"> |
|||
SELECT value, label FROM ( |
|||
SELECT LTRIM(RTRIM(dict_value)) value, dict_label label, status, dict_sort, |
|||
ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(dict_value)) |
|||
ORDER BY CASE WHEN site = #{site} THEN 0 ELSE 1 END, dict_code) rn |
|||
FROM sys_dict_data WHERE dict_type = 'fee_type' AND site IN (#{site}, '*') |
|||
) d WHERE rn = 1 AND status = 'Y' AND value <> '' ORDER BY dict_sort, value |
|||
</select> |
|||
<select id="getUsers" resultType="com.xujie.modules.inspection.expense.data.ExpenseOption"> |
|||
SELECT username value, COALESCE(NULLIF(user_display, ''), username) label |
|||
FROM sys_user WHERE status = 1 AND site = #{site} ORDER BY username |
|||
</select> |
|||
<insert id="insertHeader"> |
|||
INSERT INTO srm_fee_header (site, fee_no, fee_date, apply_user, start_place, end_place, |
|||
trip_days, trip_reason, remark, total_amount, created_by, created_date, update_by, update_date) |
|||
VALUES (#{site}, #{feeNo}, #{feeDate,jdbcType=DATE,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler}, #{applyUser}, #{startPlace}, #{endPlace}, #{tripDays}, |
|||
#{tripReason}, #{remark}, #{totalAmount}, #{createdBy}, GETDATE(), #{updateBy}, GETDATE()) |
|||
</insert> |
|||
<update id="updateHeader"> |
|||
UPDATE srm_fee_header SET fee_date = #{feeDate,jdbcType=DATE,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler}, apply_user = #{applyUser}, |
|||
start_place = #{startPlace}, end_place = #{endPlace}, trip_days = #{tripDays}, |
|||
trip_reason = #{tripReason}, remark = #{remark}, total_amount = #{totalAmount}, |
|||
update_by = #{updateBy}, update_date = GETDATE() |
|||
WHERE site = #{site} AND fee_no = #{feeNo} |
|||
AND expense_row_version = CONVERT(binary(8), #{version}, 2) |
|||
</update> |
|||
<delete id="deleteHeader"> |
|||
DELETE FROM srm_fee_header WHERE site = #{site} AND fee_no = #{feeNo} |
|||
AND expense_row_version = CONVERT(binary(8), #{version}, 2) |
|||
</delete> |
|||
<delete id="deleteDetails">DELETE FROM srm_fee_detail WHERE site = #{site} AND fee_no = #{feeNo}</delete> |
|||
<delete id="deleteTrips">DELETE FROM srm_fee_trip_detail WHERE site = #{site} AND fee_no = #{feeNo}</delete> |
|||
<delete id="deleteRequests">DELETE FROM srm_inspect_request_fee WHERE site = #{site} AND fee_no = #{feeNo}</delete> |
|||
<!-- 单条 SQL 批量插入;Service 分批控制 SQL Server 2100 参数上限 - rqrq。 --> |
|||
<insert id="insertDetails"> |
|||
INSERT INTO srm_fee_detail (site, fee_no, item_no, fee_type, amount, remark, |
|||
create_by, create_date, update_by, update_date) VALUES |
|||
<foreach collection="rows" item="r" separator=","> |
|||
(#{site}, #{feeNo}, #{r.itemNo}, #{r.feeType}, #{r.amount}, #{r.remark}, |
|||
COALESCE(#{r.createBy}, #{operator}), COALESCE(#{r.createDate,jdbcType=TIMESTAMP,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler}, GETDATE()), #{operator}, GETDATE()) |
|||
</foreach> |
|||
</insert> |
|||
<insert id="insertTrips"> |
|||
INSERT INTO srm_fee_trip_detail (site, fee_no, item_no, trip_date, start_place, end_place, |
|||
expense_desc, vehicle, bill_count, mileage, amount, create_by, create_date, update_by, update_date) VALUES |
|||
<foreach collection="rows" item="r" separator=","> |
|||
(#{site}, #{feeNo}, #{r.itemNo}, #{r.tripDate,jdbcType=DATE,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTypeHandler}, #{r.startPlace}, #{r.endPlace}, |
|||
#{r.expenseDesc}, #{r.vehicle}, #{r.billCount}, #{r.mileage}, #{r.amount}, |
|||
COALESCE(#{r.createBy}, #{operator}), COALESCE(#{r.createDate,jdbcType=TIMESTAMP,typeHandler=com.xujie.modules.inspection.expense.support.ExpenseLocalDateTimeTypeHandler}, GETDATE()), #{operator}, GETDATE()) |
|||
</foreach> |
|||
</insert> |
|||
</mapper> |
|||
Write
Preview
Loading…
Cancel
Save
Reference in new issue