账单异步生成优化
This commit is contained in:
+10
-1
@@ -194,6 +194,15 @@
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
<!-- JDK 23+ 默认不再自动发现注解处理器,显式启用 Lombok,避免 @Data 方法未生成。 -->
|
||||
<proc>full</proc>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.46</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@@ -229,4 +238,4 @@
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
||||
+139
-32
@@ -1,6 +1,7 @@
|
||||
package com.ruoyi.web.controller.ar;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -17,7 +18,9 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.ruoyi.ar.domain.ArBill;
|
||||
import com.ruoyi.ar.domain.ArBankAccount;
|
||||
import com.ruoyi.ar.domain.ArBillDetailFee;
|
||||
import com.ruoyi.ar.domain.ArBillExport;
|
||||
import com.ruoyi.ar.domain.ArBillGenerateTask;
|
||||
import com.ruoyi.ar.domain.ArBillLog;
|
||||
import com.ruoyi.ar.domain.vo.ArBillActionRequest;
|
||||
import com.ruoyi.ar.domain.vo.ArBillGenerateQuery;
|
||||
@@ -33,114 +36,218 @@ import com.ruoyi.common.utils.StringUtils;
|
||||
import com.ruoyi.common.utils.uuid.IdUtils;
|
||||
import com.ruoyi.price.domain.PrcOrderBill;
|
||||
|
||||
/** 应收账单管理。 */
|
||||
/**
|
||||
* 应收账单 HTTP 接口层。
|
||||
*
|
||||
* <p>负责账单列表、账单生成、确认/作废、异步导出、日志和详情分页接口;
|
||||
* 具体业务规则统一下沉到 {@code IArBillService}。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/ar/bill")
|
||||
@Validated
|
||||
public class ArBillController extends BaseController
|
||||
{
|
||||
public class ArBillController extends BaseController {
|
||||
@Autowired
|
||||
private IArBillService billService;
|
||||
|
||||
/**
|
||||
* 查询账单列表;分页参数由 BaseController.startPage 交给 MyBatis PageHelper 处理。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:list')")
|
||||
@GetMapping("/list")
|
||||
public TableDataInfo list(ArBillQuery query)
|
||||
{
|
||||
public TableDataInfo list(ArBillQuery query) {
|
||||
startPage();
|
||||
List<ArBill> list = billService.selectArBillList(query);
|
||||
return getDataTable(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询账单头信息;账单明细通过独立分页接口按需加载。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/{arBillId}")
|
||||
public AjaxResult getInfo(@PathVariable Long arBillId)
|
||||
{
|
||||
public AjaxResult getInfo(@PathVariable Long arBillId) {
|
||||
return success(billService.selectArBillById(arBillId));
|
||||
}
|
||||
|
||||
/** 查询指定币种的公司默认收款账户,账号返回脱敏值。 */
|
||||
/**
|
||||
* 分页查询账单明细,避免详情页一次性加载全部订单。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/{arBillId}/details")
|
||||
public TableDataInfo details(@PathVariable Long arBillId) {
|
||||
startPage();
|
||||
return getDataTable(billService.selectArBillDetails(arBillId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单条账单明细的费用明细,按展开行懒加载。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/{arBillId}/details/{detailId}/fees")
|
||||
public AjaxResult detailFees(@PathVariable Long arBillId, @PathVariable Long detailId) {
|
||||
List<ArBillDetailFee> fees = billService.selectArBillDetailFees(arBillId, detailId);
|
||||
return success(fees);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询指定币种的公司默认收款账户,账号返回脱敏值。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
|
||||
@GetMapping("/default-bank-account")
|
||||
public AjaxResult defaultBankAccount(@RequestParam(required = false, defaultValue = "CNY") String currency)
|
||||
{
|
||||
public AjaxResult defaultBankAccount(@RequestParam(required = false, defaultValue = "CNY") String currency) {
|
||||
ArBankAccount account = billService.getDefaultBankAccount(currency);
|
||||
return success(account);
|
||||
}
|
||||
|
||||
/** 查询生成账单前的订单计费结果。 */
|
||||
/**
|
||||
* 查询生成账单前的订单计费结果。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
|
||||
@GetMapping("/generate/preview")
|
||||
public TableDataInfo preview(ArBillGenerateQuery query)
|
||||
{
|
||||
public AjaxResult preview(ArBillGenerateQuery query) {
|
||||
startPage();
|
||||
List<PrcOrderBill> list = billService.previewBill(query);
|
||||
return getDataTable(list);
|
||||
TableDataInfo pageData = getDataTable(list);
|
||||
AjaxResult result = success();
|
||||
result.put("rows", pageData.getRows());
|
||||
result.put("total", pageData.getTotal());
|
||||
result.put("totalAmount", billService.sumPreviewBill(query));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建账单头和异步生成任务,接口不等待全部订单明细处理完成。
|
||||
*/
|
||||
@Log(title = "应收账单", businessType = BusinessType.INSERT)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
|
||||
@PostMapping("/generate")
|
||||
public AjaxResult generate(@Valid @RequestBody ArBillGenerateRequest request,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId)
|
||||
{
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(request.getRequestId(), headerRequestId);
|
||||
ArBill bill = billService.generateBill(request, getUsername(), requestId);
|
||||
return success(bill).put("request_id", requestId);
|
||||
ArBillGenerateTask task = billService.generateBill(request, getUsername(), requestId);
|
||||
return success(task).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单个应收账单异步生成任务。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/generate/task/{taskId}")
|
||||
public AjaxResult generateTaskInfo(@PathVariable Long taskId) {
|
||||
return success(billService.selectGenerateTask(taskId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前用户仍在处理中的应收账单生成任务。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/generate/tasks/active")
|
||||
public AjaxResult activeGenerateTasks() {
|
||||
return success(billService.selectActiveGenerateTasks(getUsername()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求取消应收账单异步生成任务。
|
||||
*/
|
||||
@Log(title = "应收账单", businessType = BusinessType.UPDATE)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
|
||||
@PostMapping("/generate/task/{taskId}/cancel")
|
||||
public AjaxResult cancelGenerateTask(@PathVariable Long taskId,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(null, headerRequestId);
|
||||
return success(billService.cancelGenerateTask(taskId, getUsername(), requestId)).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 整单重新发起应收账单异步生成任务。
|
||||
*/
|
||||
@Log(title = "应收账单", businessType = BusinessType.INSERT)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:generate')")
|
||||
@PostMapping("/generate/task/{taskId}/retry")
|
||||
public AjaxResult retryGenerateTask(@PathVariable Long taskId,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(null, headerRequestId);
|
||||
return success(billService.retryGenerateTask(taskId, getUsername(), requestId)).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认已生成完成的账单,使其进入可核销状态。
|
||||
*/
|
||||
@Log(title = "应收账单", businessType = BusinessType.UPDATE)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:confirm')")
|
||||
@PutMapping("/{arBillId}/confirm")
|
||||
public AjaxResult confirm(@PathVariable Long arBillId, @RequestBody(required = false) ArBillActionRequest request,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId)
|
||||
{
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(request == null ? null : request.getRequestId(), headerRequestId);
|
||||
return success(billService.confirmBill(arBillId, request, getUsername(), requestId)).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废尚未发生核销的账单;账单明细保留作为历史快照。
|
||||
*/
|
||||
@Log(title = "应收账单", businessType = BusinessType.UPDATE)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:void')")
|
||||
@PutMapping("/{arBillId}/void")
|
||||
public AjaxResult voidBill(@PathVariable Long arBillId, @RequestBody ArBillActionRequest request,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId)
|
||||
{
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(request == null ? null : request.getRequestId(), headerRequestId);
|
||||
return success(billService.voidBill(arBillId, request, getUsername(), requestId)).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅提交导出任务;前端通过导出任务状态接口轮询并在完成后下载。
|
||||
*/
|
||||
@Log(title = "应收账单导出", businessType = BusinessType.EXPORT)
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:export')")
|
||||
@PostMapping("/{arBillId}/export")
|
||||
public AjaxResult export(@PathVariable Long arBillId,
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId)
|
||||
{
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId) {
|
||||
String requestId = requestId(null, headerRequestId);
|
||||
return success(billService.exportBill(arBillId, getUsername(), requestId)).put("request_id", requestId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前账单的导出历史和任务状态。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/{arBillId}/exports")
|
||||
public AjaxResult exports(@PathVariable Long arBillId)
|
||||
{
|
||||
public AjaxResult exports(@PathVariable Long arBillId) {
|
||||
return success(billService.selectExports(arBillId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单个账单导出任务状态,供前端轮询。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:query')")
|
||||
@GetMapping("/export/{exportId}")
|
||||
public AjaxResult exportInfo(@PathVariable Long exportId) {
|
||||
return success(billService.selectExport(exportId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载已成功生成的导出文件;文件内容由服务层从临时文件或配置存储读取。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:bill:export')")
|
||||
@GetMapping("/export/{exportId}/download")
|
||||
public void download(@PathVariable Long exportId, HttpServletResponse response) throws Exception
|
||||
{
|
||||
public void download(@PathVariable Long exportId, HttpServletResponse response) throws Exception {
|
||||
billService.downloadExport(exportId, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询账单操作日志。
|
||||
*/
|
||||
@PreAuthorize("@ss.hasPermi('ar:log:list')")
|
||||
@GetMapping("/log/list")
|
||||
public TableDataInfo logs(ArBillLog query)
|
||||
{
|
||||
public TableDataInfo logs(ArBillLog query) {
|
||||
startPage();
|
||||
return getDataTable(billService.selectLogList(query));
|
||||
}
|
||||
|
||||
private String requestId(String bodyRequestId, String headerRequestId)
|
||||
{
|
||||
/**
|
||||
* 解析接口幂等号:优先使用请求体,再使用请求头,最后生成新的 UUID。
|
||||
* 生成账单、确认、作废和导出都依赖该值避免重复提交。
|
||||
*/
|
||||
private String requestId(String bodyRequestId, String headerRequestId) {
|
||||
if (StringUtils.isNotEmpty(bodyRequestId)) return bodyRequestId;
|
||||
if (StringUtils.isNotEmpty(headerRequestId)) return headerRequestId;
|
||||
return IdUtils.fastSimpleUUID();
|
||||
|
||||
@@ -29,8 +29,8 @@ spring:
|
||||
connectTimeout: 30000
|
||||
# 配置网络超时时间
|
||||
socketTimeout: 60000
|
||||
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
|
||||
timeBetweenEvictionRunsMillis: 60000
|
||||
# 配置间隔多久检测一次空闲连接,避免远程数据库断开后连接池继续复用失效连接,单位是毫秒
|
||||
timeBetweenEvictionRunsMillis: 30000
|
||||
# 配置一个连接在池中最小生存的时间,单位是毫秒
|
||||
minEvictableIdleTimeMillis: 300000
|
||||
# 配置一个连接在池中最大生存的时间,单位是毫秒
|
||||
@@ -38,7 +38,8 @@ spring:
|
||||
# 配置检测连接是否有效
|
||||
validationQuery: SELECT 1 FROM DUAL
|
||||
testWhileIdle: true
|
||||
testOnBorrow: false
|
||||
# 异步账单任务借用连接时校验连接有效性,避免拿到已被数据库断开的连接
|
||||
testOnBorrow: true
|
||||
testOnReturn: false
|
||||
webStatFilter:
|
||||
enabled: true
|
||||
@@ -59,4 +60,4 @@ spring:
|
||||
merge-sql: true
|
||||
wall:
|
||||
config:
|
||||
multi-statement-allow: true
|
||||
multi-statement-allow: true
|
||||
|
||||
@@ -26,9 +26,11 @@
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<!-- Java 26 编译环境使用新版 Lombok,确保模型类的 getter/setter 正常生成。 -->
|
||||
<version>1.18.46</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ruoyi.ar.config;
|
||||
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
/** 应收账单大文件导出专用线程池。 */
|
||||
@Configuration
|
||||
public class ArBillExportTaskConfig
|
||||
{
|
||||
/**
|
||||
* 账单导出会同时占用数据库连接、CPU 和磁盘,最多允许两个任务并发生成。
|
||||
* 队列满时由提交器将任务标记为失败,避免回退到 Web 请求线程执行。
|
||||
*/
|
||||
@Bean(name = "arBillExportTaskExecutor")
|
||||
public ThreadPoolTaskExecutor arBillExportTaskExecutor()
|
||||
{
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(2);
|
||||
executor.setMaxPoolSize(2);
|
||||
executor.setQueueCapacity(2);
|
||||
executor.setKeepAliveSeconds(60);
|
||||
executor.setThreadNamePrefix("ar-bill-export-");
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
|
||||
return executor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 账单生成会同时占用数据库连接、CPU 和磁盘,2核4G环境下先限制为单任务串行处理。
|
||||
*/
|
||||
@Bean(name = "arBillGenerateTaskExecutor")
|
||||
public ThreadPoolTaskExecutor arBillGenerateTaskExecutor()
|
||||
{
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(1);
|
||||
executor.setMaxPoolSize(1);
|
||||
executor.setQueueCapacity(5);
|
||||
executor.setKeepAliveSeconds(60);
|
||||
executor.setThreadNamePrefix("ar-bill-generate-");
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,15 @@ package com.ruoyi.ar.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/** 公司收款账户配置。 */
|
||||
/**
|
||||
* 公司收款账户配置。
|
||||
*/
|
||||
@Data
|
||||
public class ArBankAccount implements Serializable
|
||||
{
|
||||
public class ArBankAccount implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long bankAccountId;
|
||||
|
||||
@@ -3,41 +3,72 @@ package com.ruoyi.ar.domain;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import com.ruoyi.common.core.domain.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/** 正式应收账单。 */
|
||||
/**
|
||||
* 正式应收账单。
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class ArBill extends BaseEntity
|
||||
{
|
||||
public class ArBill extends BaseEntity {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 账单头主键。
|
||||
*/
|
||||
private Long arBillId;
|
||||
/**
|
||||
* 对外展示的账单编号。
|
||||
*/
|
||||
private String billNo;
|
||||
/**
|
||||
* 财务填写的账单名称。
|
||||
*/
|
||||
private String billName;
|
||||
/**
|
||||
* 账单所属客户主键。
|
||||
*/
|
||||
private Long customerId;
|
||||
private String customerCode;
|
||||
private String customerName;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
/** 账单所属期开始日期,导出模板展示用。 */
|
||||
private Date billPeriodStart;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
/** 账单所属期结束日期,同时作为生成订单的截止日期。 */
|
||||
private Date billPeriodEnd;
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date billDate;
|
||||
private String currency;
|
||||
private Integer orderCount;
|
||||
/**
|
||||
* 账单明细应收金额合计。
|
||||
*/
|
||||
private BigDecimal totalAmount;
|
||||
/**
|
||||
* 已通过余额核销的金额。
|
||||
*/
|
||||
private BigDecimal writtenOffAmount;
|
||||
/**
|
||||
* 尚未核销的金额,核销入口按此字段判断是否可操作。
|
||||
*/
|
||||
private BigDecimal unwrittenAmount;
|
||||
/** 状态:DRAFT草稿、CONFIRMED已确认、PARTIAL_WRITTEN_OFF部分核销、WRITTEN_OFF已核销、VOID已作废。 */
|
||||
/**
|
||||
* 状态:DRAFT草稿、CONFIRMED已确认、PARTIAL_WRITTEN_OFF部分核销、WRITTEN_OFF已核销、VOID已作废。
|
||||
*/
|
||||
private String status;
|
||||
/**
|
||||
* 生成状态:GENERATING生成中、READY可用、FAILED生成失败。
|
||||
*/
|
||||
private String generationStatus;
|
||||
private Integer billVersion;
|
||||
private String bankAccountName;
|
||||
private String bankAccountNo;
|
||||
@@ -47,7 +78,16 @@ public class ArBill extends BaseEntity
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date confirmedTime;
|
||||
|
||||
/**
|
||||
* 账单明细;详情接口分页查询时通常不直接填充该集合。
|
||||
*/
|
||||
private List<ArBillDetail> details;
|
||||
/**
|
||||
* 当前账单的导出历史。
|
||||
*/
|
||||
private List<ArBillExport> exports;
|
||||
/**
|
||||
* 当前账单的操作日志。
|
||||
*/
|
||||
private List<ArBillLog> logs;
|
||||
}
|
||||
|
||||
@@ -4,13 +4,15 @@ import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/** 账单订单快照。 */
|
||||
/**
|
||||
* 账单订单快照。
|
||||
*/
|
||||
@Data
|
||||
public class ArBillDetail implements Serializable
|
||||
{
|
||||
public class ArBillDetail implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long detailId;
|
||||
|
||||
@@ -3,13 +3,15 @@ package com.ruoyi.ar.domain;
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/** 账单费用快照。 */
|
||||
/**
|
||||
* 账单费用快照。
|
||||
*/
|
||||
@Data
|
||||
public class ArBillDetailFee implements Serializable
|
||||
{
|
||||
public class ArBillDetailFee implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long detailFeeId;
|
||||
|
||||
@@ -2,26 +2,49 @@ package com.ruoyi.ar.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/** 账单导出文件元数据。 */
|
||||
/**
|
||||
* 账单导出文件元数据。
|
||||
*/
|
||||
@Data
|
||||
public class ArBillExport implements Serializable
|
||||
{
|
||||
public class ArBillExport implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long exportId;
|
||||
private Long arBillId;
|
||||
private String fileName;
|
||||
private String fileType;
|
||||
/**
|
||||
* 提交导出任务时绑定的模板版本,避免后续模板变更影响历史任务。
|
||||
*/
|
||||
private Long templateId;
|
||||
private String templateCode;
|
||||
private String templateVersion;
|
||||
private String templateStorageType;
|
||||
private String templateStorageKey;
|
||||
private String templateHash;
|
||||
/**
|
||||
* 生成文件的实际存储键,下载接口据此读取文件。
|
||||
*/
|
||||
private String storageKey;
|
||||
/**
|
||||
* 文件字节数,便于前端展示和运维排查。
|
||||
*/
|
||||
private Long fileSize;
|
||||
/**
|
||||
* 文件摘要,用于校验文件完整性。
|
||||
*/
|
||||
private String fileHash;
|
||||
/**
|
||||
* 导出的明细行数。
|
||||
*/
|
||||
private Integer rowCount;
|
||||
/** 导出状态:PROCESSING生成中、SUCCESS成功可下载、FAILED失败。 */
|
||||
/**
|
||||
* 导出状态:PROCESSING生成中、SUCCESS成功可下载、FAILED失败。
|
||||
*/
|
||||
private String exportStatus;
|
||||
private String exportBy;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.ruoyi.ar.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 应收账单异步生成任务。
|
||||
*/
|
||||
@Data
|
||||
public class ArBillGenerateTask implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 异步任务主键。
|
||||
*/
|
||||
private Long taskId;
|
||||
/**
|
||||
* 面向日志和前端展示的任务编号。
|
||||
*/
|
||||
private String taskNo;
|
||||
/**
|
||||
* 任务对应的账单头主键。
|
||||
*/
|
||||
private Long arBillId;
|
||||
/**
|
||||
* 订单选择模式 code:EXPLICIT=手动选中,ALL_MATCHED=全选查询结果。
|
||||
*/
|
||||
private String selectionMode;
|
||||
/**
|
||||
* 生成请求快照,避免任务执行过程中依赖前端当前条件。
|
||||
*/
|
||||
private String requestPayload;
|
||||
/**
|
||||
* 任务创建时的来源订单创建时间快照。
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date snapshotCreateTime;
|
||||
/**
|
||||
* 按 bill_id 字典序处理的游标。
|
||||
*/
|
||||
private String lastSourceBillId;
|
||||
/**
|
||||
* 待处理总数;全选模式统计完成前使用 -1。
|
||||
*/
|
||||
private Integer totalCount;
|
||||
/**
|
||||
* 已扫描的来源订单数,用于进度展示。
|
||||
*/
|
||||
private Integer processedCount;
|
||||
/**
|
||||
* 成功写入账单明细的订单数。
|
||||
*/
|
||||
private Integer successCount;
|
||||
/**
|
||||
* 已写入账单明细的累计应收金额。
|
||||
*/
|
||||
private BigDecimal totalAmount;
|
||||
/**
|
||||
* 任务状态,取 ArBillGenerateTaskStatus 中定义的值。
|
||||
*/
|
||||
private String status;
|
||||
/**
|
||||
* 失败、取消或补偿清理时返回给用户的说明。
|
||||
*/
|
||||
private String errorMessage;
|
||||
/**
|
||||
* 请求幂等号,防止重复创建账单生成任务。
|
||||
*/
|
||||
private String requestToken;
|
||||
/**
|
||||
* 发起任务的用户。
|
||||
*/
|
||||
private String createBy;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private Date createTime;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
/** 首次被执行器领取的时间。 */
|
||||
private Date startedAt;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
/** 最近一次进度更新时间,用于识别执行节点异常。 */
|
||||
private Date heartbeatTime;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
/** 成功、失败或取消完成的时间。 */
|
||||
private Date finishedAt;
|
||||
}
|
||||
@@ -2,23 +2,31 @@ package com.ruoyi.ar.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
/** 应收模块追加式审计日志。 */
|
||||
/**
|
||||
* 应收模块追加式审计日志。
|
||||
*/
|
||||
@Data
|
||||
public class ArBillLog implements Serializable
|
||||
{
|
||||
public class ArBillLog implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long logId;
|
||||
private Long arBillId;
|
||||
/** 对象类型:BILL应收账单、EXPORT账单导出、BALANCE_WRITEOFF余额核销。 */
|
||||
/**
|
||||
* 对象类型:BILL应收账单、EXPORT账单导出、BALANCE_WRITEOFF余额核销。
|
||||
*/
|
||||
private String objectType;
|
||||
private String objectId;
|
||||
/** 对象业务标识,例如账单号、收款单号或核销单号。 */
|
||||
/**
|
||||
* 对象业务标识,例如账单号、收款单号或核销单号。
|
||||
*/
|
||||
private String objectDisplay;
|
||||
/** 操作类型,取值由 ArLogOperationType 维护。 */
|
||||
/**
|
||||
* 操作类型,取值由 ArLogOperationType 维护。
|
||||
*/
|
||||
private String operationType;
|
||||
private String operationDesc;
|
||||
private String fromStatus;
|
||||
@@ -27,11 +35,15 @@ public class ArBillLog implements Serializable
|
||||
private String afterData;
|
||||
private String operatorId;
|
||||
private String operatorName;
|
||||
/** 操作来源:WEB网页端、API接口、JOB定时任务、IMPORT数据导入。 */
|
||||
/**
|
||||
* 操作来源:WEB网页端、API接口、JOB定时任务、IMPORT数据导入。
|
||||
*/
|
||||
private String operationSource;
|
||||
private String requestId;
|
||||
private String traceId;
|
||||
/** 操作结果:SUCCESS成功、FAILED失败。 */
|
||||
/**
|
||||
* 操作结果:SUCCESS成功、FAILED失败。
|
||||
*/
|
||||
private String result;
|
||||
private String errorMessage;
|
||||
private String clientIp;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ruoyi.ar.domain;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 应收账单导出模板元数据。
|
||||
*/
|
||||
@Data
|
||||
public class ArExportTemplate implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long templateId;
|
||||
private String templateCode;
|
||||
private String templateName;
|
||||
private String businessType;
|
||||
private String templateVersion;
|
||||
private String storageType;
|
||||
private String storageKey;
|
||||
private String fileHash;
|
||||
private String status;
|
||||
private String isDefault;
|
||||
private Date effectiveStart;
|
||||
private Date effectiveEnd;
|
||||
private String remark;
|
||||
}
|
||||
@@ -16,4 +16,10 @@ public class ArBillGenerateQuery
|
||||
private Date billPeriodEnd;
|
||||
|
||||
private String currency;
|
||||
|
||||
/** 订单号或运单号关键词,按 OR 条件模糊查询。 */
|
||||
private String orderOrTrackingNo;
|
||||
|
||||
/** 全选模式下,排除弹窗使用的附加订单号或运单号关键词。 */
|
||||
private String excludeOrderOrTrackingNo;
|
||||
}
|
||||
|
||||
+9
-2
@@ -4,8 +4,8 @@ import java.util.Date;
|
||||
import java.util.List;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import com.ruoyi.ar.enums.ArBillSelectionMode;
|
||||
import lombok.Data;
|
||||
|
||||
/** 从订单计费结果生成正式账单的参数。 */
|
||||
@@ -21,14 +21,21 @@ public class ArBillGenerateRequest
|
||||
@NotNull(message = "账单截止日不能为空")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date billPeriodEnd;
|
||||
@NotEmpty(message = "请至少选择一条订单")
|
||||
/** 手动模式选中的来源订单 ID;全选模式为空。 */
|
||||
private List<String> sourceBillIds;
|
||||
/** 选择模式:EXPLICIT 手动选择,ALL_MATCHED 全选查询结果。 */
|
||||
private String selectionMode = ArBillSelectionMode.EXPLICIT.getCode();
|
||||
/** 全选模式中用户明确排除的来源订单 ID。 */
|
||||
private List<String> excludedSourceBillIds;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd")
|
||||
private Date billDate;
|
||||
private String currency = "CNY";
|
||||
/** 订单号或运单号关键词,生成时用于再次校验筛选条件。 */
|
||||
private String orderOrTrackingNo;
|
||||
private String bankAccountName;
|
||||
private String bankAccountNo;
|
||||
private String bankName;
|
||||
private String remark;
|
||||
/** 前端幂等号;重复提交同一请求时复用原任务。 */
|
||||
private String requestId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.ruoyi.ar.enums;
|
||||
|
||||
/** 应收账单异步生成任务状态。 */
|
||||
public final class ArBillGenerateTaskStatus
|
||||
{
|
||||
/** 待线程池领取的任务。 */
|
||||
public static final String WAITING = "WAITING";
|
||||
/** 已被某个执行节点领取,正在生成明细。 */
|
||||
public static final String RUNNING = "RUNNING";
|
||||
/** 明细全部生成成功。 */
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
/** 生成失败,账单已进入失败状态。 */
|
||||
public static final String FAILED = "FAILED";
|
||||
/** 用户已请求取消,执行器会在安全边界清理已生成数据。 */
|
||||
public static final String CANCEL_REQUESTED = "CANCEL_REQUESTED";
|
||||
/** 取消清理完成,账单及其生成明细已回收。 */
|
||||
public static final String CANCELED = "CANCELED";
|
||||
|
||||
private ArBillGenerateTaskStatus()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ruoyi.ar.enums;
|
||||
|
||||
/** 应收账单生成状态,与账单业务状态分离。 */
|
||||
public final class ArBillGenerationStatus
|
||||
{
|
||||
/** 账单头已创建,明细和费用正在异步生成。 */
|
||||
public static final String GENERATING = "GENERATING";
|
||||
/** 明细生成完成,允许确认、核销和导出。 */
|
||||
public static final String READY = "READY";
|
||||
/** 明细生成失败或取消后已完成清理。 */
|
||||
public static final String FAILED = "FAILED";
|
||||
|
||||
private ArBillGenerationStatus()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.ruoyi.ar.enums;
|
||||
|
||||
/**
|
||||
* 应收账单生成时的订单选择模式。
|
||||
* 数据库和接口仍保存英文 code,业务代码通过枚举统一校验和判断。
|
||||
*/
|
||||
public enum ArBillSelectionMode
|
||||
{
|
||||
/** 手动选择当前预览结果中的订单。 */
|
||||
EXPLICIT("EXPLICIT", "手动选择"),
|
||||
/** 选择全部查询结果,仅排除用户明确勾选的订单。 */
|
||||
ALL_MATCHED("ALL_MATCHED", "全选查询结果");
|
||||
|
||||
private final String code;
|
||||
private final String label;
|
||||
|
||||
ArBillSelectionMode(String code, String label)
|
||||
{
|
||||
this.code = code;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String getCode()
|
||||
{
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getLabel()
|
||||
{
|
||||
return label;
|
||||
}
|
||||
|
||||
/** 空值按历史默认行为视为手动选择,非法非空值返回 null 交由业务层记录失败日志。 */
|
||||
public static ArBillSelectionMode of(String code)
|
||||
{
|
||||
if (code == null || code.trim().isEmpty())
|
||||
{
|
||||
return EXPLICIT;
|
||||
}
|
||||
for (ArBillSelectionMode mode : values())
|
||||
{
|
||||
if (mode.code.equalsIgnoreCase(code.trim()))
|
||||
{
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -28,16 +28,19 @@ public enum ArBillStatus
|
||||
return label;
|
||||
}
|
||||
|
||||
/** 只有草稿账单允许确认。 */
|
||||
public boolean canConfirm()
|
||||
{
|
||||
return this == DRAFT;
|
||||
}
|
||||
|
||||
/** 草稿或已确认账单允许作废;已核销账单不可直接作废。 */
|
||||
public boolean canVoid()
|
||||
{
|
||||
return this == DRAFT || this == CONFIRMED;
|
||||
}
|
||||
|
||||
/** 已确认或部分核销账单允许继续核销。 */
|
||||
public boolean canWriteOff()
|
||||
{
|
||||
return this == CONFIRMED || this == PARTIAL_WRITTEN_OFF;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ruoyi.ar.event;
|
||||
|
||||
/**
|
||||
* 应收账单导出任务已提交事件。
|
||||
*
|
||||
* <p>由事务提交后监听器处理,确保异步线程读取到已落库的导出任务。</p>
|
||||
*/
|
||||
public class ArBillExportTaskEvent
|
||||
{
|
||||
private final Long exportId;
|
||||
|
||||
public ArBillExportTaskEvent(Long exportId)
|
||||
{
|
||||
this.exportId = exportId;
|
||||
}
|
||||
|
||||
public Long getExportId()
|
||||
{
|
||||
return exportId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ruoyi.ar.event;
|
||||
|
||||
/**
|
||||
* 应收账单异步生成任务已提交事件。
|
||||
* 监听器在创建账单事务提交后消费,避免后台线程读取到未提交的任务或账单头。
|
||||
*/
|
||||
public class ArBillGenerateTaskEvent
|
||||
{
|
||||
/** 待投递的生成任务主键。 */
|
||||
private final Long taskId;
|
||||
|
||||
public ArBillGenerateTaskEvent(Long taskId)
|
||||
{
|
||||
this.taskId = taskId;
|
||||
}
|
||||
|
||||
public Long getTaskId()
|
||||
{
|
||||
return taskId;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.ruoyi.ar.mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBankAccount;
|
||||
|
||||
public interface ArBankAccountMapper
|
||||
{
|
||||
public interface ArBankAccountMapper {
|
||||
ArBankAccount selectDefaultByCurrency(@Param("currency") String currency);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
package com.ruoyi.ar.mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBillDetailFee;
|
||||
|
||||
public interface ArBillDetailFeeMapper
|
||||
{
|
||||
public interface ArBillDetailFeeMapper {
|
||||
List<ArBillDetailFee> selectByDetailId(Long detailId);
|
||||
|
||||
List<ArBillDetailFee> selectByBillIdAndDetailId(@Param("arBillId") Long arBillId,
|
||||
@Param("detailId") Long detailId);
|
||||
|
||||
List<ArBillDetailFee> selectByBillId(Long arBillId);
|
||||
|
||||
List<ArBillDetailFee> selectByDetailIds(@Param("detailIds") List<Long> detailIds);
|
||||
|
||||
int insert(ArBillDetailFee fee);
|
||||
|
||||
int insertBatch(List<ArBillDetailFee> fees);
|
||||
|
||||
int deleteByBillId(Long arBillId);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,27 @@
|
||||
package com.ruoyi.ar.mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBillDetail;
|
||||
|
||||
public interface ArBillDetailMapper
|
||||
{
|
||||
public interface ArBillDetailMapper {
|
||||
List<ArBillDetail> selectByBillId(Long arBillId);
|
||||
|
||||
/** 查询账单明细及费用明细,避免详情页逐层查询。 */
|
||||
List<ArBillDetail> selectByBillIdAndSourceIds(@Param("arBillId") Long arBillId,
|
||||
@Param("sourceBillIds") List<String> sourceBillIds);
|
||||
|
||||
/**
|
||||
* 查询账单明细及费用明细,避免详情页逐层查询。
|
||||
*/
|
||||
List<ArBillDetail> selectByBillIdWithFees(Long arBillId);
|
||||
|
||||
List<ArBillDetail> selectExportPage(@Param("arBillId") Long arBillId,
|
||||
@Param("lastDetailNo") Integer lastDetailNo, @Param("pageSize") Integer pageSize);
|
||||
|
||||
int insert(ArBillDetail detail);
|
||||
|
||||
int insertBatch(List<ArBillDetail> details);
|
||||
|
||||
int deleteByBillId(Long arBillId);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
package com.ruoyi.ar.mapper;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBillExport;
|
||||
|
||||
public interface ArBillExportMapper
|
||||
{
|
||||
public interface ArBillExportMapper {
|
||||
List<ArBillExport> selectByBillId(Long arBillId);
|
||||
|
||||
ArBillExport selectById(Long exportId);
|
||||
|
||||
ArBillExport selectLatestSuccessByBillId(Long arBillId);
|
||||
|
||||
ArBillExport selectProcessingByBillId(Long arBillId);
|
||||
|
||||
int insert(ArBillExport export);
|
||||
|
||||
int markSuccess(ArBillExport export);
|
||||
|
||||
int markFailed(@Param("exportId") Long exportId, @Param("remark") String remark);
|
||||
|
||||
int markExpiredProcessingAsFailed(@Param("expiredBefore") Date expiredBefore, @Param("remark") String remark);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ruoyi.ar.mapper;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBillGenerateTask;
|
||||
|
||||
/**
|
||||
* 应收账单异步生成任务 Mapper。
|
||||
*/
|
||||
public interface ArBillGenerateTaskMapper {
|
||||
ArBillGenerateTask selectById(Long taskId);
|
||||
|
||||
ArBillGenerateTask selectByRequestToken(String requestToken);
|
||||
|
||||
List<ArBillGenerateTask> selectActiveByCreateBy(@Param("createBy") String createBy);
|
||||
|
||||
List<ArBillGenerateTask> selectWaiting(@Param("limit") int limit);
|
||||
|
||||
int insert(ArBillGenerateTask task);
|
||||
|
||||
int markRunning(@Param("taskId") Long taskId, @Param("startedAt") Date startedAt);
|
||||
|
||||
int updateTotalCount(@Param("taskId") Long taskId, @Param("totalCount") Integer totalCount);
|
||||
|
||||
int updateProgress(@Param("taskId") Long taskId, @Param("lastSourceBillId") String lastSourceBillId,
|
||||
@Param("processedCount") Integer processedCount, @Param("successCount") Integer successCount,
|
||||
@Param("totalAmount") java.math.BigDecimal totalAmount, @Param("heartbeatTime") Date heartbeatTime);
|
||||
|
||||
int markSuccess(@Param("taskId") Long taskId, @Param("finishedAt") Date finishedAt);
|
||||
|
||||
int markFailed(@Param("taskId") Long taskId, @Param("errorMessage") String errorMessage,
|
||||
@Param("finishedAt") Date finishedAt);
|
||||
|
||||
int markCancelRequested(@Param("taskId") Long taskId);
|
||||
|
||||
int markCanceled(@Param("taskId") Long taskId, @Param("finishedAt") Date finishedAt);
|
||||
|
||||
int resetExpiredRunning(@Param("expiredBefore") Date expiredBefore);
|
||||
|
||||
List<ArBillGenerateTask> selectCancelRequestedBefore(@Param("expiredBefore") Date expiredBefore,
|
||||
@Param("limit") int limit);
|
||||
}
|
||||
@@ -3,35 +3,49 @@ package com.ruoyi.ar.mapper;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArBill;
|
||||
import com.ruoyi.ar.domain.vo.ArBillQuery;
|
||||
|
||||
public interface ArBillMapper
|
||||
{
|
||||
public interface ArBillMapper {
|
||||
List<ArBill> selectArBillList(ArBillQuery query);
|
||||
|
||||
ArBill selectArBillById(Long arBillId);
|
||||
|
||||
ArBill selectArBillByBillNo(String billNo);
|
||||
|
||||
ArBill selectGeneratingByCustomerPeriod(@Param("customerId") Long customerId,
|
||||
@Param("currency") String currency, @Param("cutoffDate") Date cutoffDate);
|
||||
|
||||
Integer selectMaxBillVersion(@Param("customerId") Long customerId,
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency);
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency);
|
||||
|
||||
ArBill selectArBillByIdForUpdate(Long arBillId);
|
||||
|
||||
/** 查询客户可核销账单(已确认/部分核销),按账单日期升序,供余额核销选择 */
|
||||
/**
|
||||
* 查询客户可核销账单(已确认/部分核销),按账单日期升序,供余额核销选择
|
||||
*/
|
||||
List<ArBill> selectUnsettledByCustomer(@Param("customerId") Long customerId);
|
||||
|
||||
int insertArBill(ArBill bill);
|
||||
|
||||
int updateArBillStatus(@Param("arBillId") Long arBillId, @Param("status") String status,
|
||||
@Param("remark") String remark, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus);
|
||||
@Param("remark") String remark, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus);
|
||||
|
||||
int updateArBillAmounts(@Param("arBillId") Long arBillId,
|
||||
@Param("writtenOffAmount") BigDecimal writtenOffAmount,
|
||||
@Param("unwrittenAmount") BigDecimal unwrittenAmount,
|
||||
@Param("status") String status, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus);
|
||||
@Param("writtenOffAmount") BigDecimal writtenOffAmount,
|
||||
@Param("unwrittenAmount") BigDecimal unwrittenAmount,
|
||||
@Param("status") String status, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus);
|
||||
|
||||
int updateArBillProgress(@Param("arBillId") Long arBillId,
|
||||
@Param("orderCount") Integer orderCount, @Param("totalAmount") BigDecimal totalAmount,
|
||||
@Param("unwrittenAmount") BigDecimal unwrittenAmount,
|
||||
@Param("billPeriodStart") Date billPeriodStart, @Param("operator") String operator);
|
||||
|
||||
int updateArBillGenerationStatus(@Param("arBillId") Long arBillId,
|
||||
@Param("generationStatus") String generationStatus, @Param("operator") String operator,
|
||||
@Param("remark") String remark);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ruoyi.ar.mapper;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.ruoyi.ar.domain.ArExportTemplate;
|
||||
|
||||
public interface ArExportTemplateMapper {
|
||||
/**
|
||||
* 查询指定业务类型当前生效的默认模板。
|
||||
*/
|
||||
ArExportTemplate selectDefaultEnabled(@Param("businessType") String businessType,
|
||||
@Param("effectiveDate") Date effectiveDate);
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
package com.ruoyi.ar.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ruoyi.ar.domain.ArBillLog;
|
||||
import com.ruoyi.ar.enums.ArLogObjectType;
|
||||
import com.ruoyi.ar.enums.ArLogOperationType;
|
||||
|
||||
public interface IArBillLogService
|
||||
{
|
||||
public interface IArBillLogService {
|
||||
List<ArBillLog> selectLogList(ArBillLog query);
|
||||
|
||||
void record(ArBillLog log);
|
||||
|
||||
void recordFailure(Long arBillId, ArLogObjectType objectType, String objectId, ArLogOperationType operationType,
|
||||
String fromStatus, String message, String operator, String requestId);
|
||||
String fromStatus, String message, String operator, String requestId);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
package com.ruoyi.ar.service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import com.ruoyi.ar.domain.ArBill;
|
||||
import com.ruoyi.ar.domain.ArBankAccount;
|
||||
import com.ruoyi.ar.domain.ArBillDetail;
|
||||
import com.ruoyi.ar.domain.ArBillDetailFee;
|
||||
import com.ruoyi.ar.domain.ArBillExport;
|
||||
import com.ruoyi.ar.domain.ArBillGenerateTask;
|
||||
import com.ruoyi.ar.domain.ArBillLog;
|
||||
import com.ruoyi.ar.domain.vo.ArBillGenerateRequest;
|
||||
import com.ruoyi.ar.domain.vo.ArBillGenerateQuery;
|
||||
@@ -11,17 +16,48 @@ import com.ruoyi.ar.domain.vo.ArBillActionRequest;
|
||||
import com.ruoyi.ar.domain.vo.ArBillQuery;
|
||||
import com.ruoyi.price.domain.PrcOrderBill;
|
||||
|
||||
/**
|
||||
* 应收账单业务接口。
|
||||
* 查询接口面向列表/详情页面,生成和导出接口面向异步任务执行器;
|
||||
* Controller 不直接操作 Mapper,统一由这里维护业务状态和事务边界。
|
||||
*/
|
||||
public interface IArBillService
|
||||
{
|
||||
List<ArBill> selectArBillList(ArBillQuery query);
|
||||
|
||||
ArBill selectArBillById(Long arBillId);
|
||||
|
||||
List<ArBillDetail> selectArBillDetails(Long arBillId);
|
||||
|
||||
List<ArBillDetailFee> selectArBillDetailFees(Long arBillId, Long detailId);
|
||||
|
||||
ArBankAccount getDefaultBankAccount(String currency);
|
||||
|
||||
List<PrcOrderBill> previewBill(ArBillGenerateQuery query);
|
||||
|
||||
ArBill generateBill(ArBillGenerateRequest request, String operator, String requestId);
|
||||
BigDecimal sumPreviewBill(ArBillGenerateQuery query);
|
||||
|
||||
ArBillGenerateTask generateBill(ArBillGenerateRequest request, String operator, String requestId);
|
||||
|
||||
ArBillGenerateTask selectGenerateTask(Long taskId);
|
||||
|
||||
List<ArBillGenerateTask> selectActiveGenerateTasks(String operator);
|
||||
|
||||
ArBillGenerateTask cancelGenerateTask(Long taskId, String operator, String requestId);
|
||||
|
||||
ArBillGenerateTask retryGenerateTask(Long taskId, String operator, String requestId);
|
||||
|
||||
void processGenerateTask(Long taskId);
|
||||
|
||||
boolean claimGenerateTask(Long taskId);
|
||||
|
||||
void failGenerateTask(Long taskId, String remark);
|
||||
|
||||
int recoverExpiredGenerateTasks(Date expiredBefore);
|
||||
|
||||
int recoverCancelRequestedGenerateTasks(Date expiredBefore);
|
||||
|
||||
List<ArBillGenerateTask> selectWaitingGenerateTasks(int limit);
|
||||
|
||||
ArBill confirmBill(Long arBillId, ArBillActionRequest request, String operator, String requestId);
|
||||
|
||||
@@ -29,6 +65,14 @@ public interface IArBillService
|
||||
|
||||
ArBillExport exportBill(Long arBillId, String operator, String requestId);
|
||||
|
||||
ArBillExport selectExport(Long exportId);
|
||||
|
||||
void processExportTask(Long exportId);
|
||||
|
||||
void failExportTask(Long exportId, String remark);
|
||||
|
||||
int failExpiredExportTasks(Date expiredBefore);
|
||||
|
||||
List<ArBillExport> selectExports(Long arBillId);
|
||||
|
||||
void downloadExport(Long exportId, jakarta.servlet.http.HttpServletResponse response) throws Exception;
|
||||
|
||||
+51
-59
@@ -7,6 +7,7 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -39,8 +40,7 @@ import com.ruoyi.customer.customermoney.domain.CustomerBalanceFlow;
|
||||
* @date 2026-09-16
|
||||
*/
|
||||
@Service
|
||||
public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
{
|
||||
public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService {
|
||||
private static final DateTimeFormatter NO_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
|
||||
private static final int MONEY_SCALE = 2;
|
||||
|
||||
@@ -56,55 +56,55 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
@Autowired
|
||||
private ICustomerAccountApi customerAccountApi;
|
||||
|
||||
/**
|
||||
* 按客户查询允许余额核销的未结清账单。
|
||||
*/
|
||||
@Override
|
||||
public List<ArBill> selectUnsettledBills(Long customerId)
|
||||
{
|
||||
if (customerId == null)
|
||||
{
|
||||
public List<ArBill> selectUnsettledBills(Long customerId) {
|
||||
if (customerId == null) {
|
||||
return List.of();
|
||||
}
|
||||
return billMapper.selectUnsettledByCustomer(customerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询账单余额核销记录列表。
|
||||
*/
|
||||
@Override
|
||||
public List<ArBalanceWriteoff> selectWriteoffList(ArBalanceWriteoff query)
|
||||
{
|
||||
public List<ArBalanceWriteoff> selectWriteoffList(ArBalanceWriteoff query) {
|
||||
return writeoffMapper.selectWriteoffList(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行余额核销主流程:锁账单、登记核销单、扣减客户余额、更新账单金额和状态。
|
||||
* 任一步失败都会回滚当前事务,避免核销单、资金流水和账单状态不一致。
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ArBalanceWriteoff writeoff(ArBalanceWriteoff cmd)
|
||||
{
|
||||
if (cmd == null || cmd.getArBillId() == null)
|
||||
{
|
||||
public ArBalanceWriteoff writeoff(ArBalanceWriteoff cmd) {
|
||||
if (cmd == null || cmd.getArBillId() == null) {
|
||||
throw new ServiceException("请选择要核销的账单");
|
||||
}
|
||||
BigDecimal amount = cmd.getWriteoffAmount();
|
||||
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0)
|
||||
{
|
||||
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
throw new ServiceException("核销金额必须大于0");
|
||||
}
|
||||
amount = amount.setScale(MONEY_SCALE, RoundingMode.HALF_UP);
|
||||
|
||||
// 1. 行锁锁定账单(加锁顺序:账单 -> 账户,与反核销保持一致)
|
||||
ArBill bill = billMapper.selectArBillByIdForUpdate(cmd.getArBillId());
|
||||
if (bill == null)
|
||||
{
|
||||
if (bill == null) {
|
||||
throw new ServiceException("应收账单不存在");
|
||||
}
|
||||
ArBillStatus status = ArBillStatus.of(bill.getStatus());
|
||||
if (status == null || !status.canWriteOff())
|
||||
{
|
||||
if (status == null || !status.canWriteOff()) {
|
||||
throw new ServiceException("当前账单状态不允许核销:" + (status == null ? bill.getStatus() : status.getLabel()));
|
||||
}
|
||||
if (cmd.getCustomerId() != null && !cmd.getCustomerId().equals(bill.getCustomerId()))
|
||||
{
|
||||
if (cmd.getCustomerId() != null && !cmd.getCustomerId().equals(bill.getCustomerId())) {
|
||||
throw new ServiceException("账单与所选客户不匹配");
|
||||
}
|
||||
BigDecimal unwritten = nvl(bill.getUnwrittenAmount());
|
||||
if (amount.compareTo(unwritten) > 0)
|
||||
{
|
||||
if (amount.compareTo(unwritten) > 0) {
|
||||
throw new ServiceException("核销金额超过账单未核销金额:" + unwritten.toPlainString());
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
|
||||
// 3. 扣减账户余额并释放等额已用额度,写 BILL_PAY 扣款流水(余额不足在此处拦截)
|
||||
String flowRemark = "余额核销账单:" + bill.getBillNo()
|
||||
+ (StringUtils.hasText(writeoff.getRemark()) ? "(" + writeoff.getRemark() + ")" : "");
|
||||
+ (StringUtils.hasText(writeoff.getRemark()) ? "(" + writeoff.getRemark() + ")" : "");
|
||||
BalanceChangeCommand payCmd = new BalanceChangeCommand();
|
||||
payCmd.setCustomerId(bill.getCustomerId());
|
||||
payCmd.setCurrency(currency);
|
||||
@@ -147,40 +147,38 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
BigDecimal newUnwritten = unwritten.subtract(amount);
|
||||
String nextStatus = billStatus(written, nvl(bill.getTotalAmount()), fromStatus);
|
||||
if (billMapper.updateArBillAmounts(bill.getArBillId(), written, newUnwritten,
|
||||
nextStatus, operator, fromStatus) != 1)
|
||||
{
|
||||
nextStatus, operator, fromStatus) != 1) {
|
||||
throw new ServiceException("账单状态已发生变化,请刷新后重试");
|
||||
}
|
||||
|
||||
recordLog(bill.getArBillId(), writeoff.getWriteoffId(), ArLogOperationType.BALANCE_WRITEOFF,
|
||||
"账户余额核销账单 " + amount.toPlainString() + " " + currency,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
"账户余额核销账单 " + amount.toPlainString() + " " + currency,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
writeoff.setAccountId(flow.getAccountId());
|
||||
writeoff.setBalanceFlowId(flow.getId());
|
||||
return writeoff;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行反核销主流程:锁定核销单和账单、回补客户余额、恢复账单未核销金额,
|
||||
* 最后将原核销记录标记为已取消。
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void cancelWriteoff(Long writeoffId, String remark)
|
||||
{
|
||||
if (writeoffId == null)
|
||||
{
|
||||
public void cancelWriteoff(Long writeoffId, String remark) {
|
||||
if (writeoffId == null) {
|
||||
throw new ServiceException("核销记录不存在");
|
||||
}
|
||||
// 1. 锁核销单 -> 锁账单(与核销相同的加锁顺序)
|
||||
ArBalanceWriteoff writeoff = writeoffMapper.selectByIdForUpdate(writeoffId);
|
||||
if (writeoff == null)
|
||||
{
|
||||
if (writeoff == null) {
|
||||
throw new ServiceException("核销记录不存在");
|
||||
}
|
||||
if (!ArBalanceWriteoffStatus.EFFECTIVE.getCode().equals(writeoff.getStatus()))
|
||||
{
|
||||
if (!ArBalanceWriteoffStatus.EFFECTIVE.getCode().equals(writeoff.getStatus())) {
|
||||
throw new ServiceException("只有有效状态的核销记录可以反核销");
|
||||
}
|
||||
ArBill bill = billMapper.selectArBillByIdForUpdate(writeoff.getArBillId());
|
||||
if (bill == null)
|
||||
{
|
||||
if (bill == null) {
|
||||
throw new ServiceException("核销关联的账单不存在");
|
||||
}
|
||||
|
||||
@@ -204,44 +202,40 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
|
||||
// 3. 账单核销金额回退,状态按剩余已核销额重算(归零则回到已确认)
|
||||
BigDecimal written = nvl(bill.getWrittenOffAmount()).subtract(nvl(writeoff.getWriteoffAmount()));
|
||||
if (written.compareTo(BigDecimal.ZERO) < 0)
|
||||
{
|
||||
if (written.compareTo(BigDecimal.ZERO) < 0) {
|
||||
written = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal newUnwritten = nvl(bill.getTotalAmount()).subtract(written);
|
||||
String nextStatus = billStatus(written, nvl(bill.getTotalAmount()), fromStatus);
|
||||
if (billMapper.updateArBillAmounts(bill.getArBillId(), written, newUnwritten,
|
||||
nextStatus, operator, fromStatus) != 1)
|
||||
{
|
||||
nextStatus, operator, fromStatus) != 1) {
|
||||
throw new ServiceException("账单状态已发生变化,请刷新后重试");
|
||||
}
|
||||
|
||||
// 4. 核销单置为CANCELLED并登记回补流水
|
||||
if (writeoffMapper.updateCancelled(writeoffId, reverseFlow.getId(), operator, cancelRemark,
|
||||
ArBalanceWriteoffStatus.CANCELLED.getCode(), ArBalanceWriteoffStatus.EFFECTIVE.getCode()) != 1)
|
||||
{
|
||||
ArBalanceWriteoffStatus.CANCELLED.getCode(), ArBalanceWriteoffStatus.EFFECTIVE.getCode()) != 1) {
|
||||
throw new ServiceException("核销记录状态已变化,请刷新后重试");
|
||||
}
|
||||
recordLog(bill.getArBillId(), writeoffId, ArLogOperationType.CANCEL_BALANCE_WRITEOFF,
|
||||
"反核销回补账单:" + cancelRemark,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
"反核销回补账单:" + cancelRemark,
|
||||
fromStatus, nextStatus, operator, requestId);
|
||||
}
|
||||
|
||||
/** 账单状态重算:已核销归零(非草稿)-> 已确认;足额 -> 已核销;否则部分核销 */
|
||||
private String billStatus(BigDecimal written, BigDecimal total, String current)
|
||||
{
|
||||
if (written.compareTo(BigDecimal.ZERO) == 0)
|
||||
{
|
||||
/**
|
||||
* 账单状态重算:归零(非草稿)为已确认,足额为已核销,否则为部分核销。
|
||||
*/
|
||||
private String billStatus(BigDecimal written, BigDecimal total, String current) {
|
||||
if (written.compareTo(BigDecimal.ZERO) == 0) {
|
||||
return ArBillStatus.DRAFT.getCode().equals(current)
|
||||
? ArBillStatus.DRAFT.getCode() : ArBillStatus.CONFIRMED.getCode();
|
||||
? ArBillStatus.DRAFT.getCode() : ArBillStatus.CONFIRMED.getCode();
|
||||
}
|
||||
return written.compareTo(total) >= 0
|
||||
? ArBillStatus.WRITTEN_OFF.getCode() : ArBillStatus.PARTIAL_WRITTEN_OFF.getCode();
|
||||
? ArBillStatus.WRITTEN_OFF.getCode() : ArBillStatus.PARTIAL_WRITTEN_OFF.getCode();
|
||||
}
|
||||
|
||||
private void recordLog(Long billId, Long writeoffId, ArLogOperationType operationType, String desc,
|
||||
String fromStatus, String toStatus, String operator, String requestId)
|
||||
{
|
||||
String fromStatus, String toStatus, String operator, String requestId) {
|
||||
ArBillLog log = new ArBillLog();
|
||||
log.setArBillId(billId);
|
||||
log.setObjectType(ArLogObjectType.BALANCE_WRITEOFF.getCode());
|
||||
@@ -258,14 +252,12 @@ public class ArBalanceWriteoffServiceImpl implements IArBalanceWriteoffService
|
||||
logService.record(log);
|
||||
}
|
||||
|
||||
private String generateNo()
|
||||
{
|
||||
private String generateNo() {
|
||||
return "BWO" + LocalDateTime.now().format(NO_FORMATTER)
|
||||
+ ThreadLocalRandom.current().nextInt(100, 1000);
|
||||
+ ThreadLocalRandom.current().nextInt(100, 1000);
|
||||
}
|
||||
|
||||
private BigDecimal nvl(BigDecimal value)
|
||||
{
|
||||
private BigDecimal nvl(BigDecimal value) {
|
||||
return value == null ? BigDecimal.ZERO : value;
|
||||
}
|
||||
}
|
||||
|
||||
+8
-9
@@ -1,6 +1,7 @@
|
||||
package com.ruoyi.ar.service.impl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
@@ -15,29 +16,27 @@ import com.ruoyi.ar.service.IArBillLogService;
|
||||
import com.ruoyi.common.utils.uuid.IdUtils;
|
||||
|
||||
@Service
|
||||
public class ArBillLogServiceImpl implements IArBillLogService
|
||||
{
|
||||
public class ArBillLogServiceImpl implements IArBillLogService {
|
||||
@Autowired
|
||||
private ArBillLogMapper logMapper;
|
||||
|
||||
@Override
|
||||
public List<ArBillLog> selectLogList(ArBillLog query)
|
||||
{
|
||||
public List<ArBillLog> selectLogList(ArBillLog query) {
|
||||
return logMapper.selectList(query);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void record(ArBillLog log)
|
||||
{
|
||||
public void record(ArBillLog log) {
|
||||
logMapper.insert(log);
|
||||
}
|
||||
|
||||
/** 失败日志必须独立提交,不能随业务异常一起回滚。 */
|
||||
/**
|
||||
* 失败日志必须独立提交,不能随业务异常一起回滚。
|
||||
*/
|
||||
@Override
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void recordFailure(Long arBillId, ArLogObjectType objectType, String objectId, ArLogOperationType operationType,
|
||||
String fromStatus, String message, String operator, String requestId)
|
||||
{
|
||||
String fromStatus, String message, String operator, String requestId) {
|
||||
ArBillLog log = new ArBillLog();
|
||||
log.setArBillId(arBillId);
|
||||
log.setObjectType(objectType.getCode());
|
||||
|
||||
+1234
-493
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,62 @@
|
||||
package com.ruoyi.ar.task;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.core.task.TaskRejectedException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
import com.ruoyi.ar.event.ArBillExportTaskEvent;
|
||||
import com.ruoyi.ar.service.IArBillService;
|
||||
|
||||
/**
|
||||
* 应收账单导出异步任务执行器。
|
||||
* 导出文件写入服务器临时目录,Web 请求只负责提交任务,完成后再提供下载。
|
||||
*/
|
||||
@Component
|
||||
public class ArBillExportTaskRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArBillExportTaskRunner.class);
|
||||
|
||||
/**
|
||||
* 导出超过 60 分钟仍未完成时,视为异常任务。
|
||||
*/
|
||||
private static final long PROCESSING_TIMEOUT_MILLIS = 60L * 60L * 1000L;
|
||||
|
||||
@Autowired
|
||||
private IArBillService billService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("arBillExportTaskExecutor")
|
||||
private ThreadPoolTaskExecutor exportTaskExecutor;
|
||||
|
||||
/**
|
||||
* 仅在提交导出任务的事务成功提交后异步执行,避免读取到未提交数据。
|
||||
*/
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
/** 事务提交后投递到导出专用线程池,避免占用请求线程。 */
|
||||
public void run(ArBillExportTaskEvent event) {
|
||||
try {
|
||||
exportTaskExecutor.execute(() -> billService.processExportTask(event.getExportId()));
|
||||
} catch (TaskRejectedException e) {
|
||||
billService.failExportTask(event.getExportId(), "导出任务较多,请稍后重新发起导出");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定期关闭因应用中断等原因长期未完成的导出任务。
|
||||
*/
|
||||
@Scheduled(cron = "0 0/5 * * * ?")
|
||||
public void failExpiredTasks() {
|
||||
Date expiredBefore = new Date(System.currentTimeMillis() - PROCESSING_TIMEOUT_MILLIS);
|
||||
int count = billService.failExpiredExportTasks(expiredBefore);
|
||||
if (count > 0) {
|
||||
log.warn("已关闭 {} 个超时的应收账单导出任务", count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.ruoyi.ar.task;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.core.task.TaskRejectedException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
import com.ruoyi.ar.domain.ArBillGenerateTask;
|
||||
import com.ruoyi.ar.event.ArBillGenerateTaskEvent;
|
||||
import com.ruoyi.ar.service.IArBillService;
|
||||
|
||||
/**
|
||||
* 应收账单异步生成任务调度器。
|
||||
*
|
||||
* <p>事务提交后立即尝试投递任务;定时补偿负责恢复节点异常、清理超时取消任务,
|
||||
* 并重新投递仍处于 WAITING 状态的任务。</p>
|
||||
*/
|
||||
@Component
|
||||
public class ArBillGenerateTaskRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArBillGenerateTaskRunner.class);
|
||||
/**
|
||||
* 生成任务超过 15 分钟没有心跳,认为执行节点异常并恢复为待处理。
|
||||
*/
|
||||
private static final long PROCESSING_TIMEOUT_MILLIS = 15L * 60L * 1000L;
|
||||
/**
|
||||
* 取消请求超过 5 分钟没有完成,交由补偿逻辑清理账单和明细。
|
||||
*/
|
||||
private static final long CANCELLATION_TIMEOUT_MILLIS = 5L * 60L * 1000L;
|
||||
|
||||
@Autowired
|
||||
private IArBillService billService;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("arBillGenerateTaskExecutor")
|
||||
private ThreadPoolTaskExecutor generateTaskExecutor;
|
||||
|
||||
/**
|
||||
* 账单生成事务提交后触发,避免事务回滚时提前执行异步任务。
|
||||
*/
|
||||
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
|
||||
public void run(ArBillGenerateTaskEvent event) {
|
||||
submit(event.getTaskId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 每 30 秒执行一次任务恢复、取消清理和待处理任务投递。
|
||||
*/
|
||||
@Scheduled(cron = "0/30 * * * * ?")
|
||||
public void recoverAndSubmitTasks() {
|
||||
try {
|
||||
Date expiredBefore = new Date(System.currentTimeMillis() - PROCESSING_TIMEOUT_MILLIS);
|
||||
int recovered = billService.recoverExpiredGenerateTasks(expiredBefore);
|
||||
if (recovered > 0) {
|
||||
log.warn("已恢复 {} 个超时的应收账单生成任务", recovered);
|
||||
}
|
||||
|
||||
Date cancellationExpiredBefore = new Date(System.currentTimeMillis() - CANCELLATION_TIMEOUT_MILLIS);
|
||||
int canceled = billService.recoverCancelRequestedGenerateTasks(cancellationExpiredBefore);
|
||||
if (canceled > 0) {
|
||||
log.warn("已自动清理 {} 个超时的应收账单取消任务", canceled);
|
||||
}
|
||||
|
||||
for (ArBillGenerateTask task : billService.selectWaitingGenerateTasks(5)) {
|
||||
submit(task.getTaskId());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("应收账单生成任务调度失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 先用数据库条件更新抢占任务,再提交到有界线程池,避免重复执行。
|
||||
*/
|
||||
private void submit(Long taskId) {
|
||||
try {
|
||||
if (!billService.claimGenerateTask(taskId)) {
|
||||
return;
|
||||
}
|
||||
generateTaskExecutor.execute(() -> billService.processGenerateTask(taskId));
|
||||
} catch (TaskRejectedException e) {
|
||||
log.error("应收账单生成任务提交线程池失败,taskId={}", taskId, e);
|
||||
try {
|
||||
billService.failGenerateTask(taskId, "生成任务较多,请稍后重新发起");
|
||||
} catch (Exception cleanupException) {
|
||||
log.error("线程池拒绝后,清理应收账单生成任务失败,taskId={}", taskId, cleanupException);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("应收账单生成任务提交失败,taskId={}", taskId, e);
|
||||
try {
|
||||
billService.failGenerateTask(taskId, "生成任务提交失败,请稍后重新发起");
|
||||
} catch (Exception cleanupException) {
|
||||
log.error("任务提交异常后,清理应收账单生成任务失败,taskId={}", taskId, cleanupException);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,36 @@ public interface PrcOrderBillMapper
|
||||
|
||||
/** 应收账单生成读取指定客户截止日期前的未出账订单计费快照。 */
|
||||
public List<PrcOrderBill> selectPrcOrderBillByCustomerPeriod(@Param("customerId") Long customerId,
|
||||
@Param("customerCode") String customerCode, @Param("cutoffDate") Date cutoffDate,
|
||||
@Param("currency") String currency, @Param("arBillStatus") String arBillStatus);
|
||||
@Param("customerCode") String customerCode, @Param("orderOrTrackingNo") String orderOrTrackingNo,
|
||||
@Param("excludeOrderOrTrackingNo") String excludeOrderOrTrackingNo,
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency,
|
||||
@Param("arBillStatus") String arBillStatus, @Param("excludedBillIds") List<String> excludedBillIds);
|
||||
|
||||
/** 统计应收账单预览结果金额,供全选模式展示。 */
|
||||
BigDecimal sumPrcOrderBillIncomeByCustomerPeriod(@Param("customerId") Long customerId,
|
||||
@Param("customerCode") String customerCode, @Param("orderOrTrackingNo") String orderOrTrackingNo,
|
||||
@Param("excludeOrderOrTrackingNo") String excludeOrderOrTrackingNo,
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency,
|
||||
@Param("arBillStatus") String arBillStatus);
|
||||
|
||||
/** 异步生成账单按 bill_id 游标读取一批来源订单。 */
|
||||
List<PrcOrderBill> selectPrcOrderBillByCustomerPeriodCursor(@Param("customerId") Long customerId,
|
||||
@Param("customerCode") String customerCode, @Param("orderOrTrackingNo") String orderOrTrackingNo,
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency,
|
||||
@Param("arBillStatus") String arBillStatus, @Param("snapshotCreateTime") Date snapshotCreateTime,
|
||||
@Param("lastSourceBillId") String lastSourceBillId, @Param("billIds") List<String> billIds,
|
||||
@Param("excludedBillIds") List<String> excludedBillIds, @Param("limit") int limit);
|
||||
|
||||
int countPrcOrderBillByCustomerPeriod(@Param("customerId") Long customerId,
|
||||
@Param("customerCode") String customerCode, @Param("orderOrTrackingNo") String orderOrTrackingNo,
|
||||
@Param("cutoffDate") Date cutoffDate, @Param("currency") String currency,
|
||||
@Param("arBillStatus") String arBillStatus, @Param("snapshotCreateTime") Date snapshotCreateTime,
|
||||
@Param("billIds") List<String> billIds, @Param("excludedBillIds") List<String> excludedBillIds);
|
||||
|
||||
/** 按生成账单时用户勾选的订单读取,并再次校验账单筛选条件。 */
|
||||
public List<PrcOrderBill> selectPrcOrderBillByCustomerCutoffAndIds(@Param("customerId") Long customerId,
|
||||
@Param("customerCode") String customerCode, @Param("cutoffDate") Date cutoffDate,
|
||||
@Param("customerCode") String customerCode, @Param("orderOrTrackingNo") String orderOrTrackingNo,
|
||||
@Param("cutoffDate") Date cutoffDate,
|
||||
@Param("currency") String currency, @Param("billIds") List<String> billIds,
|
||||
@Param("arBillStatus") String arBillStatus);
|
||||
|
||||
@@ -37,6 +61,9 @@ public interface PrcOrderBillMapper
|
||||
public int releaseArBillOrders(@Param("billIds") List<String> billIds, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus, @Param("toStatus") String toStatus);
|
||||
|
||||
int releaseArBillOrdersByArBillId(@Param("arBillId") Long arBillId, @Param("operator") String operator,
|
||||
@Param("fromStatus") String fromStatus, @Param("toStatus") String toStatus);
|
||||
|
||||
public int insertPrcOrderBill(PrcOrderBill bill);
|
||||
|
||||
public int updatePrcOrderBill(PrcOrderBill bill);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBankAccountMapper">
|
||||
<resultMap id="ArBankAccountResult" type="ArBankAccount">
|
||||
<id property="bankAccountId" column="bank_account_id"/>
|
||||
@@ -19,12 +19,21 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<select id="selectDefaultByCurrency" resultMap="ArBankAccountResult">
|
||||
select bank_account_id, account_name, account_no, bank_name, currency,
|
||||
is_default, status, remark, create_by, create_time, update_by, update_time
|
||||
select bank_account_id,
|
||||
account_name,
|
||||
account_no,
|
||||
bank_name,
|
||||
currency,
|
||||
is_default,
|
||||
status,
|
||||
remark,
|
||||
create_by,
|
||||
create_time,
|
||||
update_by,
|
||||
update_time
|
||||
from ar_bank_account
|
||||
where currency = #{currency}
|
||||
and status = '0'
|
||||
order by is_default desc, bank_account_id
|
||||
limit 1
|
||||
order by is_default desc, bank_account_id limit 1
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<?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">
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBillDetailFeeMapper">
|
||||
<!-- 账单明细费用项读写;批量查询仅接收当前明细批次的 ID。 -->
|
||||
<resultMap id="ArBillDetailFeeResult" type="ArBillDetailFee">
|
||||
<id property="detailFeeId" column="detail_fee_id"/>
|
||||
<result property="detailId" column="detail_id"/>
|
||||
@@ -24,39 +25,116 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<select id="selectByDetailId" parameterType="long" resultMap="ArBillDetailFeeResult">
|
||||
select detail_fee_id, detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity,
|
||||
unit, unit_price, amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
from ar_bill_detail_fee where detail_id = #{detailId} order by fee_no, detail_fee_id
|
||||
select detail_fee_id,
|
||||
detail_id,
|
||||
prc_income_bill_fee_id,
|
||||
fee_no,
|
||||
fee_type,
|
||||
fee_name,
|
||||
sc_id,
|
||||
quantity,
|
||||
unit,
|
||||
unit_price,
|
||||
amount,
|
||||
currency,
|
||||
calculation_formula,
|
||||
round_mode,
|
||||
remark,
|
||||
create_by,
|
||||
create_time
|
||||
from ar_bill_detail_fee
|
||||
where detail_id = #{detailId}
|
||||
order by fee_no, detail_fee_id
|
||||
</select>
|
||||
|
||||
<select id="selectByBillIdAndDetailId" resultMap="ArBillDetailFeeResult">
|
||||
select f.detail_fee_id,
|
||||
f.detail_id,
|
||||
f.prc_income_bill_fee_id,
|
||||
f.fee_no,
|
||||
f.fee_type,
|
||||
f.fee_name,
|
||||
f.sc_id,
|
||||
f.quantity,
|
||||
f.unit,
|
||||
f.unit_price,
|
||||
f.amount,
|
||||
f.currency,
|
||||
f.calculation_formula,
|
||||
f.round_mode,
|
||||
f.remark,
|
||||
f.create_by,
|
||||
f.create_time
|
||||
from ar_bill_detail_fee f
|
||||
inner join ar_bill_detail d on d.detail_id = f.detail_id
|
||||
where d.ar_bill_id = #{arBillId}
|
||||
and f.detail_id = #{detailId}
|
||||
order by f.fee_no, f.detail_fee_id
|
||||
</select>
|
||||
|
||||
<select id="selectByBillId" parameterType="long" resultMap="ArBillDetailFeeResult">
|
||||
select detail_fee_id, detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity,
|
||||
unit, unit_price, amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
select detail_fee_id,
|
||||
detail_id,
|
||||
prc_income_bill_fee_id,
|
||||
fee_no,
|
||||
fee_type,
|
||||
fee_name,
|
||||
sc_id,
|
||||
quantity,
|
||||
unit,
|
||||
unit_price,
|
||||
amount,
|
||||
currency,
|
||||
calculation_formula,
|
||||
round_mode,
|
||||
remark,
|
||||
create_by,
|
||||
create_time
|
||||
from ar_bill_detail_fee
|
||||
where detail_id in (select detail_id from ar_bill_detail where ar_bill_id = #{arBillId})
|
||||
order by detail_id, fee_no, detail_fee_id
|
||||
</select>
|
||||
|
||||
<select id="selectByDetailIds" resultMap="ArBillDetailFeeResult">
|
||||
select detail_fee_id, detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity,
|
||||
unit, unit_price, amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
from ar_bill_detail_fee
|
||||
where detail_id in
|
||||
<foreach collection="detailIds" item="detailId" open="(" separator="," close=")">
|
||||
#{detailId}
|
||||
</foreach>
|
||||
order by detail_id, fee_no, detail_fee_id
|
||||
</select>
|
||||
|
||||
<insert id="insert" parameterType="ArBillDetailFee" useGeneratedKeys="true" keyProperty="detailFeeId">
|
||||
insert into ar_bill_detail_fee (
|
||||
detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity, unit, unit_price,
|
||||
amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
) values (
|
||||
#{detailId}, #{prcIncomeBillFeeId}, #{feeNo}, #{feeType}, #{feeName}, #{scId}, #{quantity}, #{unit},
|
||||
#{unitPrice}, #{amount}, #{currency}, #{calculationFormula}, #{roundMode}, #{remark},
|
||||
#{createBy}, sysdate()
|
||||
)
|
||||
insert into ar_bill_detail_fee (detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity,
|
||||
unit, unit_price,
|
||||
amount, currency, calculation_formula, round_mode, remark, create_by,
|
||||
create_time)
|
||||
values (#{detailId}, #{prcIncomeBillFeeId}, #{feeNo}, #{feeType}, #{feeName}, #{scId}, #{quantity}, #{unit},
|
||||
#{unitPrice}, #{amount}, #{currency}, #{calculationFormula}, #{roundMode}, #{remark},
|
||||
#{createBy}, sysdate())
|
||||
</insert>
|
||||
|
||||
<insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="detailFeeId">
|
||||
insert into ar_bill_detail_fee (
|
||||
detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity, unit, unit_price,
|
||||
amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
detail_id, prc_income_bill_fee_id, fee_no, fee_type, fee_name, sc_id, quantity, unit, unit_price,
|
||||
amount, currency, calculation_formula, round_mode, remark, create_by, create_time
|
||||
) values
|
||||
<foreach collection="list" item="item" separator=",">
|
||||
(#{item.detailId}, #{item.prcIncomeBillFeeId}, #{item.feeNo}, #{item.feeType}, #{item.feeName}, #{item.scId},
|
||||
#{item.quantity}, #{item.unit}, #{item.unitPrice}, #{item.amount}, #{item.currency},
|
||||
#{item.calculationFormula}, #{item.roundMode}, #{item.remark}, #{item.createBy}, sysdate())
|
||||
(#{item.detailId}, #{item.prcIncomeBillFeeId}, #{item.feeNo}, #{item.feeType}, #{item.feeName},
|
||||
#{item.scId},
|
||||
#{item.quantity}, #{item.unit}, #{item.unitPrice}, #{item.amount}, #{item.currency},
|
||||
#{item.calculationFormula}, #{item.roundMode}, #{item.remark}, #{item.createBy}, sysdate())
|
||||
</foreach>
|
||||
</insert>
|
||||
|
||||
<delete id="deleteByBillId" parameterType="long">
|
||||
delete
|
||||
f
|
||||
from ar_bill_detail_fee f
|
||||
inner join ar_bill_detail d on d.detail_id = f.detail_id
|
||||
where d.ar_bill_id =
|
||||
#{arBillId}
|
||||
</delete>
|
||||
</mapper>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBillDetailMapper">
|
||||
<!-- 账单明细读写;详情页分页查询,导出任务按游标批量查询。 -->
|
||||
<resultMap id="ArBillDetailResult" type="ArBillDetail">
|
||||
<id property="detailId" column="detail_id"/>
|
||||
<result property="arBillId" column="ar_bill_id"/>
|
||||
@@ -38,6 +39,20 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
from ar_bill_detail where ar_bill_id = #{arBillId} order by detail_no
|
||||
</select>
|
||||
|
||||
<select id="selectByBillIdAndSourceIds" resultMap="ArBillDetailResult">
|
||||
select detail_id, ar_bill_id, prc_order_bill_id, detail_no, order_no, tracking_no, receive_time,
|
||||
product_code, product_name, goods_description, country_code, country_name, dest_postcode,
|
||||
actual_weight, volume_weight, charge_weight, pkg_length, pkg_width, pkg_height,
|
||||
currency, total_amount, remark, create_by, create_time
|
||||
from ar_bill_detail
|
||||
where ar_bill_id = #{arBillId}
|
||||
and prc_order_bill_id in
|
||||
<foreach collection="sourceBillIds" item="sourceBillId" open="(" separator="," close=")">
|
||||
#{sourceBillId}
|
||||
</foreach>
|
||||
order by detail_no
|
||||
</select>
|
||||
|
||||
<resultMap id="ArBillDetailWithFeesResult" type="ArBillDetail" extends="ArBillDetailResult">
|
||||
<collection property="fees" ofType="ArBillDetailFee">
|
||||
<id property="detailFeeId" column="fee_detail_id"/>
|
||||
@@ -78,18 +93,29 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
order by d.detail_no, d.detail_id, f.fee_no, f.detail_fee_id
|
||||
</select>
|
||||
|
||||
<select id="selectExportPage" resultMap="ArBillDetailResult">
|
||||
select detail_id, ar_bill_id, prc_order_bill_id, detail_no, order_no, tracking_no, receive_time,
|
||||
product_code, product_name, goods_description, country_code, country_name, dest_postcode,
|
||||
actual_weight, volume_weight, charge_weight, pkg_length, pkg_width, pkg_height,
|
||||
currency, total_amount, remark, create_by, create_time
|
||||
from ar_bill_detail
|
||||
where ar_bill_id = #{arBillId} and detail_no > #{lastDetailNo}
|
||||
order by detail_no
|
||||
limit #{pageSize}
|
||||
</select>
|
||||
|
||||
<insert id="insert" parameterType="ArBillDetail" useGeneratedKeys="true" keyProperty="detailId">
|
||||
insert into ar_bill_detail (
|
||||
ar_bill_id, prc_order_bill_id, detail_no, order_no, tracking_no, receive_time, product_code,
|
||||
product_name, goods_description, country_code, country_name, dest_postcode, actual_weight,
|
||||
volume_weight, charge_weight, pkg_length, pkg_width, pkg_height, currency, total_amount,
|
||||
remark, create_by, create_time
|
||||
) values (
|
||||
#{arBillId}, #{prcOrderBillId}, #{detailNo}, #{orderNo}, #{trackingNo}, #{receiveTime},
|
||||
#{productCode}, #{productName}, #{goodsDescription}, #{countryCode}, #{countryName},
|
||||
#{destPostcode}, #{actualWeight}, #{volumeWeight}, #{chargeWeight}, #{pkgLength}, #{pkgWidth},
|
||||
#{pkgHeight}, #{currency}, #{totalAmount}, #{remark}, #{createBy}, sysdate()
|
||||
)
|
||||
insert into ar_bill_detail (ar_bill_id, prc_order_bill_id, detail_no, order_no, tracking_no, receive_time,
|
||||
product_code,
|
||||
product_name, goods_description, country_code, country_name, dest_postcode,
|
||||
actual_weight,
|
||||
volume_weight, charge_weight, pkg_length, pkg_width, pkg_height, currency,
|
||||
total_amount,
|
||||
remark, create_by, create_time)
|
||||
values (#{arBillId}, #{prcOrderBillId}, #{detailNo}, #{orderNo}, #{trackingNo}, #{receiveTime},
|
||||
#{productCode}, #{productName}, #{goodsDescription}, #{countryCode}, #{countryName},
|
||||
#{destPostcode}, #{actualWeight}, #{volumeWeight}, #{chargeWeight}, #{pkgLength}, #{pkgWidth},
|
||||
#{pkgHeight}, #{currency}, #{totalAmount}, #{remark}, #{createBy}, sysdate())
|
||||
</insert>
|
||||
|
||||
<insert id="insertBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="detailId">
|
||||
@@ -107,4 +133,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
#{item.currency}, #{item.totalAmount}, #{item.remark}, #{item.createBy}, sysdate())
|
||||
</foreach>
|
||||
</insert>
|
||||
|
||||
<delete id="deleteByBillId" parameterType="long">
|
||||
delete from ar_bill_detail where ar_bill_id = #{arBillId}
|
||||
</delete>
|
||||
</mapper>
|
||||
|
||||
@@ -3,13 +3,18 @@
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBillExportMapper">
|
||||
<!-- 导出任务和历史记录;PROCESSING/SUCCESS/FAILED 由异步执行器更新。 -->
|
||||
<resultMap id="ArBillExportResult" type="ArBillExport">
|
||||
<id property="exportId" column="export_id"/>
|
||||
<result property="arBillId" column="ar_bill_id"/>
|
||||
<result property="fileName" column="file_name"/>
|
||||
<result property="fileType" column="file_type"/>
|
||||
<result property="templateId" column="template_id"/>
|
||||
<result property="templateCode" column="template_code"/>
|
||||
<result property="templateVersion" column="template_version"/>
|
||||
<result property="templateStorageType" column="template_storage_type"/>
|
||||
<result property="templateStorageKey" column="template_storage_key"/>
|
||||
<result property="templateHash" column="template_hash"/>
|
||||
<result property="storageKey" column="storage_key"/>
|
||||
<result property="fileSize" column="file_size"/>
|
||||
<result property="fileHash" column="file_hash"/>
|
||||
@@ -21,8 +26,24 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectExportColumns">
|
||||
select export_id, ar_bill_id, file_name, file_type, template_code, template_version,
|
||||
storage_key, file_size, file_hash, row_count, export_status, export_by, export_time, remark
|
||||
select export_id,
|
||||
ar_bill_id,
|
||||
file_name,
|
||||
file_type,
|
||||
template_id,
|
||||
template_code,
|
||||
template_version,
|
||||
template_storage_type,
|
||||
template_storage_key,
|
||||
template_hash,
|
||||
storage_key,
|
||||
file_size,
|
||||
file_hash,
|
||||
row_count,
|
||||
export_status,
|
||||
export_by,
|
||||
export_time,
|
||||
remark
|
||||
from ar_bill_export
|
||||
</sql>
|
||||
|
||||
@@ -40,13 +61,43 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
order by export_time desc limit 1
|
||||
</select>
|
||||
|
||||
<select id="selectProcessingByBillId" parameterType="long" resultMap="ArBillExportResult">
|
||||
<include refid="selectExportColumns"/>
|
||||
where ar_bill_id = #{arBillId} and export_status = 'PROCESSING'
|
||||
order by export_id desc limit 1
|
||||
</select>
|
||||
|
||||
<insert id="insert" parameterType="ArBillExport" useGeneratedKeys="true" keyProperty="exportId">
|
||||
insert into ar_bill_export (
|
||||
ar_bill_id, file_name, file_type, template_code, template_version, storage_key,
|
||||
ar_bill_id, file_name, file_type, template_id, template_code, template_version,
|
||||
template_storage_type, template_storage_key, template_hash, storage_key,
|
||||
file_size, file_hash, row_count, export_status, export_by, export_time, remark
|
||||
) values (
|
||||
#{arBillId}, #{fileName}, #{fileType}, #{templateCode}, #{templateVersion}, #{storageKey},
|
||||
#{arBillId}, #{fileName}, #{fileType}, #{templateId}, #{templateCode}, #{templateVersion},
|
||||
#{templateStorageType}, #{templateStorageKey}, #{templateHash}, #{storageKey},
|
||||
#{fileSize}, #{fileHash}, #{rowCount}, #{exportStatus}, #{exportBy}, sysdate(), #{remark}
|
||||
)
|
||||
</insert>
|
||||
|
||||
<update id="markSuccess" parameterType="ArBillExport">
|
||||
update ar_bill_export
|
||||
set storage_key = #{storageKey},
|
||||
file_size = #{fileSize},
|
||||
file_hash = #{fileHash},
|
||||
export_status = 'SUCCESS',
|
||||
remark = null
|
||||
where export_id = #{exportId} and export_status = 'PROCESSING'
|
||||
</update>
|
||||
|
||||
<update id="markFailed">
|
||||
update ar_bill_export
|
||||
set export_status = 'FAILED', remark = #{remark}
|
||||
where export_id = #{exportId} and export_status = 'PROCESSING'
|
||||
</update>
|
||||
|
||||
<update id="markExpiredProcessingAsFailed">
|
||||
update ar_bill_export
|
||||
set export_status = 'FAILED', remark = #{remark}
|
||||
where export_status = 'PROCESSING' and export_time < #{expiredBefore}
|
||||
</update>
|
||||
</mapper>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
<?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.ruoyi.ar.mapper.ArBillGenerateTaskMapper">
|
||||
<!-- 生成任务表是异步任务的持久化队列;状态更新均带前置状态条件,保证多节点抢占幂等。 -->
|
||||
<resultMap id="ArBillGenerateTaskResult" type="ArBillGenerateTask">
|
||||
<id property="taskId" column="task_id"/>
|
||||
<result property="taskNo" column="task_no"/>
|
||||
<result property="arBillId" column="ar_bill_id"/>
|
||||
<result property="selectionMode" column="selection_mode"/>
|
||||
<result property="requestPayload" column="request_payload"/>
|
||||
<result property="snapshotCreateTime" column="snapshot_create_time"/>
|
||||
<result property="lastSourceBillId" column="last_source_bill_id"/>
|
||||
<result property="totalCount" column="total_count"/>
|
||||
<result property="processedCount" column="processed_count"/>
|
||||
<result property="successCount" column="success_count"/>
|
||||
<result property="totalAmount" column="total_amount"/>
|
||||
<result property="status" column="status"/>
|
||||
<result property="errorMessage" column="error_message"/>
|
||||
<result property="requestToken" column="request_token"/>
|
||||
<result property="createBy" column="create_by"/>
|
||||
<result property="createTime" column="create_time"/>
|
||||
<result property="startedAt" column="started_at"/>
|
||||
<result property="heartbeatTime" column="heartbeat_time"/>
|
||||
<result property="finishedAt" column="finished_at"/>
|
||||
</resultMap>
|
||||
|
||||
<sql id="columns">
|
||||
select task_id,
|
||||
task_no,
|
||||
ar_bill_id,
|
||||
selection_mode,
|
||||
request_payload,
|
||||
snapshot_create_time,
|
||||
last_source_bill_id,
|
||||
total_count,
|
||||
processed_count,
|
||||
success_count,
|
||||
total_amount,
|
||||
status,
|
||||
error_message,
|
||||
request_token,
|
||||
create_by,
|
||||
create_time,
|
||||
started_at,
|
||||
heartbeat_time,
|
||||
finished_at
|
||||
from ar_bill_generate_task
|
||||
</sql>
|
||||
|
||||
<select id="selectById" parameterType="long" resultMap="ArBillGenerateTaskResult">
|
||||
<include refid="columns"/>
|
||||
where task_id = #{taskId}
|
||||
</select>
|
||||
|
||||
<select id="selectByRequestToken" parameterType="string" resultMap="ArBillGenerateTaskResult">
|
||||
<include refid="columns"/>
|
||||
where request_token = #{requestToken}
|
||||
</select>
|
||||
|
||||
<!-- 前端恢复页面时查询当前用户仍需展示的任务。 -->
|
||||
<select id="selectActiveByCreateBy" resultMap="ArBillGenerateTaskResult">
|
||||
<include refid="columns"/>
|
||||
where create_by = #{createBy}
|
||||
and status in ('WAITING', 'RUNNING', 'CANCEL_REQUESTED')
|
||||
order by create_time desc, task_id desc
|
||||
</select>
|
||||
|
||||
<!-- 定时调度器按创建时间顺序取待处理任务。 -->
|
||||
<select id="selectWaiting" resultMap="ArBillGenerateTaskResult">
|
||||
<include refid="columns"/>
|
||||
where status = 'WAITING'
|
||||
order by create_time asc, task_id asc
|
||||
limit #{limit}
|
||||
</select>
|
||||
|
||||
<insert id="insert" parameterType="ArBillGenerateTask" useGeneratedKeys="true" keyProperty="taskId">
|
||||
insert into ar_bill_generate_task (task_no, ar_bill_id, selection_mode, request_payload, snapshot_create_time,
|
||||
last_source_bill_id, total_count, processed_count, success_count,
|
||||
total_amount,
|
||||
status, error_message, request_token, create_by, create_time, started_at,
|
||||
heartbeat_time, finished_at)
|
||||
values (#{taskNo}, #{arBillId}, #{selectionMode}, #{requestPayload}, #{snapshotCreateTime},
|
||||
#{lastSourceBillId}, #{totalCount}, #{processedCount}, #{successCount}, #{totalAmount},
|
||||
#{status}, #{errorMessage}, #{requestToken}, #{createBy}, sysdate(), #{startedAt},
|
||||
#{heartbeatTime}, #{finishedAt})
|
||||
</insert>
|
||||
|
||||
<!-- 条件更新抢占任务;返回 1 才表示当前节点真正拿到执行权。 -->
|
||||
<update id="markRunning">
|
||||
update ar_bill_generate_task
|
||||
set status = 'RUNNING',
|
||||
started_at = coalesce(started_at, #{startedAt}),
|
||||
heartbeat_time = #{startedAt}
|
||||
where task_id = #{taskId}
|
||||
and status = 'WAITING'
|
||||
</update>
|
||||
|
||||
<update id="updateTotalCount">
|
||||
update ar_bill_generate_task
|
||||
set total_count = #{totalCount},
|
||||
heartbeat_time = sysdate()
|
||||
where task_id = #{taskId}
|
||||
and status = 'RUNNING'
|
||||
</update>
|
||||
|
||||
<!-- 每批成功后写入游标、计数和心跳;游标用于故障恢复后继续扫描。 -->
|
||||
<update id="updateProgress">
|
||||
update ar_bill_generate_task
|
||||
set last_source_bill_id = #{lastSourceBillId},
|
||||
processed_count = #{processedCount},
|
||||
success_count = #{successCount},
|
||||
total_amount = #{totalAmount},
|
||||
heartbeat_time = #{heartbeatTime}
|
||||
where task_id = #{taskId}
|
||||
and status = 'RUNNING'
|
||||
</update>
|
||||
|
||||
<update id="markSuccess">
|
||||
update ar_bill_generate_task
|
||||
set status = 'SUCCESS',
|
||||
finished_at = #{finishedAt},
|
||||
heartbeat_time = #{finishedAt}
|
||||
where task_id = #{taskId}
|
||||
and status = 'RUNNING'
|
||||
</update>
|
||||
|
||||
<update id="markFailed">
|
||||
update ar_bill_generate_task
|
||||
set status = 'FAILED',
|
||||
error_message = #{errorMessage},
|
||||
finished_at = #{finishedAt},
|
||||
heartbeat_time = #{finishedAt}
|
||||
where task_id = #{taskId}
|
||||
and status in ('WAITING', 'RUNNING', 'CANCEL_REQUESTED')
|
||||
</update>
|
||||
|
||||
<update id="markCancelRequested">
|
||||
update ar_bill_generate_task
|
||||
set status = 'CANCEL_REQUESTED',
|
||||
heartbeat_time = sysdate()
|
||||
where task_id = #{taskId}
|
||||
and status in ('WAITING', 'RUNNING')
|
||||
</update>
|
||||
|
||||
<update id="markCanceled">
|
||||
update ar_bill_generate_task
|
||||
set status = 'CANCELED',
|
||||
error_message = '用户取消账单生成',
|
||||
finished_at = #{finishedAt},
|
||||
heartbeat_time = #{finishedAt}
|
||||
where task_id = #{taskId}
|
||||
and status in ('WAITING', 'RUNNING', 'CANCEL_REQUESTED')
|
||||
</update>
|
||||
|
||||
<!-- 执行节点宕机时恢复无心跳的 RUNNING 任务,供调度器重新投递。 -->
|
||||
<update id="resetExpiredRunning">
|
||||
update ar_bill_generate_task
|
||||
set status = 'WAITING',
|
||||
error_message = '任务执行节点已重启,已自动恢复等待处理',
|
||||
heartbeat_time = null
|
||||
where status = 'RUNNING'
|
||||
and heartbeat_time < #{expiredBefore}
|
||||
</update>
|
||||
|
||||
<!-- 取消请求长时间未完成时由补偿任务取出并执行数据清理。 -->
|
||||
<select id="selectCancelRequestedBefore" resultMap="ArBillGenerateTaskResult">
|
||||
<include refid="columns"/>
|
||||
where status = 'CANCEL_REQUESTED'
|
||||
and coalesce(heartbeat_time, create_time) < #{expiredBefore}
|
||||
order by create_time asc, task_id asc
|
||||
limit #{limit}
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -1,7 +1,7 @@
|
||||
<?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">
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBillLogMapper">
|
||||
<resultMap id="ArBillLogResult" type="ArBillLog">
|
||||
<id property="logId" column="log_id"/>
|
||||
@@ -28,24 +28,27 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
|
||||
<select id="selectList" parameterType="ArBillLog" resultMap="ArBillLogResult">
|
||||
select l.log_id, l.ar_bill_id, l.object_type, l.object_id, l.operation_type, l.operation_desc,
|
||||
case l.object_type
|
||||
when 'BILL' then b.bill_no
|
||||
when 'EXPORT' then coalesce(e.file_name, b.bill_no)
|
||||
when 'BALANCE_WRITEOFF' then bw.writeoff_no
|
||||
else null
|
||||
end as object_display,
|
||||
l.from_status, l.to_status, l.before_data, l.after_data, l.operator_id, l.operator_name,
|
||||
l.operation_source, l.request_id, l.trace_id, l.result, l.error_message, l.client_ip, l.create_time
|
||||
case l.object_type
|
||||
when 'BILL' then b.bill_no
|
||||
when 'EXPORT' then coalesce(e.file_name, b.bill_no)
|
||||
when 'BALANCE_WRITEOFF' then bw.writeoff_no
|
||||
else null
|
||||
end as object_display,
|
||||
l.from_status, l.to_status, l.before_data, l.after_data, l.operator_id, l.operator_name,
|
||||
l.operation_source, l.request_id, l.trace_id, l.result, l.error_message, l.client_ip, l.create_time
|
||||
from ar_bill_log l
|
||||
left join ar_bill b on b.ar_bill_id = l.ar_bill_id
|
||||
left join ar_bill_export e on e.export_id = case when l.object_type = 'EXPORT' then cast(l.object_id as unsigned) end
|
||||
left join ar_balance_writeoff bw on bw.writeoff_id = case when l.object_type = 'BALANCE_WRITEOFF' then cast(l.object_id as unsigned) end
|
||||
left join ar_bill_export e on e.export_id = case when l.object_type = 'EXPORT' then cast(l.object_id as
|
||||
unsigned) end
|
||||
left join ar_balance_writeoff bw on bw.writeoff_id = case when l.object_type = 'BALANCE_WRITEOFF' then
|
||||
cast(l.object_id as unsigned) end
|
||||
<where>
|
||||
<if test="arBillId != null">and l.ar_bill_id = #{arBillId}</if>
|
||||
<if test="objectType != null and objectType != ''">and l.object_type = #{objectType}</if>
|
||||
<if test="objectId != null and objectId != ''">and l.object_id = #{objectId}</if>
|
||||
<if test="operationType != null and operationType != ''">and l.operation_type = #{operationType}</if>
|
||||
<if test="operationSource != null and operationSource != ''">and l.operation_source = #{operationSource}</if>
|
||||
<if test="operationSource != null and operationSource != ''">and l.operation_source = #{operationSource}
|
||||
</if>
|
||||
<if test="requestId != null and requestId != ''">and l.request_id = #{requestId}</if>
|
||||
<if test="result != null and result != ''">and l.result = #{result}</if>
|
||||
</where>
|
||||
@@ -53,23 +56,39 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</select>
|
||||
|
||||
<select id="selectSuccessByRequestId" resultMap="ArBillLogResult">
|
||||
select log_id, ar_bill_id, object_type, object_id, operation_type, operation_desc,
|
||||
from_status, to_status, before_data, after_data, operator_id, operator_name,
|
||||
operation_source, request_id, trace_id, result, error_message, client_ip, create_time
|
||||
select log_id,
|
||||
ar_bill_id,
|
||||
object_type,
|
||||
object_id,
|
||||
operation_type,
|
||||
operation_desc,
|
||||
from_status,
|
||||
to_status,
|
||||
before_data,
|
||||
after_data,
|
||||
operator_id,
|
||||
operator_name,
|
||||
operation_source,
|
||||
request_id,
|
||||
trace_id,
|
||||
result,
|
||||
error_message,
|
||||
client_ip,
|
||||
create_time
|
||||
from ar_bill_log
|
||||
where request_id = #{requestId} and object_type = #{objectType} and result = #{result}
|
||||
where request_id = #{requestId}
|
||||
and object_type = #{objectType}
|
||||
and result = #{result}
|
||||
order by log_id limit 1
|
||||
</select>
|
||||
|
||||
<insert id="insert" parameterType="ArBillLog" useGeneratedKeys="true" keyProperty="logId">
|
||||
insert into ar_bill_log (
|
||||
ar_bill_id, object_type, object_id, operation_type, operation_desc, from_status, to_status,
|
||||
before_data, after_data, operator_id, operator_name, operation_source, request_id,
|
||||
trace_id, result, error_message, client_ip, create_time
|
||||
) values (
|
||||
#{arBillId}, #{objectType}, #{objectId}, #{operationType}, #{operationDesc}, #{fromStatus}, #{toStatus},
|
||||
#{beforeData}, #{afterData}, #{operatorId}, #{operatorName}, #{operationSource}, #{requestId},
|
||||
#{traceId}, #{result}, #{errorMessage}, #{clientIp}, sysdate()
|
||||
)
|
||||
insert into ar_bill_log (ar_bill_id, object_type, object_id, operation_type, operation_desc, from_status,
|
||||
to_status,
|
||||
before_data, after_data, operator_id, operator_name, operation_source, request_id,
|
||||
trace_id, result, error_message, client_ip, create_time)
|
||||
values (#{arBillId}, #{objectType}, #{objectId}, #{operationType}, #{operationDesc}, #{fromStatus}, #{toStatus},
|
||||
#{beforeData}, #{afterData}, #{operatorId}, #{operatorName}, #{operationSource}, #{requestId},
|
||||
#{traceId}, #{result}, #{errorMessage}, #{clientIp}, sysdate())
|
||||
</insert>
|
||||
</mapper>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<?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">
|
||||
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.ar.mapper.ArBillMapper">
|
||||
<!-- 账单头查询、状态流转和金额/生成进度更新。带 ForUpdate 的查询用于核销并发控制。 -->
|
||||
<resultMap id="ArBillResult" type="ArBill">
|
||||
<id property="arBillId" column="ar_bill_id"/>
|
||||
<result property="billNo" column="bill_no"/>
|
||||
@@ -19,6 +20,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<result property="writtenOffAmount" column="written_off_amount"/>
|
||||
<result property="unwrittenAmount" column="unwritten_amount"/>
|
||||
<result property="status" column="status"/>
|
||||
<result property="generationStatus" column="generation_status"/>
|
||||
<result property="billVersion" column="bill_version"/>
|
||||
<result property="bankAccountName" column="bank_account_name"/>
|
||||
<result property="bankAccountNo" column="bank_account_no"/>
|
||||
@@ -33,21 +35,48 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</resultMap>
|
||||
|
||||
<sql id="selectArBillColumns">
|
||||
select ar_bill_id, bill_no, bill_name, customer_id, customer_code, customer_name,
|
||||
bill_period_start, bill_period_end, bill_date, currency, order_count,
|
||||
total_amount, written_off_amount, unwritten_amount, status, bill_version,
|
||||
bank_account_name, bank_account_no, bank_name, remark, confirmed_by,
|
||||
confirmed_time, create_by, create_time, update_by, update_time
|
||||
select ar_bill_id,
|
||||
bill_no,
|
||||
bill_name,
|
||||
customer_id,
|
||||
customer_code,
|
||||
customer_name,
|
||||
bill_period_start,
|
||||
bill_period_end,
|
||||
bill_date,
|
||||
currency,
|
||||
order_count,
|
||||
total_amount,
|
||||
written_off_amount,
|
||||
unwritten_amount,
|
||||
status,
|
||||
generation_status,
|
||||
bill_version,
|
||||
bank_account_name,
|
||||
bank_account_no,
|
||||
bank_name,
|
||||
remark,
|
||||
confirmed_by,
|
||||
confirmed_time,
|
||||
create_by,
|
||||
create_time,
|
||||
update_by,
|
||||
update_time
|
||||
from ar_bill
|
||||
</sql>
|
||||
|
||||
<select id="selectArBillList" parameterType="com.ruoyi.ar.domain.vo.ArBillQuery" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/>
|
||||
<where>
|
||||
and (generation_status is null or generation_status = 'READY')
|
||||
<if test="billNo != null and billNo != ''">and bill_no like concat('%', #{billNo}, '%')</if>
|
||||
<if test="billName != null and billName != ''">and bill_name like concat('%', #{billName}, '%')</if>
|
||||
<if test="customerCode != null and customerCode != ''">and customer_code like concat('%', #{customerCode}, '%')</if>
|
||||
<if test="customerName != null and customerName != ''">and customer_name like concat('%', #{customerName}, '%')</if>
|
||||
<if test="customerCode != null and customerCode != ''">and customer_code like concat('%', #{customerCode},
|
||||
'%')
|
||||
</if>
|
||||
<if test="customerName != null and customerName != ''">and customer_name like concat('%', #{customerName},
|
||||
'%')
|
||||
</if>
|
||||
<if test="customerId != null">and customer_id = #{customerId}</if>
|
||||
<if test="status != null and status != ''">and status = #{status}</if>
|
||||
<if test="currency != null and currency != ''">and currency = #{currency}</if>
|
||||
@@ -59,11 +88,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
</select>
|
||||
|
||||
<select id="selectArBillById" parameterType="long" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/> where ar_bill_id = #{arBillId}
|
||||
<include refid="selectArBillColumns"/>
|
||||
where ar_bill_id = #{arBillId}
|
||||
</select>
|
||||
|
||||
<select id="selectArBillByBillNo" parameterType="string" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/> where bill_no = #{billNo}
|
||||
<include refid="selectArBillColumns"/>
|
||||
where bill_no = #{billNo}
|
||||
</select>
|
||||
|
||||
<select id="selectGeneratingByCustomerPeriod" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/>
|
||||
where customer_id = #{customerId}
|
||||
and currency = #{currency}
|
||||
and bill_period_end = #{cutoffDate}
|
||||
and generation_status = 'GENERATING'
|
||||
order by ar_bill_id desc
|
||||
limit 1
|
||||
</select>
|
||||
|
||||
<select id="selectMaxBillVersion" resultType="int">
|
||||
@@ -72,41 +113,47 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
where customer_id = #{customerId}
|
||||
and bill_period_end = #{cutoffDate}
|
||||
and currency = #{currency}
|
||||
order by bill_version desc
|
||||
limit 1
|
||||
for update
|
||||
order by bill_version desc limit 1
|
||||
for
|
||||
update
|
||||
</select>
|
||||
|
||||
<select id="selectArBillByIdForUpdate" parameterType="long" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/> where ar_bill_id = #{arBillId} for update
|
||||
<include refid="selectArBillColumns"/>
|
||||
where ar_bill_id = #{arBillId} for update
|
||||
</select>
|
||||
|
||||
<select id="selectUnsettledByCustomer" resultMap="ArBillResult">
|
||||
<include refid="selectArBillColumns"/>
|
||||
where customer_id = #{customerId}
|
||||
and status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF')
|
||||
and unwritten_amount > 0
|
||||
and status in ('CONFIRMED', 'PARTIAL_WRITTEN_OFF')
|
||||
and (generation_status is null or generation_status = 'READY')
|
||||
and unwritten_amount > 0
|
||||
order by bill_date asc, ar_bill_id asc
|
||||
</select>
|
||||
|
||||
<insert id="insertArBill" parameterType="ArBill" useGeneratedKeys="true" keyProperty="arBillId">
|
||||
insert into ar_bill (
|
||||
bill_no, bill_name, customer_id, customer_code, customer_name, bill_period_start, bill_period_end,
|
||||
bill_date, currency, order_count, total_amount, written_off_amount, unwritten_amount,
|
||||
status, bill_version, bank_account_name, bank_account_no, bank_name, remark,
|
||||
confirmed_by, confirmed_time, create_by, create_time, update_by, update_time
|
||||
) values (
|
||||
#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName}, #{billPeriodStart}, #{billPeriodEnd},
|
||||
#{billDate}, #{currency}, #{orderCount}, #{totalAmount}, #{writtenOffAmount}, #{unwrittenAmount},
|
||||
#{status}, #{billVersion}, #{bankAccountName}, #{bankAccountNo}, #{bankName}, #{remark},
|
||||
#{confirmedBy}, #{confirmedTime}, #{createBy}, sysdate(), #{updateBy}, sysdate()
|
||||
)
|
||||
insert into ar_bill (bill_no, bill_name, customer_id, customer_code, customer_name, bill_period_start,
|
||||
bill_period_end,
|
||||
bill_date, currency, order_count, total_amount, written_off_amount, unwritten_amount,
|
||||
status, generation_status, bill_version, bank_account_name, bank_account_no, bank_name,
|
||||
remark,
|
||||
confirmed_by, confirmed_time, create_by, create_time, update_by, update_time)
|
||||
values (#{billNo}, #{billName}, #{customerId}, #{customerCode}, #{customerName}, #{billPeriodStart},
|
||||
#{billPeriodEnd},
|
||||
#{billDate}, #{currency}, #{orderCount}, #{totalAmount}, #{writtenOffAmount}, #{unwrittenAmount},
|
||||
#{status}, #{generationStatus}, #{billVersion}, #{bankAccountName}, #{bankAccountNo}, #{bankName},
|
||||
#{remark},
|
||||
#{confirmedBy}, #{confirmedTime}, #{createBy}, sysdate(), #{updateBy}, sysdate())
|
||||
</insert>
|
||||
|
||||
<update id="updateArBillStatus">
|
||||
update ar_bill
|
||||
set status = #{status}, remark = #{remark}, update_by = #{operator}, update_time = sysdate(),
|
||||
confirmed_by = case when #{status} = 'CONFIRMED' then #{operator} else confirmed_by end,
|
||||
set status = #{status},
|
||||
remark = #{remark},
|
||||
update_by = #{operator},
|
||||
update_time = sysdate(),
|
||||
confirmed_by = case when #{status} = 'CONFIRMED' then #{operator} else confirmed_by end,
|
||||
confirmed_time = case when #{status} = 'CONFIRMED' then sysdate() else confirmed_time end
|
||||
where ar_bill_id = #{arBillId}
|
||||
and status = #{fromStatus}
|
||||
@@ -114,9 +161,34 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
|
||||
<update id="updateArBillAmounts">
|
||||
update ar_bill
|
||||
set written_off_amount = #{writtenOffAmount}, unwritten_amount = #{unwrittenAmount},
|
||||
status = #{status}, update_by = #{operator}, update_time = sysdate()
|
||||
set written_off_amount = #{writtenOffAmount},
|
||||
unwritten_amount = #{unwrittenAmount},
|
||||
status = #{status},
|
||||
update_by = #{operator},
|
||||
update_time = sysdate()
|
||||
where ar_bill_id = #{arBillId}
|
||||
and status = #{fromStatus}
|
||||
</update>
|
||||
|
||||
<update id="updateArBillProgress">
|
||||
update ar_bill
|
||||
set order_count = #{orderCount},
|
||||
total_amount = #{totalAmount},
|
||||
unwritten_amount = #{unwrittenAmount},
|
||||
bill_period_start = case
|
||||
when #{billPeriodStart} < bill_period_start then #{billPeriodStart}
|
||||
else bill_period_start end,
|
||||
update_by = #{operator},
|
||||
update_time = sysdate()
|
||||
where ar_bill_id = #{arBillId}
|
||||
</update>
|
||||
|
||||
<update id="updateArBillGenerationStatus">
|
||||
update ar_bill
|
||||
set generation_status = #{generationStatus},
|
||||
update_by = #{operator},
|
||||
update_time = sysdate(),
|
||||
remark = case when #{remark} is null or #{remark} = '' then remark else #{remark} end
|
||||
where ar_bill_id = #{arBillId}
|
||||
</update>
|
||||
</mapper>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?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.ruoyi.ar.mapper.ArExportTemplateMapper">
|
||||
<!-- 模板管理查询;导出提交时会把选中的模板版本快照到导出任务。 -->
|
||||
<resultMap id="ArExportTemplateResult" type="ArExportTemplate">
|
||||
<id property="templateId" column="template_id"/>
|
||||
<result property="templateCode" column="template_code"/>
|
||||
<result property="templateName" column="template_name"/>
|
||||
<result property="businessType" column="business_type"/>
|
||||
<result property="templateVersion" column="template_version"/>
|
||||
<result property="storageType" column="storage_type"/>
|
||||
<result property="storageKey" column="storage_key"/>
|
||||
<result property="fileHash" column="file_hash"/>
|
||||
<result property="status" column="status"/>
|
||||
<result property="isDefault" column="is_default"/>
|
||||
<result property="effectiveStart" column="effective_start"/>
|
||||
<result property="effectiveEnd" column="effective_end"/>
|
||||
<result property="remark" column="remark"/>
|
||||
</resultMap>
|
||||
|
||||
<select id="selectDefaultEnabled" resultMap="ArExportTemplateResult">
|
||||
select template_id,
|
||||
template_code,
|
||||
template_name,
|
||||
business_type,
|
||||
template_version,
|
||||
storage_type,
|
||||
storage_key,
|
||||
file_hash,
|
||||
status,
|
||||
is_default,
|
||||
effective_start,
|
||||
effective_end,
|
||||
remark
|
||||
from ar_export_template
|
||||
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})
|
||||
order by effective_start desc, template_id desc limit 1
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -4,6 +4,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.ruoyi.price.mapper.PrcOrderBillMapper">
|
||||
|
||||
<!-- 应收账单生成依赖的来源计费订单查询;本项目的 prc_bill 需求表映射为 prc_order_bill。 -->
|
||||
|
||||
<resultMap type="PrcOrderBill" id="PrcOrderBillResult">
|
||||
<id property="billId" column="bill_id" />
|
||||
<result property="billKey" column="bill_key" />
|
||||
@@ -155,21 +157,107 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
order by create_time desc, bill_id desc
|
||||
</select>
|
||||
|
||||
<!-- The repository's rename_bill_tables.sql maps the requirement's prc_bill to prc_order_bill. -->
|
||||
<!-- rename_bill_tables.sql 已将需求文档中的 prc_bill 映射为本项目的 prc_order_bill。 -->
|
||||
<!-- 生成弹窗预览:按客户、截止日、币种和订单/运单号 OR 条件分页查询未入账订单。 -->
|
||||
<select id="selectPrcOrderBillByCustomerPeriod" resultMap="PrcOrderBillResult">
|
||||
<include refid="selectPrcOrderBillVo"/>
|
||||
where customer_id = #{customerId}
|
||||
<if test="customerCode != null and customerCode != ''">
|
||||
and customer_code like concat('%', #{customerCode}, '%')
|
||||
</if>
|
||||
<if test="orderOrTrackingNo != null and orderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{orderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{orderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
<if test="excludeOrderOrTrackingNo != null and excludeOrderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{excludeOrderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{excludeOrderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
and biz_date <= #{cutoffDate}
|
||||
and ar_bill_status = #{arBillStatus}
|
||||
<if test="currency != null and currency != ''">
|
||||
and currency = #{currency}
|
||||
</if>
|
||||
<if test="excludedBillIds != null and excludedBillIds.size() > 0">
|
||||
and bill_id not in
|
||||
<foreach collection="excludedBillIds" item="excludedBillId" open="(" separator="," close=")">
|
||||
#{excludedBillId}
|
||||
</foreach>
|
||||
</if>
|
||||
order by biz_date, order_no, bill_id
|
||||
</select>
|
||||
|
||||
<select id="sumPrcOrderBillIncomeByCustomerPeriod" resultType="java.math.BigDecimal">
|
||||
select coalesce(sum(income_total), 0)
|
||||
from prc_order_bill
|
||||
where customer_id = #{customerId}
|
||||
<if test="customerCode != null and customerCode != ''">
|
||||
and customer_code like concat('%', #{customerCode}, '%')
|
||||
</if>
|
||||
<if test="orderOrTrackingNo != null and orderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{orderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{orderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
<if test="excludeOrderOrTrackingNo != null and excludeOrderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{excludeOrderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{excludeOrderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
and biz_date <= #{cutoffDate}
|
||||
and ar_bill_status = #{arBillStatus}
|
||||
<if test="currency != null and currency != ''">
|
||||
and currency = #{currency}
|
||||
</if>
|
||||
</select>
|
||||
|
||||
<sql id="customerPeriodConditions">
|
||||
where customer_id = #{customerId}
|
||||
<if test="customerCode != null and customerCode != ''">
|
||||
and customer_code like concat('%', #{customerCode}, '%')
|
||||
</if>
|
||||
<if test="orderOrTrackingNo != null and orderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{orderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{orderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
and biz_date <= #{cutoffDate}
|
||||
and ar_bill_status = #{arBillStatus}
|
||||
<if test="currency != null and currency != ''">
|
||||
and currency = #{currency}
|
||||
</if>
|
||||
<if test="snapshotCreateTime != null">
|
||||
and (create_time is null or create_time <= #{snapshotCreateTime})
|
||||
</if>
|
||||
<if test="billIds != null and billIds.size() > 0">
|
||||
and bill_id in
|
||||
<foreach collection="billIds" item="billId" open="(" separator="," close=")">
|
||||
#{billId}
|
||||
</foreach>
|
||||
</if>
|
||||
<if test="excludedBillIds != null and excludedBillIds.size() > 0">
|
||||
and bill_id not in
|
||||
<foreach collection="excludedBillIds" item="excludedBillId" open="(" separator="," close=")">
|
||||
#{excludedBillId}
|
||||
</foreach>
|
||||
</if>
|
||||
</sql>
|
||||
|
||||
<!-- 异步生成使用 bill_id 游标批量读取,避免深分页和一次加载全量订单。 -->
|
||||
<select id="selectPrcOrderBillByCustomerPeriodCursor" resultMap="PrcOrderBillResult">
|
||||
<include refid="selectPrcOrderBillVo"/>
|
||||
<include refid="customerPeriodConditions"/>
|
||||
<if test="lastSourceBillId != null and lastSourceBillId != ''">
|
||||
and bill_id > #{lastSourceBillId}
|
||||
</if>
|
||||
order by bill_id
|
||||
limit #{limit}
|
||||
</select>
|
||||
|
||||
<!-- 全选模式先统计总数,用于任务进度和空范围校验。 -->
|
||||
<select id="countPrcOrderBillByCustomerPeriod" resultType="int">
|
||||
select count(1)
|
||||
from prc_order_bill
|
||||
<include refid="customerPeriodConditions"/>
|
||||
</select>
|
||||
|
||||
<select id="selectPrcOrderBillByCustomerCutoffAndIds" resultMap="PrcOrderBillResult">
|
||||
<include refid="selectPrcOrderBillVo"/>
|
||||
where customer_id = #{customerId}
|
||||
@@ -182,6 +270,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
<if test="customerCode != null and customerCode != ''">
|
||||
and customer_code like concat('%', #{customerCode}, '%')
|
||||
</if>
|
||||
<if test="orderOrTrackingNo != null and orderOrTrackingNo != ''">
|
||||
and (order_no like concat('%', #{orderOrTrackingNo}, '%')
|
||||
or tracking_no like concat('%', #{orderOrTrackingNo}, '%'))
|
||||
</if>
|
||||
<if test="currency != null and currency != ''">
|
||||
and currency = #{currency}
|
||||
</if>
|
||||
@@ -280,6 +372,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
where bill_id = #{billId}
|
||||
</update>
|
||||
|
||||
<!-- 抢占来源订单:只有未入账订单可以变更为已入账,防止重复生成。 -->
|
||||
<update id="claimArBillOrders">
|
||||
update prc_order_bill
|
||||
set ar_bill_status = #{toStatus}, updated_by = #{operator}, update_time = sysdate()
|
||||
@@ -299,4 +392,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
#{billId}
|
||||
</foreach>
|
||||
</update>
|
||||
|
||||
<update id="releaseArBillOrdersByArBillId">
|
||||
update prc_order_bill p
|
||||
inner join ar_bill_detail d on d.prc_order_bill_id = p.bill_id
|
||||
set p.ar_bill_status = #{toStatus}, p.updated_by = #{operator}, p.update_time = sysdate()
|
||||
where d.ar_bill_id = #{arBillId}
|
||||
and p.ar_bill_status = #{fromStatus}
|
||||
</update>
|
||||
</mapper>
|
||||
|
||||
@@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS ar_bill (
|
||||
written_off_amount DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '已核销金额缓存',
|
||||
unwritten_amount DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '未核销金额缓存',
|
||||
status VARCHAR(30) NOT NULL COMMENT '状态:DRAFT=草稿,CONFIRMED=已确认,PARTIAL_WRITTEN_OFF=部分核销,WRITTEN_OFF=已核销,VOID=已作废',
|
||||
generation_status VARCHAR(20) NOT NULL DEFAULT 'READY' COMMENT '生成状态:GENERATING=生成中,READY=可用,FAILED=生成失败',
|
||||
bill_version INT(11) NOT NULL DEFAULT 1 COMMENT '账单版本',
|
||||
bank_account_name VARCHAR(100) DEFAULT NULL COMMENT '收款账户名称快照',
|
||||
bank_account_no VARCHAR(128) DEFAULT NULL COMMENT '收款账号快照,应用层脱敏展示',
|
||||
@@ -40,6 +41,34 @@ CREATE TABLE IF NOT EXISTS ar_bill (
|
||||
KEY idx_ar_bill_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='正式应收账单主表';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ar_bill_generate_task (
|
||||
task_id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '生成任务ID',
|
||||
task_no VARCHAR(50) NOT NULL COMMENT '生成任务编号',
|
||||
ar_bill_id BIGINT(20) NOT NULL COMMENT '应收账单ID',
|
||||
selection_mode VARCHAR(20) NOT NULL COMMENT '选择模式:EXPLICIT=手动选择,ALL_MATCHED=全选查询结果',
|
||||
request_payload LONGTEXT NOT NULL COMMENT '生成请求快照JSON',
|
||||
snapshot_create_time DATETIME DEFAULT NULL COMMENT '来源订单创建时间快照',
|
||||
last_source_bill_id VARCHAR(36) DEFAULT NULL COMMENT '来源订单游标',
|
||||
total_count INT(11) NOT NULL DEFAULT -1 COMMENT '待处理订单数,-1表示尚未统计',
|
||||
processed_count INT(11) NOT NULL DEFAULT 0 COMMENT '已处理订单数',
|
||||
success_count INT(11) NOT NULL DEFAULT 0 COMMENT '成功订单数',
|
||||
total_amount DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '当前生成金额',
|
||||
status VARCHAR(30) NOT NULL COMMENT '任务状态:WAITING=待处理,RUNNING=生成中,SUCCESS=生成成功,FAILED=生成失败,CANCEL_REQUESTED=取消中,CANCELED=已取消',
|
||||
error_message VARCHAR(1000) DEFAULT NULL COMMENT '错误信息',
|
||||
request_token VARCHAR(64) NOT NULL COMMENT '请求幂等标识',
|
||||
create_by VARCHAR(64) NOT NULL COMMENT '创建人',
|
||||
create_time DATETIME NOT NULL COMMENT '创建时间',
|
||||
started_at DATETIME DEFAULT NULL COMMENT '开始时间',
|
||||
heartbeat_time DATETIME DEFAULT NULL COMMENT '最近心跳时间',
|
||||
finished_at DATETIME DEFAULT NULL COMMENT '完成时间',
|
||||
PRIMARY KEY (task_id),
|
||||
UNIQUE KEY uk_ar_bill_generate_task_no (task_no),
|
||||
UNIQUE KEY uk_ar_bill_generate_request_token (request_token),
|
||||
KEY idx_ar_bill_generate_status (status, create_time),
|
||||
KEY idx_ar_bill_generate_creator (create_by, status, create_time),
|
||||
KEY idx_ar_bill_generate_bill (ar_bill_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='应收账单异步生成任务';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ar_bill_detail (
|
||||
detail_id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '账单订单明细ID',
|
||||
ar_bill_id BIGINT(20) NOT NULL COMMENT '应收账单ID',
|
||||
@@ -98,13 +127,54 @@ CREATE TABLE IF NOT EXISTS ar_bill_detail_fee (
|
||||
CONSTRAINT fk_ar_detail_fee_detail FOREIGN KEY (detail_id) REFERENCES ar_bill_detail (detail_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='应收账单费用快照';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ar_export_template (
|
||||
template_id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '导出模板ID',
|
||||
template_code VARCHAR(50) NOT NULL COMMENT '模板编码,例如 AR_CUSTOMER_BILL',
|
||||
template_name VARCHAR(100) NOT NULL COMMENT '模板名称',
|
||||
business_type VARCHAR(50) NOT NULL COMMENT '业务类型,例如 AR_BILL',
|
||||
template_version VARCHAR(50) NOT NULL COMMENT '模板版本,已启用版本不可覆盖',
|
||||
storage_type VARCHAR(20) NOT NULL DEFAULT 'CLASSPATH' COMMENT '存储类型:CLASSPATH=应用内置资源,FILE=服务器文件,OSS=对象存储,MINIO=MinIO对象存储',
|
||||
storage_key VARCHAR(500) NOT NULL COMMENT '模板文件存储Key或classpath资源路径',
|
||||
file_hash VARCHAR(128) DEFAULT NULL COMMENT '模板文件SHA-256校验值',
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'ENABLED' COMMENT '状态:ENABLED=启用,DISABLED=停用',
|
||||
is_default CHAR(1) NOT NULL DEFAULT '0' COMMENT '是否默认模板:1是0否',
|
||||
effective_start DATE DEFAULT NULL COMMENT '生效开始日期',
|
||||
effective_end DATE DEFAULT NULL COMMENT '生效结束日期',
|
||||
remark VARCHAR(500) DEFAULT NULL COMMENT '备注',
|
||||
create_by VARCHAR(64) NOT NULL COMMENT '创建人',
|
||||
create_time DATETIME NOT NULL COMMENT '创建时间',
|
||||
update_by VARCHAR(64) DEFAULT NULL COMMENT '更新人',
|
||||
update_time DATETIME DEFAULT NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (template_id),
|
||||
UNIQUE KEY uk_ar_export_template_code_version (business_type, template_code, template_version),
|
||||
KEY idx_ar_export_template_default (business_type, status, is_default, effective_start, effective_end)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='应收账单导出模板管理';
|
||||
|
||||
INSERT INTO ar_export_template (
|
||||
template_code, template_name, business_type, template_version, storage_type, storage_key,
|
||||
file_hash, status, is_default, create_by, create_time, remark
|
||||
)
|
||||
SELECT
|
||||
'AR_CUSTOMER_BILL', '应收账单默认模板', 'AR_BILL', '1.0', 'CLASSPATH',
|
||||
'templates/ar/ar_bill_template.xlsx', '735002ac3561e0579b724c0612a2c5ce2d6725bc7fd39c450b0aeff70911a45e', 'ENABLED', '1', 'system', NOW(), '系统内置默认模板'
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM ar_export_template
|
||||
WHERE business_type = 'AR_BILL'
|
||||
AND template_code = 'AR_CUSTOMER_BILL'
|
||||
AND template_version = '1.0'
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS ar_bill_export (
|
||||
export_id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '导出ID',
|
||||
ar_bill_id BIGINT(20) NOT NULL COMMENT '应收账单ID',
|
||||
file_name VARCHAR(255) NOT NULL COMMENT '下载展示名称',
|
||||
file_type VARCHAR(20) NOT NULL COMMENT 'XLSX/PDF',
|
||||
template_id BIGINT(20) DEFAULT NULL COMMENT '提交导出任务时绑定的模板ID',
|
||||
template_code VARCHAR(50) NOT NULL COMMENT '导出模板标识',
|
||||
template_version VARCHAR(50) DEFAULT NULL COMMENT '模板版本',
|
||||
template_storage_type VARCHAR(20) DEFAULT NULL COMMENT '绑定模板存储类型',
|
||||
template_storage_key VARCHAR(500) DEFAULT NULL COMMENT '绑定模板存储Key',
|
||||
template_hash VARCHAR(128) DEFAULT NULL COMMENT '绑定模板SHA-256校验值',
|
||||
storage_key VARCHAR(500) NOT NULL COMMENT '对象存储或本地文件Key',
|
||||
file_size BIGINT(20) DEFAULT NULL COMMENT '文件字节数',
|
||||
file_hash VARCHAR(128) DEFAULT NULL COMMENT 'SHA-256校验值',
|
||||
@@ -115,6 +185,7 @@ CREATE TABLE IF NOT EXISTS ar_bill_export (
|
||||
remark VARCHAR(500) DEFAULT NULL COMMENT '失败原因或备注',
|
||||
PRIMARY KEY (export_id),
|
||||
KEY idx_ar_bill_export_bill (ar_bill_id, export_time),
|
||||
KEY idx_ar_bill_export_template (template_id),
|
||||
KEY idx_ar_bill_export_status (export_status),
|
||||
CONSTRAINT fk_ar_bill_export_bill FOREIGN KEY (ar_bill_id) REFERENCES ar_bill (ar_bill_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='应收账单导出文件元数据';
|
||||
@@ -145,4 +216,144 @@ CREATE TABLE IF NOT EXISTS ar_bill_log (
|
||||
KEY idx_ar_bill_log_request (request_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='应收账单操作日志';
|
||||
|
||||
-- ============================================================
|
||||
-- 兼容已执行旧版本脚本的增量补齐逻辑
|
||||
-- 本文件是应收账单模块唯一数据库脚本,新库和存量库均可重复执行。
|
||||
-- ============================================================
|
||||
SET @ar_db_name := DATABASE();
|
||||
|
||||
-- 1. 异步生成任务依赖字段
|
||||
SET @ar_has_generation_status := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill'
|
||||
AND COLUMN_NAME = 'generation_status'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_generation_status = 0,
|
||||
'ALTER TABLE ar_bill ADD COLUMN generation_status VARCHAR(20) NOT NULL DEFAULT ''READY'' COMMENT ''生成状态:GENERATING=生成中,READY=可用,FAILED=生成失败'' AFTER status',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
-- 异步生成任务状态增加中文含义,便于数据库运维和排查。
|
||||
-- 已存在 status 时只修改定义,不重复新增;兼容历史上已创建但字段不完整的任务表。
|
||||
SET @ar_has_task_status := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_generate_task'
|
||||
AND COLUMN_NAME = 'status'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_task_status = 0,
|
||||
'ALTER TABLE ar_bill_generate_task ADD COLUMN status VARCHAR(30) NOT NULL COMMENT ''任务状态:WAITING=待处理,RUNNING=生成中,SUCCESS=生成成功,FAILED=生成失败,CANCEL_REQUESTED=取消中,CANCELED=已取消'' AFTER total_amount',
|
||||
'ALTER TABLE ar_bill_generate_task MODIFY COLUMN status VARCHAR(30) NOT NULL COMMENT ''任务状态:WAITING=待处理,RUNNING=生成中,SUCCESS=生成成功,FAILED=生成失败,CANCEL_REQUESTED=取消中,CANCELED=已取消''');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
UPDATE ar_bill
|
||||
SET generation_status = 'READY'
|
||||
WHERE generation_status IS NULL;
|
||||
|
||||
-- 2. 为异步游标查询补充来源订单索引。
|
||||
-- 来源表可能尚未由价格模块脚本创建,因此这里做存在性判断。
|
||||
SET @ar_has_source_table := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'prc_order_bill'
|
||||
);
|
||||
SET @ar_has_source_cursor_index := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'prc_order_bill'
|
||||
AND INDEX_NAME = 'idx_bill_ar_async_cursor'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_source_table = 1 AND @ar_has_source_cursor_index = 0,
|
||||
'ALTER TABLE prc_order_bill ADD INDEX idx_bill_ar_async_cursor (customer_id, currency, ar_bill_status, create_time, bill_id)',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
-- 3. 兼容已存在的模板表和导出记录表,补齐模板字段、注释及索引。
|
||||
ALTER TABLE ar_export_template
|
||||
MODIFY COLUMN storage_type VARCHAR(20) NOT NULL DEFAULT 'CLASSPATH'
|
||||
COMMENT '存储类型:CLASSPATH=应用内置资源,FILE=服务器文件,OSS=对象存储,MINIO=MinIO对象存储',
|
||||
MODIFY COLUMN status VARCHAR(20) NOT NULL DEFAULT 'ENABLED'
|
||||
COMMENT '状态:ENABLED=启用,DISABLED=停用';
|
||||
|
||||
SET @ar_has_template_id := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_export'
|
||||
AND COLUMN_NAME = 'template_id'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_template_id = 0,
|
||||
'ALTER TABLE ar_bill_export ADD COLUMN template_id BIGINT(20) DEFAULT NULL COMMENT ''提交导出任务时绑定的模板ID'' AFTER file_type',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
SET @ar_has_template_storage_type := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_export'
|
||||
AND COLUMN_NAME = 'template_storage_type'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_template_storage_type = 0,
|
||||
'ALTER TABLE ar_bill_export ADD COLUMN template_storage_type VARCHAR(20) DEFAULT NULL COMMENT ''绑定模板存储类型'' AFTER template_version',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
SET @ar_has_template_storage_key := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_export'
|
||||
AND COLUMN_NAME = 'template_storage_key'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_template_storage_key = 0,
|
||||
'ALTER TABLE ar_bill_export ADD COLUMN template_storage_key VARCHAR(500) DEFAULT NULL COMMENT ''绑定模板存储Key'' AFTER template_storage_type',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
SET @ar_has_template_hash := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_export'
|
||||
AND COLUMN_NAME = 'template_hash'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_template_hash = 0,
|
||||
'ALTER TABLE ar_bill_export ADD COLUMN template_hash VARCHAR(128) DEFAULT NULL COMMENT ''绑定模板SHA-256校验值'' AFTER template_storage_key',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
SET @ar_has_template_index := (
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = @ar_db_name
|
||||
AND TABLE_NAME = 'ar_bill_export'
|
||||
AND INDEX_NAME = 'idx_ar_bill_export_template'
|
||||
);
|
||||
SET @ar_sql := IF(@ar_has_template_index = 0,
|
||||
'ALTER TABLE ar_bill_export ADD INDEX idx_ar_bill_export_template (template_id)',
|
||||
'SELECT 1');
|
||||
PREPARE ar_stmt FROM @ar_sql;
|
||||
EXECUTE ar_stmt;
|
||||
DEALLOCATE PREPARE ar_stmt;
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
Reference in New Issue
Block a user