Browse Source

refactor(botp): 重构字段映射策略体系与插件兼容机制

- 将映射策略接口改为按单行目标+源行组求值,解耦编排层与策略层
- BotpMappingContext 由 if/else 工厂改为 EnumMap 策略工厂,修复未知取值方式抛 NPE 的问题
- 各策略实现改为 Spring bean,依赖通过 @Resource 注入替代手工 getBean
- 新增按条件取值策略(BotpMappingStrategyCondition),复用在线规则引擎求值
- AbstractTransformPlugIn 改为实现 ConvertPlugIn 接口的兼容桥,存量插件无需改代码
- 回写插件分录表名从映射计划动态获取,修复 Long 对象引用比较的 bug
- 新增 BotpMappingException 替代 NPE,提供含配置原值的可读报错
- 抽取 BillDataConverter 工具类,编排器与兼容入口共用单据数据转换逻辑
dev-lml
chenchuchuan 1 month ago
parent
commit
da2be26f9c
  1. 17
      common/common-botp/pom.xml
  2. 26
      common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java
  3. 64
      common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRequest.java
  4. 54
      common/common-botp/src/main/java/apelet/common/botp/dto/ConvertResult.java
  5. 31
      common/common-botp/src/main/java/apelet/common/botp/dto/ConvertedBill.java
  6. 50
      common/common-botp/src/main/java/apelet/common/botp/exception/BotpMappingException.java
  7. 11
      common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java
  8. 60
      common/common-botp/src/main/java/apelet/common/botp/model/constant/BotpRuleConstant.java
  9. 94
      common/common-botp/src/main/java/apelet/common/botp/model/constant/ExcessActionEnum.java
  10. 101
      common/common-botp/src/main/java/apelet/common/botp/model/constant/MergeMethodEnum.java
  11. 83
      common/common-botp/src/main/java/apelet/common/botp/model/constant/PluginTypeEnum.java
  12. 115
      common/common-botp/src/main/java/apelet/common/botp/model/constant/ReverseWriteModeEnum.java
  13. 125
      common/common-botp/src/main/java/apelet/common/botp/model/constant/WriteBackHookEnum.java
  14. 106
      common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java
  15. 109
      common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java
  16. 97
      common/common-botp/src/main/java/apelet/common/botp/plugin/BotpPlugInLoader.java
  17. 41
      common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java
  18. 207
      common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java
  19. 44
      common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugIn.java
  20. 57
      common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugInContext.java
  21. 83
      common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackContext.java
  22. 90
      common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackPlugIn.java
  23. 31
      common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java
  24. 18
      common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java
  25. 1039
      common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java
  26. 531
      common/common-botp/src/main/java/apelet/common/botp/service/execute/ConvertOrchestrator.java
  27. 96
      common/common-botp/src/main/java/apelet/common/botp/service/execute/RuleVersionResolver.java
  28. 814
      common/common-botp/src/main/java/apelet/common/botp/service/execute/WriteBackOrchestrator.java
  29. 61
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertBatch.java
  30. 35
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java
  31. 67
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConditionBranch.java
  32. 78
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertMappingPlan.java
  33. 29
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertSourceRow.java
  34. 61
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertSourceRowGroup.java
  35. 40
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java
  36. 41
      common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ResolvedConvertRule.java
  37. 97
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java
  38. 71
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java
  39. 27
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java
  40. 150
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyCondition.java
  41. 27
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java
  42. 55
      common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java
  43. 34
      common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java
  44. 170
      common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java
  45. 141
      common/common-botp/src/main/java/apelet/common/botp/util/BillDataConverter.java
  46. 195
      common/common-botp/src/main/java/apelet/common/botp/util/MappingValueMerger.java
  47. 106
      common/common-botp/src/main/java/apelet/common/botp/util/RuleValueCalculator.java
  48. 30
      common/common-core/src/main/java/apelet/common/core/botp/BotpReverseWriteFacade.java
  49. 70
      common/common-core/src/main/java/apelet/common/core/botp/BotpReverseWriteSupport.java
  50. 113
      common/common-core/src/main/java/apelet/common/core/botp/BotpWriteBackRequest.java
  51. 11
      common/common-generator/src/main/java/apelet/common/generator/service/impl/OnlFormHeadServiceImpl.java
  52. 150
      common/common-online/src/main/java/apelet/common/online/plugin/pre/AuditOperationServicePlugIn.java
  53. 57
      common/common-online/src/main/java/apelet/common/online/plugin/pre/RevokeOperationServicePlugIn.java
  54. 198
      common/common-online/src/main/java/apelet/common/online/plugin/pre/SaveOperationServicePlugIn.java
  55. 41
      common/common-online/src/main/java/apelet/common/online/plugin/pre/UnAuditOperationServicePlugIn.java

17
common/common-botp/pom.xml

@ -17,7 +17,7 @@ @@ -17,7 +17,7 @@
<dependency>
<groupId>apelet</groupId>
<artifactId>common-core</artifactId>
<version>${common-core.version}</version>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>apelet</groupId>
@ -68,4 +68,19 @@ @@ -68,4 +68,19 @@
</dependency>
</dependencies>
<!--
【临时配置,提交前删除】
项目默认继承的 maven-surefire-plugin 是 2.12.4(2013 年版),只支持 JUnit3/4,
跑 JUnit5 会出现 "Tests run: 0"。这里临时升到 2.22.2 让本地单测能跑。
-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>

26
common/common-botp/src/main/java/apelet/common/botp/controller/ConvertRuleController.java

@ -2,6 +2,7 @@ package apelet.common.botp.controller; @@ -2,6 +2,7 @@ package apelet.common.botp.controller;
import apelet.common.botp.dto.ConvertRelationDelDto;
import apelet.common.botp.dto.ConvertRelationListDto;
import apelet.common.botp.dto.ConvertRequest;
import apelet.common.botp.dto.TransfromDto;
import apelet.common.botp.model.AllField;
import apelet.common.botp.model.ConvertRule;
@ -193,8 +194,31 @@ public class ConvertRuleController { @@ -193,8 +194,31 @@ public class ConvertRuleController {
}
/**
* 单据转换(推式下推 / 拉式选单共用)。
*
* <p>与下面的 {@code /transform} 的区别:本接口支持多源单、分单策略、合并取值、按版本执行,
* 并返回<b>每一个</b>目标单的 id 与单号;{@code /transform} 是兼容老前端的单目标单入口。</p>
*
* @param request 转换请求。
* @return 转换结果。
*/
@PostMapping(value = "/convert")
@Schema(description = "单据转换(多源单 / 分单策略 / 按版本)")
public ResponseResult<?> convert(@RequestBody ConvertRequest request) {
return ResponseResult.success(convertRuleService.convert(request));
}
/**
* 单据转换(兼容入口,单目标单)。
*
* @param dto 转换参数。
* @return 单张目标单的转换结果。
* @deprecated 请改用 {@code /convert}。
*/
@Deprecated
@PostMapping(value = "/transform")
@Schema(description = "单据转换")
@Schema(description = "单据转换(兼容:单目标单)")
public ResponseResult<?> transform(@RequestBody TransfromDto dto) {
return ResponseResult.success(convertRuleService.transform(dto.getBotpId()

64
common/common-botp/src/main/java/apelet/common/botp/dto/ConvertRequest.java

@ -0,0 +1,64 @@ @@ -0,0 +1,64 @@
package apelet.common.botp.dto;
import lombok.Data;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 转换请求。
*
* <p>推式(下推)与拉式(选单)共用本入参——两者的差异只在「源单 id 从哪来」:
* 推式是用户在源单列表上勾选的集合,拉式是用户在选单对话框里挑出来的集合。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertRequest {
/**
* 转换规则 id。
*/
private String ruleId;
/**
* 显式指定的规则版本;为空时取最新生效版本。
*/
private Integer ruleVersion;
/**
* 源单 id 集合(允许多选,全部参与转换)。
*/
private Set<String> srcBillIds = new LinkedHashSet<>();
/**
* 构造单源请求。
*
* @param ruleId 转换规则 id。
* @param srcBillId 源单 id。
* @return 请求对象。
*/
public static ConvertRequest of(String ruleId, String srcBillId) {
ConvertRequest request = new ConvertRequest();
request.setRuleId(ruleId);
request.getSrcBillIds().add(srcBillId);
return request;
}
/**
* 构造多源请求。
*
* @param ruleId 转换规则 id。
* @param srcBillIds 源单 id 集合。
* @return 请求对象。
*/
public static ConvertRequest of(String ruleId, Set<String> srcBillIds) {
ConvertRequest request = new ConvertRequest();
request.setRuleId(ruleId);
if (srcBillIds != null) {
request.getSrcBillIds().addAll(srcBillIds);
}
return request;
}
}

54
common/common-botp/src/main/java/apelet/common/botp/dto/ConvertResult.java

@ -0,0 +1,54 @@ @@ -0,0 +1,54 @@
package apelet.common.botp.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 转换结果。
*
* <p>原实现只返回单个目标单的数据,多源下推会静默丢单;本结果改为返回<b>每个目标单</b>的
* id 与单号,前端据此打开目标单,同时携带本次实际使用的规则版本供事后回溯。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertResult {
/**
* 生成的目标单据列表。
*/
private List<ConvertedBill> bills = new ArrayList<>();
/**
* 本次实际使用的规则版本。
*/
private Integer usedRuleVersion;
/**
* 传入的源单总数。
*/
private int sourceCount;
/**
* 通过选单过滤、真正参与转换的源单数。
*/
private int passedCount;
/**
* 被选单过滤掉的源单 id。
*/
private List<String> filteredOutIds = new ArrayList<>();
/**
* 表单状态:1 新增状态(已落库)/ 2 保存状态(未落库,前端要自己保存)。
*/
private String formStatus;
/**
* 表单类型:1 路由表单 / 2 在线表单。
*/
private String formType;
}

31
common/common-botp/src/main/java/apelet/common/botp/dto/ConvertedBill.java

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
package apelet.common.botp.dto;
import apelet.common.botp.service.execute.entity.BillData;
import lombok.Data;
/**
* 一张目标单据的转换产物。
*
* <p>一对一策略下有多少条源单就有多少个本对象;多对一恒为一个;按规则分组合并等于分组数。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertedBill {
/**
* 目标单 id。autoSave 关闭时为空(此时单据还没落库)。
*/
private Long billId;
/**
* 目标单号。
*/
private String billNumber;
/**
* 前端打开目标单要用的数据(表头 + 分录)。
*/
private BillData billData;
}

50
common/common-botp/src/main/java/apelet/common/botp/exception/BotpMappingException.java

@ -0,0 +1,50 @@ @@ -0,0 +1,50 @@
package apelet.common.botp.exception;
import apelet.common.core.exception.MyRuntimeException;
/**
* BOTP 单据转换异常。
*
* <p>用于转换过程中【配置错误】的可读报错,替代原先的 NPE:把出错的配置原值带进消息里,
* 便于配置管理员直接定位问题,而不是面对一个空指针堆栈。</p>
*
* <p>继承 {@link MyRuntimeException}(RuntimeException),抛出后本次操作整体回滚。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public class BotpMappingException extends MyRuntimeException {
private static final long serialVersionUID = 1L;
public BotpMappingException(String msg) {
super(msg);
}
public BotpMappingException(String msg, Throwable throwable) {
super(msg, throwable);
}
/**
* 字段映射配置了未知的取值方式。
*
* <p>原先 BotpMappingContext 是 if/else 工厂且没有 else 分支,未知取值会让策略对象保持 null,
* 直到调用时才抛 NPE。改为在构造策略时就抛出本异常。</p>
*
* @param valueMethod 配置里的取值方式原值。
* @return 含原值与可选值的异常。
*/
public static BotpMappingException unknownValueMethod(String valueMethod) {
return new BotpMappingException("字段映射的取值方式不正确:" + valueMethod + ",可选值为 " + apelet.common.botp.model.constant.ValueMethodEnum.validOptions());
}
/**
* 字段映射缺少必要配置。
*
* @param reason 具体原因。
* @return 异常。
*/
public static BotpMappingException invalidMapping(String reason) {
return new BotpMappingException("字段映射配置不正确:" + reason);
}
}

11
common/common-botp/src/main/java/apelet/common/botp/model/ConvertRelationEntry.java

@ -60,4 +60,15 @@ public class ConvertRelationEntry extends BaseModel { @@ -60,4 +60,15 @@ public class ConvertRelationEntry extends BaseModel {
@Schema(description = "目标分录id")
private String targeEntryId;
/**
* 反写前的源单字段原值。
*
* <p>只有「覆盖」方式需要它——累加/扣减天然可逆(加了多少减回去),覆盖把原值冲掉了,
* 不记下来撤销时就回不去。反向写一次记一次。</p>
*
* <p>对应 DDL:convert_relation_entry 需要新增 before_value 列。</p>
*/
@Schema(description = "反写前的源单字段原值,仅覆盖方式使用,供撤销回滚恢复")
private java.math.BigDecimal beforeValue;
}

60
common/common-botp/src/main/java/apelet/common/botp/model/constant/BotpRuleConstant.java

@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
package apelet.common.botp.model.constant;
/**
* BOTP 规则内核专用常量。
*
* <p><b>本类只服务于「转换规则 + 反写规则」这套代码</b>,不要往里放通用常量;
* 通用常量请放各自模块的常量类。</p>
*
* <h3>为什么这些值要提出来</h3>
* <p>下面这些名字/取值都是<b>跨模块或跨类共用同一份约定</b>的:比如 closed_flag 由
* common-generator 建列、common-botp 写列、迁移脚本补列,三处必须写成同一个字符串;
* 写错任何一处都是运行时才暴露的静默故障。用具名常量收敛,比散落的裸字符串安全。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public final class BotpRuleConstant {
private BotpRuleConstant() {
}
// ==================== 单据上的系统标准字段(列名) ====================
/**
* 源单行关闭标记列名。
*
* <p>分录表的系统标准字段:新建表单由 {@code OnlFormHeadServiceImpl} 与 parent_id / seq
* 同批自动生成;存量表由 {@code zz-resource/db-scripts/botp-source-close-flag.sql} 补列。</p>
*
* <p>反写规则的「源单行关闭条件」成立时写 1、不成立时写 0——
* 撤销/弃审把数量退回后条件不再成立,会写回 0 自动解除关闭。</p>
*/
public static final String COLUMN_CLOSED_FLAG = "closed_flag";
/**
* 来源分录ID列名。
*
* <p>下游单据上的普通在线表单字段(用户可改、可清空),语义上是「这一行从源单哪一行来的」。
* 新链路已改用系统写入的 convert_relation_entry 定位;本字段只在关系记录缺失时作为
* 迁移期回退依据,一次性切换完成后下线。</p>
*/
public static final String COLUMN_SRC_ENTRY_ID = "srcbillentryid";
// ==================== 开关类配置的取值 ====================
/**
* 开关类配置视为「开」的文本取值。
*
* <p>用于插件启用、规则启用等 varchar 类型开关列。</p>
*/
public static final String SWITCH_ON_VALUE = "true";
/**
* 开关类配置视为「开」的数字取值。
*
* <p>历史数据里同一语义存在 "true" 与 "1" 两种口径(如 convert_rule.auto_save),
* 判定时必须两者都认,否则同一配置在不同路径下行为不同。</p>
*/
public static final String SWITCH_ON_NUMERIC_VALUE = "1";
}

94
common/common-botp/src/main/java/apelet/common/botp/model/constant/ExcessActionEnum.java

@ -0,0 +1,94 @@ @@ -0,0 +1,94 @@
package apelet.common.botp.model.constant;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 反写超额动作枚举。
*
* <p>对应 reverse_writing_rules.excess_action,落库为 varchar 的 "1"/"2",默认按「拦截报错」处理。</p>
*
* <p>仅在反写规则配置了超额检查公式、且求值判定为超额时生效。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public enum ExcessActionEnum {
/**
* 拦截报错:抛异常,整个业务操作回滚。
*/
REJECT("1", "拦截报错"),
/**
* 仅告警:记 WARN 日志后放行。
*/
WARN("2", "仅告警");
@Getter
private final String code;
@Getter
private final String description;
private static final Map<String, ExcessActionEnum> ENUM_MAP;
ExcessActionEnum(String code, String description) {
this.code = code;
this.description = description;
}
static {
ENUM_MAP = Arrays.stream(values()).collect(Collectors.toMap(ExcessActionEnum::getCode, e -> e));
}
/**
* 根据 code 获取枚举对象。
*
* @param code 超额动作编码。
* @return 枚举对象。
*/
public static ExcessActionEnum of(String code) {
return Optional.ofNullable(ENUM_MAP.get(code))
.orElseThrow(() -> new IllegalArgumentException("无法根据 code 获取超额动作:" + code));
}
/**
* 根据 code 获取枚举对象,空值按「拦截报错」处理(与字段默认值一致)。
*
* @param code 超额动作编码。
* @return 枚举对象。
*/
public static ExcessActionEnum ofNullable(String code) {
if (StringUtils.isBlank(code)) {
return REJECT;
}
return of(code.trim());
}
/**
* 根据 code 获取枚举对象,空值或未知 code 均返回 null(不兜底、不抛异常)。
*
* @param code 超额动作编码。
* @return 枚举对象;不是已知编码时返回 null。
*/
public static ExcessActionEnum parse(String code) {
return StringUtils.isBlank(code) ? null : ENUM_MAP.get(code.trim());
}
/**
* 生成可选值说明,用于错误提示。
*
* @return 形如「1-拦截报错 2-仅告警」。
*/
public static String validOptions() {
return Arrays.stream(values())
.map(e -> e.getCode() + "-" + e.getDescription())
.collect(Collectors.joining(" "));
}
}

101
common/common-botp/src/main/java/apelet/common/botp/model/constant/MergeMethodEnum.java

@ -0,0 +1,101 @@ @@ -0,0 +1,101 @@
package apelet.common.botp.model.constant;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 字段映射的合并方式枚举。
*
* <p>对应 convert_fieldmapping_entry.merge_method,落库为 varchar 的 "1"/"2"/"3",默认按「直接取」处理。</p>
*
* <p>仅在多对一或按规则分组合并、且多条源行映射到同一目标行时生效;一对一策略下无合并场景。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public enum MergeMethodEnum {
/**
* 直接取:取组内第一条源行的值。
*/
DIRECT("1", "直接取"),
/**
* 求和:组内所有源行的值相加。
*/
SUM("2", "求和"),
/**
* 拼接:组内所有源行的值用英文逗号连接,重复值自动去重。
*/
CONCAT("3", "拼接");
@Getter
private final String code;
@Getter
private final String description;
private static final Map<String, MergeMethodEnum> ENUM_MAP;
MergeMethodEnum(String code, String description) {
this.code = code;
this.description = description;
}
static {
ENUM_MAP = Arrays.stream(values()).collect(Collectors.toMap(MergeMethodEnum::getCode, e -> e));
}
/**
* 根据 code 获取枚举对象。
*
* @param code 合并方式编码。
* @return 枚举对象。
*/
public static MergeMethodEnum of(String code) {
return Optional.ofNullable(ENUM_MAP.get(code))
.orElseThrow(() -> new IllegalArgumentException("无法根据 code 获取合并方式:" + code));
}
/**
* 根据 code 获取枚举对象,空值按「直接取」处理(与字段默认值一致)。
*
* @param code 合并方式编码。
* @return 枚举对象。
*/
public static MergeMethodEnum ofNullable(String code) {
if (StringUtils.isBlank(code)) {
return DIRECT;
}
return of(code.trim());
}
/**
* 根据 code 获取枚举对象,空值或未知 code 均返回 null(不兜底、不抛异常)。
*
* <p>供保存校验等场景使用:需要区分「未配置」与「配置了非法值」时,用本方法。</p>
*
* @param code 合并方式编码。
* @return 枚举对象;不是已知编码时返回 null。
*/
public static MergeMethodEnum parse(String code) {
return StringUtils.isBlank(code) ? null : ENUM_MAP.get(code.trim());
}
/**
* 生成可选值说明,用于错误提示。
*
* @return 形如「1-直接取 2-求和 3-拼接」。
*/
public static String validOptions() {
return Arrays.stream(values())
.map(e -> e.getCode() + "-" + e.getDescription())
.collect(Collectors.joining(" "));
}
}

83
common/common-botp/src/main/java/apelet/common/botp/model/constant/PluginTypeEnum.java

@ -0,0 +1,83 @@ @@ -0,0 +1,83 @@
package apelet.common.botp.model.constant;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 插件类型枚举。
*
* <p>对应 convert_plugin_entry.type。转换插件与反写插件共用一张表,靠本字段区分:</p>
*
* <p>两者的 parentId 分别指向 convert_rule.id 与 reverse_writing_rules.id,而两张表主键值域重叠,
* 因此【所有】查询/删除都必须带上 type 条件,统一走 IConvertPluginEntryService 的收敛方法,
* 不允许各处手写 wrapper。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public enum PluginTypeEnum {
/**
* 转换插件:挂在转换规则下,实现 ConvertPlugIn。
*/
CONVERT("convert", "转换插件"),
/**
* 反写插件:挂在反写规则下,实现 WriteBackPlugIn。
*/
WRITE_BACK("writeback", "反写插件");
@Getter
private final String code;
@Getter
private final String description;
private static final Map<String, PluginTypeEnum> ENUM_MAP;
PluginTypeEnum(String code, String description) {
this.code = code;
this.description = description;
}
static {
ENUM_MAP = Arrays.stream(values()).collect(Collectors.toMap(PluginTypeEnum::getCode, e -> e));
}
/**
* 根据 code 获取枚举对象。
*
* @param code 插件类型编码。
* @return 枚举对象。
*/
public static PluginTypeEnum of(String code) {
return Optional.ofNullable(ENUM_MAP.get(code))
.orElseThrow(() -> new IllegalArgumentException("无法根据 code 获取插件类型:" + code));
}
/**
* 根据 code 获取枚举对象,空值或未知 code 均返回 null(不兜底、不抛异常)。
*
* @param code 插件类型编码。
* @return 枚举对象;不是已知编码时返回 null。
*/
public static PluginTypeEnum parse(String code) {
return StringUtils.isBlank(code) ? null : ENUM_MAP.get(code.trim());
}
/**
* 生成可选值说明,用于错误提示。
*
* @return 形如「convert-转换插件 writeback-反写插件」。
*/
public static String validOptions() {
return Arrays.stream(values())
.map(e -> e.getCode() + "-" + e.getDescription())
.collect(Collectors.joining(" "));
}
}

115
common/common-botp/src/main/java/apelet/common/botp/model/constant/ReverseWriteModeEnum.java

@ -0,0 +1,115 @@ @@ -0,0 +1,115 @@
package apelet.common.botp.model.constant;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 反写方式枚举。
*
* <p>对应 reverse_writing_formula.mode,落库为 varchar 的 "1"/"2"/"3"。</p>
*
* <p>累加与扣减互为逆运算,撤销/弃审时反向执行;覆盖不可逆,回滚需依赖反写前记录的原值
* (convert_relation_entry.before_value)。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public enum ReverseWriteModeEnum {
/**
* 累加:源单字段 + 本次值。
*/
ACCUMULATE("1", "累加"),
/**
* 扣减:源单字段 - 本次值。
*/
SUBTRACT("2", "扣减"),
/**
* 覆盖:直接用本次值冲掉源单字段。
*/
OVERWRITE("3", "覆盖");
@Getter
private final String code;
@Getter
private final String description;
private static final Map<String, ReverseWriteModeEnum> ENUM_MAP;
ReverseWriteModeEnum(String code, String description) {
this.code = code;
this.description = description;
}
static {
ENUM_MAP = Arrays.stream(values()).collect(Collectors.toMap(ReverseWriteModeEnum::getCode, e -> e));
}
/**
* 根据 code 获取枚举对象。
*
* @param code 反写方式编码。
* @return 枚举对象。
*/
public static ReverseWriteModeEnum of(String code) {
return Optional.ofNullable(ENUM_MAP.get(code))
.orElseThrow(() -> new IllegalArgumentException("无法根据 code 获取反写方式:" + code));
}
/**
* 根据 code 获取枚举对象,空值按「累加」处理。
*
* @param code 反写方式编码。
* @return 枚举对象。
*/
public static ReverseWriteModeEnum ofNullable(String code) {
if (StringUtils.isBlank(code)) {
return ACCUMULATE;
}
return of(code.trim());
}
/**
* 根据 code 获取枚举对象,空值或未知 code 均返回 null(不兜底、不抛异常)。
*
* @param code 反写方式编码。
* @return 枚举对象;不是已知编码时返回 null。
*/
public static ReverseWriteModeEnum parse(String code) {
return StringUtils.isBlank(code) ? null : ENUM_MAP.get(code.trim());
}
/**
* 取本方式的逆运算方式:累加与扣减互换,覆盖仍是覆盖(但回滚需读原值,见 {@link #OVERWRITE})。
*
* @return 逆运算方式。
*/
public ReverseWriteModeEnum reverse() {
if (this == ACCUMULATE) {
return SUBTRACT;
}
if (this == SUBTRACT) {
return ACCUMULATE;
}
return OVERWRITE;
}
/**
* 生成可选值说明,用于错误提示。
*
* @return 形如「1-累加 2-扣减 3-覆盖」。
*/
public static String validOptions() {
return Arrays.stream(values())
.map(e -> e.getCode() + "-" + e.getDescription())
.collect(Collectors.joining(" "));
}
}

125
common/common-botp/src/main/java/apelet/common/botp/model/constant/WriteBackHookEnum.java

@ -0,0 +1,125 @@ @@ -0,0 +1,125 @@
package apelet.common.botp.model.constant;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 反写插件钩子枚举,与 {@link apelet.common.botp.plugin.spi.WriteBackPlugIn} 的五个方法一一对应。
*
* <p><b>钩子由「流程走到哪一步」决定,不由配置决定</b>——配置里没有"这个插件只在某个钩子执行"的字段,
* 插件"关心哪些钩子"是通过覆盖哪些方法表达的(接口里全是 default 空实现)。</p>
*
* <pre>
* 定位关联单据
* ↓
* beforeExecWriteBackRule ← BEFORE_RULE
* ↓
* 业务规则三分支
* ↓
* 逐条公式:条件求值 → 取值 → BigDecimal 计算
* ↓
* afterCalcWriteValue ← AFTER_CALC
* ↓
* beforeExcessCheck ← BEFORE_EXCESS
* ↓
* 超额检查
* ↓
* afterExcessCheck ← AFTER_EXCESS
* ↓
* 写入源单 / 源单行关闭
* ↓
* 事务提交
* ↓
* afterCommitAmount ← AFTER_COMMIT
* </pre>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public enum WriteBackHookEnum {
/**
* 反写规则开始执行前。
*/
BEFORE_RULE("beforeExecWriteBackRule", "反写规则执行前"),
/**
* 数值算完、尚未做超额检查与写入。
*/
AFTER_CALC("afterCalcWriteValue", "数值算完后"),
/**
* 超额检查前。
*/
BEFORE_EXCESS("beforeExcessCheck", "超额检查前"),
/**
* 超额检查后。
*/
AFTER_EXCESS("afterExcessCheck", "超额检查后"),
/**
* 值已写入源单、事务提交后回调。
*/
AFTER_COMMIT("afterCommitAmount", "事务提交后");
/**
* 钩子编码,与 WriteBackPlugIn 的方法名一致。
*/
@Getter
private final String code;
/**
* 钩子说明,用于日志与配置页展示。
*/
@Getter
private final String description;
private static final Map<String, WriteBackHookEnum> ENUM_MAP;
WriteBackHookEnum(String code, String description) {
this.code = code;
this.description = description;
}
static {
ENUM_MAP = Arrays.stream(values()).collect(Collectors.toMap(WriteBackHookEnum::getCode, e -> e));
}
/**
* 根据 code 获取枚举对象。
*
* @param code 钩子编码。
* @return 枚举对象。
*/
public static WriteBackHookEnum of(String code) {
return Optional.ofNullable(ENUM_MAP.get(code))
.orElseThrow(() -> new IllegalArgumentException("无法根据 code 获取反写插件钩子:" + code));
}
/**
* 根据 code 获取枚举对象,空值或未知 code 均返回 null(不兜底、不抛异常)。
*
* @param code 钩子编码。
* @return 枚举对象;不是已知编码时返回 null。
*/
public static WriteBackHookEnum parse(String code) {
return StringUtils.isBlank(code) ? null : ENUM_MAP.get(code.trim());
}
/**
* 生成可选值说明,用于日志与错误提示。
*
* @return 形如「beforeExecWriteBackRule-反写规则执行前 ...」。
*/
public static String validOptions() {
return Arrays.stream(values())
.map(e -> e.getCode() + "-" + e.getDescription())
.collect(Collectors.joining(" "));
}
}

106
common/common-botp/src/main/java/apelet/common/botp/plugin/AbstractTransformPlugIn.java

@ -1,55 +1,137 @@ @@ -1,55 +1,137 @@
package apelet.common.botp.plugin;
import apelet.common.botp.plugin.entity.BotpRule;
import apelet.common.botp.plugin.spi.ConvertPlugIn;
import apelet.common.botp.plugin.spi.ConvertPlugInContext;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.util.ApplicationContextHolder;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import java.util.Collection;
import java.util.Collections;
/**
* 转换插件基类(兼容桥)。
*
* <p>新插件请直接实现 {@link ConvertPlugIn} 接口。本类保留是为了让存量插件<b>不改代码也能继续跑</b>——
* 它实现 {@code ConvertPlugIn},把带上下文参数的钩子转成老的无参钩子。</p>
*
* <p>老写法(子类只需覆盖无参方法):</p>
*
* <pre>
* public class XxxPlugIn extends AbstractTransformPlugIn {
* public void afterFieldMapping() { ... 用 srcBillData / destBillData ... }
* }
* </pre>
*
* <p>新写法(推荐,能直接注入依赖):</p>
*
* <pre>
* &#64;Component
* public class XxxPlugIn implements ConvertPlugIn {
* public void afterFieldMapping(ConvertPlugInContext ctx) { ... }
* }
* </pre>
*
* @author Soon
* @version 1.0
* Create by 2024/1/16 18:01
*/
public abstract class AbstractTransformPlugIn {
public abstract class AbstractTransformPlugIn implements ConvertPlugIn {
/**
* 源单据描述
*/
protected ObjectValue srcBillData;
/**
* 目标单据描述
*/
protected ObjectValue destBillData;
/**
* 转换规则
*/
protected BotpRule rule;
/**
* 单据转换后事件,最后执行
* 本次转换的上下文(含映射计划、元数据),供插件取表名/字段名,避免写死。
*/
public abstract void afterTransform();
protected ConvertPlugInContext context;
/**
* 目标字段赋值完毕后事件
* 单据转换后事件,最后执行(落库后,只做副作用)。
*/
public abstract void afterFieldMapping();
public void afterTransform() {
}
/**
* 设置转换上下文变量
* 目标字段赋值完毕后事件(落库前,可改数据)。
*/
public void setContext(ObjectValue srcBillData, ObjectValue destBillData, BotpRule rule){
public void afterFieldMapping() {
}
/**
* 设置转换上下文变量。
*
* @param srcBillData 源单数据。
* @param destBillData 目标单数据。
* @param rule 规则上下文。
*/
public void setContext(ObjectValue srcBillData, ObjectValue destBillData, BotpRule rule) {
this.srcBillData = srcBillData;
this.destBillData = destBillData;
this.rule = rule;
}
@Override
public void afterFieldMapping(ConvertPlugInContext context) {
this.context = context;
setContext(context.getSrcBillData(), context.getDestBillData(), context.getRule());
afterFieldMapping();
}
public OrmGenDataSourceUtil ormGenDataSourceUtil(){
return ApplicationContextHolder.getBean("ormGenDataSourceUtil");
@Override
public void afterTransform(ConvertPlugInContext context) {
this.context = context;
setContext(context.getSrcBillData(), context.getDestBillData(), context.getRule());
afterTransform();
}
/**
* 目标单的全部分录表名,取自映射计划而不是写死。
*
* <p>插件遍历目标分录时应该用它,这样同一套插件换单据也能复用。</p>
*
* @return 目标分录表名集合;上下文缺失时返回空集合。
*/
protected Collection<String> destEntryTables() {
if (context == null || context.getMappingPlan() == null) {
return Collections.emptyList();
}
return context.getMappingPlan().getDestEntryColumns().keySet();
}
/**
* 本次转换涉及的源分录表名,取自映射计划而不是写死。
*
* @return 源分录表名集合;上下文缺失时返回空集合。
*/
protected Collection<String> srcEntryTables() {
if (context == null || context.getMappingPlan() == null) {
return Collections.emptyList();
}
return context.getMappingPlan().getSrcEntryTables();
}
/**
* 取 ORM 数据源工具。
*
* <p>存量插件遗留的取法。新插件请直接 @Resource 注入,不要再走这个。</p>
*
* @return ORM 数据源工具。
*/
public OrmGenDataSourceUtil ormGenDataSourceUtil() {
return ApplicationContextHolder.getBean("ormGenDataSourceUtil");
}
}

109
common/common-botp/src/main/java/apelet/common/botp/plugin/BackPurReqTransformPlugIn.java

@ -1,5 +1,7 @@ @@ -1,5 +1,7 @@
package apelet.common.botp.plugin;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.constant.BotpRuleConstant;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.orm.impl.Selector;
@ -8,49 +10,92 @@ import apelet.common.orm.impl.SelectorItem; @@ -8,49 +10,92 @@ import apelet.common.orm.impl.SelectorItem;
import java.math.BigDecimal;
/**
* 采购申请下推采购订单后回写采购申请分录已订货数量
* 下推后回写源单分录的已订货数量:把目标分录的 qty 累加到源分录的 orderqty。
*
* <p><b>改造点(FR-7.4)</b>:源/目标分录表名原来写死 {@code pur_apply_entry} /
* {@code pm_purorderbill_entry},现在都从映射计划取。</p>
*
* <p><b>改造点(回归修复)</b>:原来用 {@code srcEntryId == srcbillentryid} 比较两个 Long——
* 比的是对象引用而不是值,只有 id 落在 Long 缓存区间(-128~127)才侥幸成立,
* 实际对真实单据几乎从不生效,且不报错。现改为按值比较。</p>
*
* <p><b>遗留说明(未收口)</b>:本插件本质是「反写」——把目标单的数据写回源单,与新引擎
* {@code WriteBackOrchestrator} 的职责重叠。之所以<b>不</b>像 ReverseWritingPlugIn 那样停用,
* 是因为它是写死的具体业务规则(qty → orderqty),没有配置化的等价物;
* 停用它会让「下推后回写已订货数量」直接失效。</p>
*
* <p>收口路径:先为采购申请/采购订单配一条反写规则(公式:已订货数量 + 本次数量,累加),
* 验证生效后再从 convert_plugin_entry 中移除本插件配置、删除本类。</p>
*
* @author Soon
* @version 1.0
*/
public class BackPurReqTransformPlugIn extends AbstractTransformPlugIn{
public class BackPurReqTransformPlugIn extends AbstractTransformPlugIn {
/**
* 目标分录的数量字段。
*/
private static final String FIELD_QTY = "qty";
/**
* 源分录的已订货数量字段。
*/
private static final String FIELD_ORDER_QTY = "orderqty";
@Override
public void afterTransform() {
}
@Override
public void afterFieldMapping() {
//源单据 申请单
ObjectCollection srcObjectCollection =
srcBillData.getObjectCollection("pur_apply_entry");
//目标 订单
ObjectCollection descObjectCollection =
destBillData.getObjectCollection("pm_purorderbill_entry");
for (int i = 0 ; i < descObjectCollection.size() ; i++){
//目标单据
ObjectValue objectValue = descObjectCollection.getObject(i);
BigDecimal qty = objectValue.getBigDecimal("qty");
Long srcbillentryid = objectValue.getLong("srcbillentryid");
//原单据
for (int j = 0 ; j < srcObjectCollection.size() ; j++){
ObjectValue srcobjv = srcObjectCollection.getObject(j);
Long srcEntryId = srcobjv.getLong("id");
if(srcEntryId==srcbillentryid){
ObjectValue purReqObjV = new ObjectValue("pur_apply_entry");
purReqObjV.put("id",srcEntryId);
purReqObjV.put("orderqty",srcobjv.getBigDecimal("orderqty").add(qty));
Selector selector = new Selector();
selector.getList().add(new SelectorItem("orderqty"));
try{
ormGenDataSourceUtil().update(purReqObjV.getTableName(),purReqObjV,selector);
}catch (Exception e1){
e1.printStackTrace();;
throw new RuntimeException(e1);
}
for (String destEntryTable : destEntryTables()) {
ObjectCollection destRows = destBillData.getObjectCollection(destEntryTable);
if (destRows == null) {
continue;
}
for (int i = 0; i < destRows.size(); i++) {
ObjectValue destRow = destRows.getObject(i);
Long srcEntryId = destRow.getLong(BotpRuleConstant.COLUMN_SRC_ENTRY_ID);
if (srcEntryId == null) {
continue;
}
accumulate(srcEntryId, destRow.getBigDecimal(FIELD_QTY));
}
}
}
/**
* 把增量累加到源分录的已订货数量上。
*
* @param srcEntryId 源分录行 id。
* @param qty 本次增量,为空时跳过。
*/
private void accumulate(Long srcEntryId, BigDecimal qty) {
if (qty == null) {
return;
}
for (String srcEntryTable : srcEntryTables()) {
ObjectValue srcRow;
try {
srcRow = ormGenDataSourceUtil().queryOne(srcEntryTable, srcEntryId);
} catch (Exception e) {
throw new BotpMappingException("回写源单分录时查询失败,表名=" + srcEntryTable + ",id=" + srcEntryId, e);
}
if (srcRow == null) {
continue;
}
BigDecimal current = srcRow.getBigDecimal(FIELD_ORDER_QTY);
ObjectValue update = new ObjectValue(srcEntryTable);
update.put("id", srcEntryId);
update.put(FIELD_ORDER_QTY, (current == null ? BigDecimal.ZERO : current).add(qty));
Selector selector = new Selector();
selector.getList().add(new SelectorItem(FIELD_ORDER_QTY));
try {
ormGenDataSourceUtil().update(srcEntryTable, update, selector);
} catch (Exception e) {
throw new BotpMappingException("回写源单分录失败,表名=" + srcEntryTable + ",id=" + srcEntryId, e);
}
return;
}
}
}

97
common/common-botp/src/main/java/apelet/common/botp/plugin/BotpPlugInLoader.java

@ -0,0 +1,97 @@ @@ -0,0 +1,97 @@
package apelet.common.botp.plugin;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.core.util.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Component;
/**
* BOTP 插件加载器:按配置里的类名把插件变成实例。
*
* <p>加载顺序:<b>先取 Spring 容器 bean,取不到再反射 newInstance</b>。</p>
*
* <p>原实现直接用 {@code clazz.newInstance()},插件不走 Spring,拿不到依赖注入,只能在字段初始化时
* 手工 {@code ApplicationContextHolder.getBean("bean名")}。改为 bean 优先后,插件可以正常 @Autowired。</p>
*
* <p><b>加载失败一律抛异常,不静默跳过</b>——插件是规则里声明的必经逻辑,静默跳过会让用户以为
* 配置生效了。这一点与「反写找不到关联关系时记 WARN 跳过」正好相反:前者是配置错必须暴露,
* 后者是历史数据可能本就无关联。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
@Slf4j
public class BotpPlugInLoader {
/**
* 按类名加载插件实例。
*
* @param className 插件全类名(配置在 convert_plugin_entry.class_name)。
* @param spiType 期望的插件接口类型,如 ConvertPlugIn.class / WriteBackPlugIn.class。
* @param <T> 插件接口类型。
* @return 插件实例,来自 Spring 容器或反射创建。
*/
public <T> T load(String className, Class<T> spiType) {
if (className == null || className.trim().isEmpty()) {
throw new BotpMappingException("插件类名为空,无法加载 " + spiType.getSimpleName());
}
String name = className.trim();
Class<?> clazz = resolveClass(name);
if (!spiType.isAssignableFrom(clazz)) {
throw new BotpMappingException("插件类 " + name + " 未实现 " + spiType.getName() + ",请检查插件配置");
}
Object instance = getBeanQuietly(clazz);
if (instance == null) {
instance = newInstance(name, clazz);
}
return spiType.cast(instance);
}
/**
* 加载类对象。
*
* @param className 插件全类名。
* @return 类对象。
*/
private Class<?> resolveClass(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new BotpMappingException("插件类不存在:" + className + ",请确认该类已随应用一起部署", e);
}
}
/**
* 从 Spring 容器取 bean,取不到返回 null(不抛异常)。
*
* <p>ApplicationContextHolder 没有安全取法,这里自己兜住 BeansException。</p>
*
* @param clazz 插件类。
* @return bean 实例;容器里没有该类型的 bean 时返回 null。
*/
private Object getBeanQuietly(Class<?> clazz) {
try {
return ApplicationContextHolder.getBean(clazz);
} catch (BeansException e) {
log.debug("插件类 {} 不是 Spring bean,改为反射创建", clazz.getName());
return null;
}
}
/**
* 反射创建实例。
*
* @param className 插件全类名。
* @param clazz 插件类。
* @return 实例。
*/
private Object newInstance(String className, Class<?> clazz) {
try {
return clazz.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new BotpMappingException("插件类实例化失败:" + className + ",请确认存在无参构造方法", e);
}
}
}

41
common/common-botp/src/main/java/apelet/common/botp/plugin/PurorderTransformPlugIn.java

@ -6,30 +6,47 @@ import apelet.common.core.object.ObjectValue; @@ -6,30 +6,47 @@ import apelet.common.core.object.ObjectValue;
import java.math.BigDecimal;
/**
* 目标分录金额 = 数量 × 单价。
*
* <p><b>改造点(FR-7.4)</b>:原来写死 {@code pur_order_entry},换单据就得改 Java 重新发版。
* 现在目标分录表名从映射计划取({@link #destEntryTables()}),对任意单据都成立——
* 只要该单据的分录上有 qty / price / amount 三个字段即可复用。</p>
*
* <p>qty / price / amount 是业务语义字段名,仍以常量呈现;若要做到连字段名也可配,
* 需要给 convert_plugin_entry 加一个参数列,当前表没有该列(见设计说明 §7 待确认项)。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/4/22 11:15
*/
public class PurorderTransformPlugIn extends AbstractTransformPlugIn{
public class PurorderTransformPlugIn extends AbstractTransformPlugIn {
private static final String FIELD_QTY = "qty";
private static final String FIELD_PRICE = "price";
private static final String FIELD_AMOUNT = "amount";
@Override
public void afterTransform() {
}
@Override
public void afterFieldMapping() {
ObjectCollection objectCollection =
destBillData.getObjectCollection("pur_order_entry");
for (int i = 0 ; i < objectCollection.size() ; i++){
ObjectValue objectValue = objectCollection.getObject(i);
BigDecimal qty = objectValue.getBigDecimal("qty");
BigDecimal price = objectValue.getBigDecimal("price");
BigDecimal amount = qty.multiply(price);
objectValue.setBigDecimal("amount",amount);
for (String entryTable : destEntryTables()) {
ObjectCollection rows = destBillData.getObjectCollection(entryTable);
if (rows == null) {
continue;
}
for (int i = 0; i < rows.size(); i++) {
ObjectValue row = rows.getObject(i);
BigDecimal qty = row.getBigDecimal(FIELD_QTY);
BigDecimal price = row.getBigDecimal(FIELD_PRICE);
if (qty == null || price == null) {
continue;
}
row.setBigDecimal(FIELD_AMOUNT, qty.multiply(price));
}
}
}
}

207
common/common-botp/src/main/java/apelet/common/botp/plugin/ReverseWritingPlugIn.java

@ -1,198 +1,39 @@ @@ -1,198 +1,39 @@
package apelet.common.botp.plugin;
import apelet.common.core.exception.MyRuntimeException;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.util.ApplicationContextHolder;
import apelet.common.botp.dto.ReverseWritingRulesDto;
import apelet.common.botp.model.ReverseWritingBusiness;
import apelet.common.botp.model.ReverseWritingFormula;
import apelet.common.botp.service.impl.ReverseWritingRulesServiceImpl;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.online.service.impl.OnlineFormServiceImpl;
import apelet.common.online.util.Jexl3Util;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* 采购申请下推采购订单后回写采购申请分录已订货数量
* 已停用的反写插件(保留占位)。
*
* <p><b>为什么保留而不删除</b>:线上 {@code convert_plugin_entry} 里有类名指向本类的存量配置。
* 若直接删类,转换时加载插件会抛 ClassNotFoundException,把本来能跑的下推打断。
* 保留成空实现后:下推照常进行,只是不再由本类做反写。</p>
*
* <p><b>为什么可以空实现</b>:反写已收口到 {@code WriteBackOrchestrator}——
* 保存 / 审核 / 撤销 / 弃审四个入口共用一条流水线,且 autoSave 下推后由
* {@code ConvertOrchestrator} 显式触发,覆盖了原先靠本插件补的那一刀。</p>
*
* <p>原实现的问题(业务规则结果不落库、公式用 Integer.parseInt 且按单号子串匹配行)
* 不再需要在这里修——新引擎已按 BigDecimal + 主键配对重写。</p>
*
* <p><b>运维动作</b>:确认新链路生效后,删除 convert_plugin_entry 中
* {@code class_name = 'apelet.common.botp.plugin.ReverseWritingPlugIn'} 的存量行。</p>
*
* @author Soon
* @version 1.0
* @deprecated 已由 {@code apelet.common.botp.service.execute.WriteBackOrchestrator} 取代。
*/
@Deprecated
@Slf4j
public class ReverseWritingPlugIn extends AbstractTransformPlugIn {
private final ReverseWritingRulesServiceImpl reverseWritingRulesService =
ApplicationContextHolder.getBean(ReverseWritingRulesServiceImpl.class);
private final OnlineFormServiceImpl onlineFormService =
ApplicationContextHolder.getBean(OnlineFormServiceImpl.class);
private final OrmGenDataSourceUtil ormGenDataSourceUtil =
ApplicationContextHolder.getBean(OrmGenDataSourceUtil.class);
private final Jexl3Util Jexl3Util =
ApplicationContextHolder.getBean(Jexl3Util.class);
@Override
public void afterTransform() {
}
/**
* 源单据 srcBillData
* 目标单据 destBillData
*/
@Override
public void afterFieldMapping() {
try {
String destBillType = rule.getDestBillType();
String sourceBillType = rule.getSourceBillType();
List<ReverseWritingRulesDto> rulesList = reverseWritingRulesService.listAll();
List<ReverseWritingRulesDto> collect = rulesList.stream()
.filter(f -> f.getSourceDocuments().toString().equals(sourceBillType) &&
f.getTargetDoc().toString().equals(destBillType) &&
f.getTriggerTiming().equals("1")
)
.collect(Collectors.toList());
collect.forEach(f -> {
// 业务规则
f.getBusinessList().stream().filter(i -> i.getEnable() == 1).forEach(this::a);
// 反写公式 根据目标单据数据 -> 修改原单据
f.getFormulaList().stream().filter(i -> i.getEnable() == 1).forEach(this::b);
});
}catch (Exception e){
throw new MyRuntimeException(e);
}
}
void a(ReverseWritingBusiness b) {
String preconditionsEnglish = b.getPreconditionsEnglish();
JSONObject preconditionsJson = JSON.parseObject(b.getPreconditionsJson());
String preconditionsField = b.getPreconditionsField();
JSONObject jsonObject = JSON.parseObject(preconditionsField);
Map<String, Object> hashMap = Jexl3Util.getMapValue(jsonObject, destBillData);
Object expression = Jexl3Util.expression(preconditionsEnglish, hashMap);
Object func = onlineFormService.func(preconditionsEnglish, preconditionsJson, destBillData);
String established = "";
String establishedField = "";
String establishedJson = "";
if (func instanceof Boolean && func.equals(true)) {
// 成立
established = b.getEstablishedEnglish();
establishedField = b.getEstablishedField();
establishedJson = b.getEstablishedJson();
} else {
// 不成立
established = b.getNotEstablishedEnglish();
establishedField = b.getNotEstablishedField();
establishedJson = b.getNotEstablishedJson();
}
// Map<String, Object> map = Jexl3Util.getMapValue(JSON.parseObject(establishedField), destBillData);
// Jexl3Util.expression(established, map);
// 执行操作
JSONObject json = JSON.parseObject(establishedJson);
String expressionTransl = json.getString("expressionTranslation");
List<String> split = Arrays.asList(expressionTransl.split("="));
String fun = "";
for (String s : split) {
s = s.trim();
if (s.startsWith("$") && s.endsWith("$")) {
fun = s;
}
}
fun = Jexl3Util.getMySplit("\\$(.*?)\\$", fun);
List<String> funParam = Arrays.asList(Jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
Object[] objects = Jexl3Util.getFunParam(funParam, destBillData);
Object o = onlineFormService.executeFunction(json, fun, objects);
// 修改单据
List<String> s = Arrays.asList(split.get(0).split("\\."));
if (s.get(0).equals(s.get(1))) {
// 表头
destBillData.put(s.get(s.size()-1), o);
try {
// ormGenDataSourceUtil.update(destBillData.getTableName(),destBillData,null);
} catch (Exception e) {
throw new MyRuntimeException(e);
}
}else{
// 分录 TODO 待确定
}
}
/**
* 根据目标单据数据 -> 修改原单据
* @param b
*/
void b(ReverseWritingFormula b) {
String conditionEnglish = b.getConditionEnglish(); // 条件
String conditionField = b.getConditionField();
JSONObject conditionJson = JSON.parseObject(b.getConditionJson());
// JSONObject jsonObject = JSON.parseObject(conditionField);
// Map<String, Object> hashMap = Jexl3Util.getMapValue(jsonObject, destBillData);
// Object expression = Jexl3Util.expression(conditionEnglish, hashMap);
Object func = onlineFormService.func(conditionEnglish, conditionJson, srcBillData);
if (Jexl3Util.judgmentFunc(conditionEnglish, func)) {
// 反写公式
String formulaEnglish = b.getFormulaEnglish();
JSONObject formulaJson = JSON.parseObject(b.getFormulaJson());
Object func1 = onlineFormService.func(formulaEnglish, formulaJson, srcBillData);
String formula = b.getFormulaEnglish().replaceAll("\\s", ""); // 公式
String[] formulas = formula.split("\\.");
ObjectCollection o = (ObjectCollection) destBillData.getValues().get(formulas[1]);
Iterator iterator = o.iterator();
while (iterator.hasNext()) {
ObjectValue next = (ObjectValue) iterator.next();
Object destValue = next.getValues().get(formulas[2]) == null ? 0 : next.getValues().get(formulas[2]);
String sourceSingleField = b.getSourceSingleField().replaceAll("\\s", ""); // 源单字段
String[] srcStr = sourceSingleField.split("\\.");
ObjectCollection o1 = (ObjectCollection) srcBillData.getValues().get(srcStr[1]);
Iterator iterator2 = o1.iterator();
while (iterator2.hasNext()) {
ObjectValue next2 = (ObjectValue) iterator2.next();
if (!ObjectUtil.contains(next2.get("number"), next.get("number"))) {
continue;
}
Object srcValue = next2.getValues().get(srcStr[2]) == null ? 0 : next2.getValues().get(srcStr[2]);
String a = "";
switch (b.getMode()) { // 累加方式 1:累加, 2:扣减, 3:覆盖
case "1": {
a = String.valueOf((Integer.parseInt(srcValue.toString()) + Integer.parseInt(destValue.toString())));
break;
}
case "2": {
a = String.valueOf((Integer.parseInt(srcValue.toString()) - Integer.parseInt(destValue.toString())));
break;
}
case "3": {
a = destValue.toString();
break;
}
}
ObjectValue purReqObjV = new ObjectValue(srcStr[1]);
purReqObjV.put("id", next2.get("id"));
purReqObjV.put(srcStr[2], a);
Selector selector = new Selector();
selector.getList().add(new SelectorItem(srcStr[2]));
try {
ormGenDataSourceUtil().update(purReqObjV.getTableName(), purReqObjV, selector);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
log.warn("ReverseWritingPlugIn 已停用:反写已收口到 WriteBackOrchestrator。"
+ "请在 convert_plugin_entry 中删除 class_name = '{}' 的存量转换插件配置。", getClass().getName());
}
}

44
common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugIn.java

@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
package apelet.common.botp.plugin.spi;
/**
* 转换插件扩展点。
*
* <p>插件是「配置化字段映射覆盖不了时的逃生舱」:跨表计算、多字段联动、落库前的数据修正等,
* 用字段映射表达不了的逻辑写在这里。</p>
*
* <p>插件不硬编码在流程里,而是配置在 convert_plugin_entry(type=convert)中,可挂 0~N 个,
* 每个能单独开关、单独排序(按 serialNumber 升序执行)。</p>
*
* <p><b>两个钩子的时序语义不同,选错会不生效:</b></p>
* <ul>
* <li>{@link #afterFieldMapping} —— 字段映射完成、<b>尚未落库</b>。可以改数据,改了会一起落库。</li>
* <li>{@link #afterTransform} —— 转换完成、<b>已落库</b>。只能做副作用(发通知、写日志、调外部系统),
* 此时再改 destBillData 不会写进数据库。</li>
* </ul>
*
* <p><b>插件不可覆盖</b>:条件求值与数值计算内核、精度规则、事务边界、规则的启用/过滤判定。
* 插件是扩展点,不是覆盖点——内核必须唯一,否则每个插件各算一套,口径就散了。</p>
*
* <p>钩子方法均有 default 空实现,插件只实现自己关心的钩子即可。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public interface ConvertPlugIn {
/**
* 目标字段赋值完毕后事件(落库前,可改数据)。
*
* @param context 转换上下文。
*/
default void afterFieldMapping(ConvertPlugInContext context) {
}
/**
* 单据转换后事件(落库后,只做副作用)。
*
* @param context 转换上下文。
*/
default void afterTransform(ConvertPlugInContext context) {
}
}

57
common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugInContext.java

@ -0,0 +1,57 @@ @@ -0,0 +1,57 @@
package apelet.common.botp.plugin.spi;
import apelet.common.botp.plugin.entity.BotpRule;
import apelet.common.botp.service.execute.entity.ConvertMappingPlan;
import apelet.common.core.object.ObjectValue;
import apelet.common.generator.model.OnlFormHead;
import lombok.Data;
/**
* 转换插件上下文。
*
* <p>每次转换生成一份,按钩子传给插件。插件通过它拿到规则信息与单据数据;</p>
*
* <p>元数据({@link OnlFormHead})用于替代原先插件里硬编码的表名/字段名——插件不应再写死
* {@code pur_order_entry}、{@code orderqty} 这类具体单据的表名字段名,而应从规则上下文与元数据推导,
* 这样同一套插件换单据就能复用。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertPlugInContext {
/**
* 转换规则上下文(规则 id / 编码 / 名称 / 源单标识 / 目标单标识)。
*/
private BotpRule rule;
/**
* 源单元数据(表名、字段定义列表)。
*/
private OnlFormHead srcFormHead;
/**
* 目标单元数据(表名、字段定义列表)。
*/
private OnlFormHead destFormHead;
/**
* 源单数据:表头字段平铺,分录为 ObjectCollection。
*/
private ObjectValue srcBillData;
/**
* 目标单数据:表头字段平铺,分录为 ObjectCollection。
*/
private ObjectValue destBillData;
/**
* 本次转换的字段映射计划。
*
* <p>插件取表名/字段名从这里取,不要写死 {@code pur_order_entry}、{@code orderqty} 这类具体单据的
* 表名字段名——写死意味着换单据就得改 Java 重新发版,「任意表单可配置」就不成立了。
* {@code mappingPlan.getDestEntryColumns().keySet()} 即目标单的全部分录表名。</p>
*/
private ConvertMappingPlan mappingPlan;
}

83
common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackContext.java

@ -0,0 +1,83 @@ @@ -0,0 +1,83 @@
package apelet.common.botp.plugin.spi;
import apelet.common.botp.model.ReverseWritingFormula;
import apelet.common.botp.model.ReverseWritingRules;
import apelet.common.core.object.ObjectValue;
import lombok.Data;
import java.math.BigDecimal;
/**
* 反写插件上下文。
*
* <p>反写是一条有严格顺序的流水线(定位关联 → 业务规则 → 逐条公式 → 超额检查 → 写入源单 → 关闭源单行),
* 每次反写生成一份上下文,随流水线推进逐步填充字段,各钩子阶段可读到的内容不同:</p>
*
* <table border="1">
* <caption>各钩子阶段可用的字段</caption>
* <tr><th>钩子</th><th>已填充</th></tr>
* <tr><td>beforeExecWriteBackRule</td><td>rule / srcBillData / destBillData</td></tr>
* <tr><td>afterCalcWriteValue</td><td>+ formula / originalValue / currentValue / newValue</td></tr>
* <tr><td>beforeExcessCheck</td><td>同上</td></tr>
* <tr><td>afterExcessCheck</td><td>+ excess</td></tr>
* <tr><td>afterCommitAmount</td><td>+ committed(是否已实际写入源单)</td></tr>
* </table>
*
* <p>未被填充的字段为 null,插件取用前需自行判空。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class WriteBackContext {
/**
* 当前生效的反写规则(含触发时机、超额动作、源单行关闭条件等)。
*/
private ReverseWritingRules rule;
/**
* 源单数据(反写的写入目标)。
*/
private ObjectValue sourceBillData;
/**
* 目标单数据(触发反写的单据)。
*/
private ObjectValue targetBillData;
/**
* 当前正在执行的公式(逐条执行,执行到哪条就是哪条)。
*/
private ReverseWritingFormula formula;
/**
* 源单字段的反写前原值。
*/
private BigDecimal originalValue;
/**
* 本次写入值(来自目标单)。
*/
private BigDecimal currentValue;
/**
* 按反写方式算出的新值(已按目标字段精度四舍五入)。
*/
private BigDecimal newValue;
/**
* 是否判定为超额;未做超额检查时为 null。
*/
private Boolean excess;
/**
* 新值是否已实际写入源单(事务提交后回调时为 true)。
*/
private Boolean committed;
/**
* 是否为回滚方向(撤销 / 弃审),正向反写为 false。
*/
private boolean rollback;
}

90
common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackPlugIn.java

@ -0,0 +1,90 @@ @@ -0,0 +1,90 @@
package apelet.common.botp.plugin.spi;
/**
* 反写插件扩展点。
*
* <p>反写流水线在关键节点留出 5 个钩子,插件可在这些点插入定制逻辑,但内核始终握着关键部分
* (条件求值、数值计算、精度、超额判定、事务边界)。</p>
*
* <p>流水线与钩子的位置:</p>
*
* <pre>
* 定位关联单据
* ↓
* beforeExecWriteBackRule ← 钩子 1
* ↓
* 业务规则前置条件 → 成立 / 不成立分支
* ↓
* 逐条公式(按 exec_order 升序):条件求值 → 求源单字段值 → BigDecimal 计算
* ↓
* afterCalcWriteValue ← 钩子 2(新值已算出,尚未写入源单)
* ↓
* beforeExcessCheck ← 钩子 3
* ↓
* 超额检查(拦截报错 / 仅告警)
* ↓
* afterExcessCheck ← 钩子 4
* ↓
* 写入源单(按行主键精确匹配)
* ↓
* 源单行关闭条件判定
* ↓
* 事务提交
* ↓
* afterCommitAmount ← 钩子 5(事务提交后回调)
* </pre>
*
* <p>钩子方法均有 default 空实现,插件只实现自己关心的钩子即可。</p>
*
* <p>插件配置在 convert_plugin_entry(type=writeback)中,按 serialNumber 升序执行、按 enable 过滤。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public interface WriteBackPlugIn {
/**
* 反写规则开始执行前。
*
* @param context 反写上下文。
*/
default void beforeExecWriteBackRule(WriteBackContext context) {
}
/**
* 数值算完、尚未做超额检查与写入。
*
* <p>此时可读到 {@code formula}、{@code originalValue}、{@code currentValue}、{@code newValue},
* 但改 {@code newValue} 是否生效由编排器决定——插件不应依赖能改值。</p>
*
* @param context 反写上下文。
*/
default void afterCalcWriteValue(WriteBackContext context) {
}
/**
* 超额检查前。
*
* @param context 反写上下文。
*/
default void beforeExcessCheck(WriteBackContext context) {
}
/**
* 超额检查后,可读到 {@code excess} 判定结果。
*
* @param context 反写上下文。
*/
default void afterExcessCheck(WriteBackContext context) {
}
/**
* 值已写入源单、事务提交后回调。
*
* <p>典型的副作用场景:发通知、写外部系统。此时回滚已不可能。</p>
*
* @param context 反写上下文。
*/
default void afterCommitAmount(WriteBackContext context) {
}
}

31
common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java

@ -1,6 +1,7 @@ @@ -1,6 +1,7 @@
package apelet.common.botp.service;
import apelet.common.botp.model.ConvertPluginEntry;
import apelet.common.botp.model.constant.PluginTypeEnum;
import apelet.common.core.base.service.IBaseService;
import java.util.List;
@ -13,4 +14,34 @@ public interface IConvertPluginEntryService extends IBaseService<ConvertPluginEn @@ -13,4 +14,34 @@ public interface IConvertPluginEntryService extends IBaseService<ConvertPluginEn
List<ConvertPluginEntry> getConvertPluginEntryRelation(Long id);
List<ConvertPluginEntry> getConvertPluginEntryListWithRelation(ConvertPluginEntry convertPluginEntryFilter, String buildOrderBy);
/**
* 查某规则下指定类型的全部插件。
*
* <p>转换插件与反写插件共用 convert_plugin_entry,parentId 分别指向 convert_rule.id 与
* reverse_writing_rules.id —— 两张表主键值域重叠,只能靠 type 区分。
* <b>所有</b>查询/删除都必须走本类的这三个方法,不要各处手写 wrapper,漏一处就会串数据。</p>
*
* @param ruleId 规则 id。
* @param type 插件类型。
* @return 插件分录列表。
*/
List<ConvertPluginEntry> listByRule(Long ruleId, PluginTypeEnum type);
/**
* 查某规则下指定类型且已启用的插件。
*
* @param ruleId 规则 id。
* @param type 插件类型。
* @return 已启用的插件分录列表。
*/
List<ConvertPluginEntry> listEnabledByRule(Long ruleId, PluginTypeEnum type);
/**
* 删除某规则下指定类型的全部插件。
*
* @param ruleId 规则 id。
* @param type 插件类型。
*/
void removeByRule(Long ruleId, PluginTypeEnum type);
}

18
common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java

@ -2,6 +2,8 @@ package apelet.common.botp.service; @@ -2,6 +2,8 @@ package apelet.common.botp.service;
import apelet.common.botp.dto.ConvertRelationDelDto;
import apelet.common.botp.dto.ConvertRelationListDto;
import apelet.common.botp.dto.ConvertRequest;
import apelet.common.botp.dto.ConvertResult;
import apelet.common.botp.dto.RuleVersionDiffDto;
import apelet.common.botp.dto.TransformResultDto;
import apelet.common.botp.model.*;
@ -71,12 +73,25 @@ public interface IConvertRuleService extends IBaseService<ConvertRule,Long> { @@ -71,12 +73,25 @@ public interface IConvertRuleService extends IBaseService<ConvertRule,Long> {
public boolean removeAllRelation(ConvertRelationDelDto dto);
/**
* 执行转换:支持多源单、分单策略、合并取值、按版本执行。
*
* <p>推式(下推)与拉式(选单)共用本入口,差异只在源单 id 从哪来。</p>
*
* @param request 转换请求。
* @return 转换结果,含每个目标单的 id 与单号、实际使用的规则版本。
*/
ConvertResult convert(ConvertRequest request);
/**
* @botpId 转准规则id
* @srcBill 源单据元数据id
* @destBill 目标单据元数据id
* @srcbillId 源单据id
* @return
* @deprecated 兼容老前端:只返回单张目标单。多目标单时只取第一张并记 WARN,
* 请改用 {@link #convert(ConvertRequest)}。
*/
@Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId);
/**
@ -85,7 +100,10 @@ public interface IConvertRuleService extends IBaseService<ConvertRule,Long> { @@ -85,7 +100,10 @@ public interface IConvertRuleService extends IBaseService<ConvertRule,Long> {
* @destBill 目标单据元数据id
* @srcbillId 源单据id集合
* @return
* @deprecated 兼容老前端:只返回单张目标单。多目标单时只取第一张并记 WARN,
* 请改用 {@link #convert(ConvertRequest)}。
*/
@Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, Set<String> srcBillList);

1039
common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java

File diff suppressed because it is too large Load Diff

531
common/common-botp/src/main/java/apelet/common/botp/service/execute/ConvertOrchestrator.java

@ -0,0 +1,531 @@ @@ -0,0 +1,531 @@
package apelet.common.botp.service.execute;
import apelet.common.botp.dao.ConvertFieldmappingEntryMapper;
import apelet.common.botp.dao.ConvertRuleMapper;
import apelet.common.botp.dto.ConvertRequest;
import apelet.common.botp.dto.ConvertResult;
import apelet.common.botp.dto.ConvertedBill;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.ConvertFieldmappingEntry;
import apelet.common.botp.model.ConvertPluginEntry;
import apelet.common.botp.model.ConvertRule;
import apelet.common.botp.model.constant.BotpRuleConstant;
import apelet.common.botp.model.constant.PluginTypeEnum;
import apelet.common.botp.model.constant.SplitMergeStrategyEnum;
import apelet.common.botp.service.IConvertPluginEntryService;
import apelet.common.botp.service.execute.entity.BtpTransformResult;
import apelet.common.botp.service.execute.entity.ConvertBatch;
import apelet.common.botp.service.execute.entity.ResolvedConvertRule;
import apelet.common.botp.util.BillDataConverter;
import apelet.common.botp.util.Constant;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.generator.dao.OnlFormHeadMapper;
import apelet.common.generator.model.OnlFormHead;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.online.model.OnlineColumn;
import apelet.common.online.model.OnlineTable;
import apelet.common.online.model.constant.FieldKind;
import apelet.common.online.rule.condition.ConditionEvaluator;
import apelet.common.online.rule.model.RuleCondition;
import apelet.common.online.rule.model.RuleEvalContext;
import apelet.common.online.service.OnlineColumnService;
import apelet.common.online.service.OnlineTableService;
import apelet.common.orm.impl.Filter;
import apelet.common.orm.impl.FilterItem;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* 转换编排器:推式(下推)与拉式(选单)的共同入口。
*
* <p>编排器管「几张单、什么条件、事务边界」,单张目标单怎么填交给
* {@link BotpService}。两者分层是为了让拉式能复用推式的全部链路,而不是重写一套。</p>
*
* <p>流程:</p>
* <pre>
* ① 解析规则(显式版本取快照,未传入取最新生效版本)
* ② 规则启用条件判定(不满足则本次转换不执行)
* ③ 选单过滤(逐单求值,返回真的源单才参与)
* ④ 分单:按分单策略把源单集合切成批次
* ⑤ 逐批次转换(每批次一张目标单)
* ⑥ 落库 + 写转换关系(同一事务)
* ⑦ autoSave 开启时触发保存时机的反写
* ⑧ 组装结果(每个目标单的 id 与单号 + 实际使用的规则版本)
* </pre>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
@Slf4j
public class ConvertOrchestrator {
@Autowired
private ConvertRuleMapper convertRuleMapper;
@Autowired
private ConvertFieldmappingEntryMapper convertFieldmappingEntryMapper;
@Autowired
private IConvertPluginEntryService convertPluginEntryService;
@Autowired
private OnlFormHeadMapper onlFormHeadMapper;
@Autowired
private OrmGenDataSourceUtil ormGenDataSourceUtil;
@Autowired
private BotpService botpService;
@Autowired
private WriteBackOrchestrator writeBackOrchestrator;
@Autowired
private BillDataConverter billDataConverter;
@Autowired
private RuleVersionResolver ruleVersionResolver;
@Autowired
private ConditionEvaluator conditionEvaluator;
@Autowired
private OnlineTableService onlineTableService;
@Autowired
private OnlineColumnService onlineColumnService;
/**
* 执行转换。
*
* <p>落库与写转换关系在同一事务内,确保反写失败时本次转换一并回滚。</p>
*
* @param request 转换请求。
* @return 转换结果。
*/
@Transactional(rollbackFor = Exception.class)
public ConvertResult transform(ConvertRequest request) {
validateRequest(request);
ResolvedConvertRule resolved = resolveRule(request);
ConvertRule rule = resolved.getRule();
OnlFormHead srcFormHead = onlFormHeadMapper.selectById(rule.getSourceEntityId());
OnlFormHead destFormHead = onlFormHeadMapper.selectById(rule.getTargetEntityId());
if (srcFormHead == null || destFormHead == null) {
throw new BotpMappingException("转换规则的源单或目标单元数据不存在,规则id=" + rule.getId());
}
Set<String> passedIds = filterSourceBills(rule, srcFormHead, resolved.getFieldMappings(), request.getSrcBillIds());
ConvertResult result = new ConvertResult();
result.setUsedRuleVersion(resolved.getVersion());
result.setSourceCount(request.getSrcBillIds().size());
result.setPassedCount(passedIds.size());
result.getFilteredOutIds().addAll(diff(request.getSrcBillIds(), passedIds));
boolean autoSaveOn = isAutoSaveOn(rule);
result.setFormStatus(autoSaveOn ? Constant.FormStatus_AddNew : Constant.FormStatus_Save);
result.setFormType(rule.getDownInterfaceType());
if (passedIds.isEmpty()) {
log.info("选单过滤后无可转换的源单,规则id={},传入={}条", rule.getId(), request.getSrcBillIds().size());
return result;
}
String billNumberColumn = resolveBillNumberColumn(destFormHead.getTableName());
for (ConvertBatch batch : split(rule, passedIds)) {
result.getBills().add(transformBatch(rule, resolved.getFieldMappings(), resolved.getPluginEntries(), srcFormHead, destFormHead, batch, billNumberColumn));
}
if (Constant.InterfaceType_ROUTE.equals(result.getFormType())) {
// 路由表单的页面字段是驼峰,在线表单是下划线,两种形态前端各有一套取值方式
for (ConvertedBill bill : result.getBills()) {
if (bill.getBillData() != null) {
billDataConverter.toCamelCase(bill.getBillData());
}
}
}
if (autoSaveOn) {
triggerSaveWriteBack(result, destFormHead);
}
return result;
}
/**
* 解析规则:显式版本取快照执行,未传入取库中当前数据(即最新生效版本)。
*
* @param request 转换请求。
* @return 解析结果。
*/
private ResolvedConvertRule resolveRule(ConvertRequest request) {
ConvertRule rule = loadRule(request.getRuleId());
if (request.getRuleVersion() != null) {
return ruleVersionResolver.resolveFromSnapshot(rule.getId(), request.getRuleVersion());
}
ResolvedConvertRule resolved = new ResolvedConvertRule();
resolved.setRule(rule);
resolved.setFieldMappings(loadMappings(rule.getId()));
resolved.setPluginEntries(loadConvertPlugins(rule.getId()));
resolved.setVersion(rule.getRuleVersion());
return resolved;
}
/**
* 规则启用条件 + 选单过滤,返回真正参与转换的源单。
*
* <p>两者都用 {@code ConditionEvaluator} 逐单求值,口径与在线规则引擎一致。
* 求值上下文是<b>完整源单</b>(表头 + 映射涉及的源分录),条件里引用分录字段也能取到值。</p>
*
* <p>规则启用条件不满足时抛异常终止本次转换(FR-1.3);选单过滤不满足只剔除该源单(FR-1.4)。</p>
*
* @param rule 转换规则。
* @param srcFormHead 源单元数据。
* @param mappings 字段映射分录,决定加载哪些源分录。
* @param srcBillIds 传入的源单 id。
* @return 通过过滤的源单 id(保持传入顺序)。
*/
private Set<String> filterSourceBills(ConvertRule rule, OnlFormHead srcFormHead, List<ConvertFieldmappingEntry> mappings, Set<String> srcBillIds) {
boolean hasEnableCondition = StringUtils.isNotBlank(rule.getEnableConditionJson());
boolean hasSelectFilter = StringUtils.isNotBlank(rule.getSelectFilterJson());
if (!hasEnableCondition && !hasSelectFilter) {
return srcBillIds;
}
Map<String, ObjectValue> bills = new HashMap<>();
for (ObjectValue bill : botpService.loadSourceBillsForCondition(mappings, srcFormHead, srcBillIds)) {
bills.put(String.valueOf(bill.get("id")), bill);
}
Set<String> passed = new LinkedHashSet<>();
for (String billId : srcBillIds) {
ObjectValue bill = bills.get(billId);
if (bill == null) {
continue;
}
if (hasEnableCondition && !conditionHit(rule.getEnableConditionJson(), bill)) {
// 规则启用条件不满足:本次转换整体不执行
throw new BotpMappingException("规则启用条件不满足,本次转换未执行。规则=" + rule.getName()
+ ",条件=" + rule.getEnableConditionJson());
}
if (hasSelectFilter && !conditionHit(rule.getSelectFilterJson(), bill)) {
continue;
}
passed.add(billId);
}
return passed;
}
/**
* 条件求值。支持两种配置形态:JSON(取 expressionTranslation + functionForm)或裸表达式字符串。
*
* @param conditionJson 条件配置。
* @param objectValue 求值上下文。
* @return 成立返回 true。
*/
private boolean conditionHit(String conditionJson, ObjectValue objectValue) {
RuleCondition condition = new RuleCondition();
String text = conditionJson.trim();
if (text.startsWith("{")) {
JSONObject json = JSON.parseObject(text);
condition.setExpression(json.getString("expressionTranslation"));
condition.setFunctionForm(parseFunctionForm(json.getJSONArray("functionForm")));
} else {
condition.setExpression(text);
}
if (StringUtils.isBlank(condition.getExpression())) {
return true;
}
return conditionEvaluator.evaluate(condition, new RuleEvalContext(objectValue, null));
}
/**
* 解析 functionForm 数组为「函数名 → 函数 id」。
*
* @param array functionForm 数组,可空。
* @return 映射。
*/
private Map<String, Long> parseFunctionForm(JSONArray array) {
Map<String, Long> map = new HashMap<>();
if (array == null) {
return map;
}
for (Object item : array) {
JSONObject json = (JSONObject) item;
for (String key : json.keySet()) {
Long value = json.getLong(key);
if (value != null) {
map.put(key, value);
}
}
}
return map;
}
/**
* 分单:按分单策略把源单集合切成批次。
*
* @param rule 转换规则。
* @param srcBillIds 源单 id 集合。
* @return 批次列表,每个批次生成一张目标单。
*/
private List<ConvertBatch> split(ConvertRule rule, Set<String> srcBillIds) {
SplitMergeStrategyEnum strategy = SplitMergeStrategyEnum.ofNullable(rule.getSplitMergeStrategy());
if (strategy == SplitMergeStrategyEnum.MANY_TO_ONE) {
ConvertBatch all = new ConvertBatch();
srcBillIds.forEach(all::add);
return Collections.singletonList(all);
}
if (strategy == SplitMergeStrategyEnum.GROUP_BY_RULE) {
return splitByGroup(rule, srcBillIds);
}
List<ConvertBatch> batches = new ArrayList<>(srcBillIds.size());
for (String billId : srcBillIds) {
ConvertBatch one = new ConvertBatch(billId);
one.add(billId);
batches.add(one);
}
return batches;
}
/**
* 按分单字段分组:同一分组值的源单进同一批次。
*
* @param rule 转换规则。
* @param srcBillIds 源单 id 集合。
* @return 批次列表。
*/
private List<ConvertBatch> splitByGroup(ConvertRule rule, Set<String> srcBillIds) {
String groupByField = rule.getGroupByField();
if (StringUtils.isBlank(groupByField)) {
// 保存时已校验「策略=3 必须配置分单字段」,这里兜底防止历史脏数据
throw new BotpMappingException("分单策略为「按规则分组合并」但未配置分单字段,规则id=" + rule.getId());
}
String srcTable = resolveSourceTable(rule);
Map<String, String> groupKeys = loadGroupKeys(srcTable, srcBillIds, groupByField);
Map<String, ConvertBatch> grouped = new LinkedHashMap<>();
for (String billId : srcBillIds) {
String groupValue = groupKeys.get(billId);
if (groupValue == null) {
throw new BotpMappingException("源单不存在,表名=" + srcTable + ",id=" + billId);
}
grouped.computeIfAbsent(groupValue, ConvertBatch::new).add(billId);
}
return new ArrayList<>(grouped.values());
}
/**
* 批量取源单的分组字段值。
*
* <p>一次 {@code id in (...)} 查询取回全部源单的分组值,避免逐条 queryOne 的 N 次往返。</p>
*
* @param srcTable 源单表名。
* @param billIds 源单 id 集合。
* @param groupByField 分单字段(列名)。
* @return 源单 id → 分组值;查不到的源单不在结果里。
*/
private Map<String, String> loadGroupKeys(String srcTable, Set<String> billIds, String groupByField) {
Map<String, String> groupKeys = new HashMap<>();
if (billIds == null || billIds.isEmpty()) {
return groupKeys;
}
List<Long> ids = new ArrayList<>(billIds.size());
for (String billId : billIds) {
ids.add(Long.valueOf(billId));
}
Filter filter = new Filter();
filter.add(new FilterItem("id", FilterItem.in, ids));
Selector selector = new Selector();
selector.getList().add(new SelectorItem("id"));
selector.getList().add(new SelectorItem(groupByField));
ObjectCollection rows;
try {
rows = ormGenDataSourceUtil.query(srcTable, filter, selector);
} catch (Exception e) {
throw new BotpMappingException("按分单字段查询源单失败,表名=" + srcTable + ",字段=" + groupByField, e);
}
if (rows == null) {
return groupKeys;
}
for (int i = 0; i < rows.size(); i++) {
ObjectValue row = rows.getObject(i);
Object value = row.get(groupByField);
groupKeys.put(String.valueOf(row.get("id")), value == null ? "" : String.valueOf(value));
}
return groupKeys;
}
/**
* 转换一个批次。
*
* @param rule 转换规则。
* @param mappings 字段映射分录。
* @param plugins 转换插件分录。
* @param srcFormHead 源单元数据。
* @param destFormHead 目标单元数据。
* @param batch 转换批次。
* @param billNumberColumn 目标单的单号列名,可能为空。
* @return 本批次生成的目标单据信息。
*/
private ConvertedBill transformBatch(ConvertRule rule, List<ConvertFieldmappingEntry> mappings, List<ConvertPluginEntry> plugins,
OnlFormHead srcFormHead, OnlFormHead destFormHead, ConvertBatch batch, String billNumberColumn) {
BtpTransformResult rawResult = botpService.transform(rule, mappings, plugins, srcFormHead, destFormHead, batch.getSourceBillIds());
ConvertedBill convertedBill = new ConvertedBill();
if (rawResult.getBillDataList().isEmpty()) {
return convertedBill;
}
ObjectValue target = rawResult.getBillDataList().getObject(0);
convertedBill.setBillId(target.getPkValue());
convertedBill.setBillData(billDataConverter.convert(target));
if (billNumberColumn != null) {
Object number = target.get(billNumberColumn);
convertedBill.setBillNumber(number == null ? null : String.valueOf(number));
}
return convertedBill;
}
/**
* 解析目标单的「单号」列名。
*
* <p>单据号在在线表单里是自动编码字段(fieldKind = AUTO_CODE),据此识别。
* 找不到时返回 null——此时结果里不带单号,前端按 id 打开即可。</p>
*
* @param tableName 目标单表名。
* @return 单号列名,识别不到时为 null。
*/
private String resolveBillNumberColumn(String tableName) {
if (StringUtils.isBlank(tableName)) {
return null;
}
OnlineTable table = onlineTableService.getOne(new LambdaQueryWrapper<OnlineTable>().eq(OnlineTable::getTableName, tableName));
if (table == null) {
return null;
}
List<OnlineColumn> columns = onlineColumnService.list(new LambdaQueryWrapper<OnlineColumn>().eq(OnlineColumn::getTableId, table.getTableId()));
for (OnlineColumn column : columns) {
if (column.getFieldKind() != null && column.getFieldKind() == FieldKind.AUTO_CODE) {
return column.getColumnName();
}
}
return null;
}
/**
* autoSave 落库后触发「保存即反写」。
*
* <p><b>为什么必须在这里补一刀</b>:autoSave 走 {@code ormGenDataSourceUtil.addNew} 直接落库,
* 绕过了在线表单的保存操作链,保存插件不会被触发,反写就丢了。这也是原先把
* ReverseWritingPlugIn 配成「转换插件」挂在转换流程里的原因。</p>
*
* <p>与反写编排器共事务:反写失败会连同本次转换一起回滚(FR-4.4 / FR-6.7)。</p>
*
* @param result 转换结果。
* @param destFormHead 目标单元数据。
*/
private void triggerSaveWriteBack(ConvertResult result, OnlFormHead destFormHead) {
String tableName = destFormHead.getTableName();
for (ConvertedBill bill : result.getBills()) {
if (bill.getBillId() == null) {
continue;
}
writeBackOrchestrator.execute(BotpWriteBackRequest.of(tableName, bill.getBillId(), BotpWriteBackRequest.TIMING_SAVE));
}
}
/**
* autoSave 判定口径统一:{@code "1"} 与 {@code "true"} 均视为开,空值与其它值视为关。
*
* <p>原实现两处不一致——BotpService 判 {@code "true"}、ConvertRuleServiceImpl 判 {@code "1"},
* 同一配置在不同路径下行为不同;且对可能为 null 的值直接调 equals 会 NPE。这里统一且空安全。</p>
*
* @param rule 转换规则。
* @return 开启返回 true。
*/
private boolean isAutoSaveOn(ConvertRule rule) {
String autoSave = rule.getAutoSave();
return BotpRuleConstant.SWITCH_ON_NUMERIC_VALUE.equals(autoSave) || BotpRuleConstant.SWITCH_ON_VALUE.equals(autoSave);
}
/**
* 解析源单表名,优先取规则上冗余的 sourceTable,缺失时回查元数据。
*
* @param rule 转换规则。
* @return 源单表名。
*/
private String resolveSourceTable(ConvertRule rule) {
if (StringUtils.isNotBlank(rule.getSourceTable())) {
return rule.getSourceTable();
}
OnlFormHead head = onlFormHeadMapper.selectById(rule.getSourceEntityId());
if (head == null) {
throw new BotpMappingException("转换规则的源单元数据不存在,sourceEntityId=" + rule.getSourceEntityId());
}
return head.getTableName();
}
/**
* 加载转换规则。
*
* @param ruleId 规则 id。
* @return 规则。
*/
private ConvertRule loadRule(String ruleId) {
ConvertRule rule = convertRuleMapper.selectById(ruleId);
if (rule == null) {
throw new BotpMappingException("转换规则不存在,id=" + ruleId);
}
return rule;
}
/**
* 加载字段映射分录。
*
* @param ruleId 规则 id。
* @return 映射分录列表。
*/
private List<ConvertFieldmappingEntry> loadMappings(Long ruleId) {
return convertFieldmappingEntryMapper.selectList(new LambdaQueryWrapper<ConvertFieldmappingEntry>()
.eq(ConvertFieldmappingEntry::getParentId, ruleId));
}
/**
* 加载已启用的转换插件分录。
*
* <p>插件表与反写插件共用(靠 type 区分),这里只取 type=convert 的行。</p>
*
* <p><b>⚠️ 上线前置</b>:存量转换插件的 type 是 NULL,必须先执行回填
* ({@code UPDATE convert_plugin_entry SET type = 'convert' WHERE type IS NULL OR type = ''}),
* 否则一加上本条件,现有插件就全查不到了。</p>
*
* @param ruleId 规则 id。
* @return 已启用的插件分录列表。
*/
private List<ConvertPluginEntry> loadConvertPlugins(Long ruleId) {
return convertPluginEntryService.listEnabledByRule(ruleId, PluginTypeEnum.CONVERT);
}
/**
* 求差集。
*
* @param all 全集。
* @param subset 子集。
* @return 差集(保持 all 的顺序)。
*/
private List<String> diff(Set<String> all, Set<String> subset) {
List<String> result = new ArrayList<>();
for (String item : all) {
if (!subset.contains(item)) {
result.add(item);
}
}
return result;
}
/**
* 校验请求入参。
*
* @param request 转换请求。
*/
private void validateRequest(ConvertRequest request) {
if (request == null || StringUtils.isBlank(request.getRuleId())) {
throw new BotpMappingException("转换规则 id 不能为空");
}
if (request.getSrcBillIds() == null || request.getSrcBillIds().isEmpty()) {
throw new BotpMappingException("源单 id 不能为空");
}
}
}

96
common/common-botp/src/main/java/apelet/common/botp/service/execute/RuleVersionResolver.java

@ -0,0 +1,96 @@ @@ -0,0 +1,96 @@
package apelet.common.botp.service.execute;
import apelet.common.botp.dao.ConvertRuleVerMapper;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.ConvertFieldmappingEntry;
import apelet.common.botp.model.ConvertPluginEntry;
import apelet.common.botp.model.ConvertRule;
import apelet.common.botp.model.ConvertRuleVer;
import apelet.common.botp.service.execute.entity.ResolvedConvertRule;
import apelet.common.botp.util.RuleSnapshotUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 规则版本解析:显式传入版本号时取该版本快照,未传入时取最新生效版本。
*
* <p>快照由配置侧在每次保存时落库(convert_rule_ver / reverse_writing_rules_ver),
* 结构见 {@link RuleSnapshotUtil}。执行侧只负责读。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
@Slf4j
public class RuleVersionResolver {
@Autowired
private ConvertRuleVerMapper convertRuleVerMapper;
/**
* 从快照中还原一份转换规则。
*
* @param ruleId 转换规则 id。
* @param version 版本号;为空时取最新版本。
* @return 解析结果。
*/
public ResolvedConvertRule resolveFromSnapshot(Long ruleId, Integer version) {
ConvertRuleVer snapshot = querySnapshot(ruleId, version);
JSONObject json = JSON.parseObject(snapshot.getSnapshotJson());
ResolvedConvertRule resolved = new ResolvedConvertRule();
resolved.setRule(JSON.parseObject(json.getString(RuleSnapshotUtil.SECTION_RULE), ConvertRule.class));
resolved.setFieldMappings(parseList(json.getJSONArray(RuleSnapshotUtil.SECTION_FIELD_MAPPINGS), ConvertFieldmappingEntry.class));
resolved.setPluginEntries(parseList(json.getJSONArray(RuleSnapshotUtil.SECTION_PLUGIN_ENTRIES), ConvertPluginEntry.class));
resolved.setVersion(snapshot.getRuleVersion());
if (resolved.getRule() == null) {
throw new BotpMappingException("规则快照内容不完整,缺少 rule 分区。规则id=" + ruleId + ",版本=" + snapshot.getRuleVersion());
}
return resolved;
}
/**
* 查版本快照。
*
* @param ruleId 转换规则 id。
* @param version 版本号;为空时取最新版本。
* @return 快照记录。
*/
private ConvertRuleVer querySnapshot(Long ruleId, Integer version) {
List<ConvertRuleVer> list;
if (version == null) {
list = convertRuleVerMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ConvertRuleVer>()
.eq(ConvertRuleVer::getRuleId, ruleId)
.orderByDesc(ConvertRuleVer::getRuleVersion)
.last("LIMIT 1"));
} else {
list = convertRuleVerMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ConvertRuleVer>()
.eq(ConvertRuleVer::getRuleId, ruleId)
.eq(ConvertRuleVer::getRuleVersion, version));
}
if (list == null || list.isEmpty()) {
throw new BotpMappingException("转换规则快照不存在,规则id=" + ruleId + ",版本=" + version);
}
return list.get(0);
}
/**
* 解析快照里的子表分区。
*
* @param array 分区数组,可为空。
* @param clazz 目标类型。
* @param <T> 类型。
* @return 列表,不会返回 null。
*/
private <T> List<T> parseList(JSONArray array, Class<T> clazz) {
if (array == null) {
return java.util.Collections.emptyList();
}
return array.toJavaList(clazz);
}
}

814
common/common-botp/src/main/java/apelet/common/botp/service/execute/WriteBackOrchestrator.java

@ -0,0 +1,814 @@ @@ -0,0 +1,814 @@
package apelet.common.botp.service.execute;
import apelet.common.botp.dao.ConvertRelationEntryMapper;
import apelet.common.botp.dao.ConvertRelationMapper;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.*;
import apelet.common.botp.model.constant.BotpRuleConstant;
import apelet.common.botp.model.constant.ExcessActionEnum;
import apelet.common.botp.model.constant.PluginTypeEnum;
import apelet.common.botp.model.constant.ReverseWriteModeEnum;
import apelet.common.botp.model.constant.WriteBackHookEnum;
import apelet.common.botp.plugin.BotpPlugInLoader;
import apelet.common.botp.plugin.spi.WriteBackContext;
import apelet.common.botp.plugin.spi.WriteBackPlugIn;
import apelet.common.botp.service.IConvertPluginEntryService;
import apelet.common.botp.service.IReverseWritingBusinessService;
import apelet.common.botp.service.IReverseWritingFormulaService;
import apelet.common.botp.service.IReverseWritingRulesService;
import apelet.common.botp.util.RuleValueCalculator;
import apelet.common.core.botp.BotpReverseWriteFacade;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.generator.model.OnlFormField;
import apelet.common.generator.model.OnlFormHead;
import apelet.common.generator.service.IOnlFormHeadService;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.online.rule.condition.ConditionEvaluator;
import apelet.common.online.rule.condition.FunctionExecutor;
import apelet.common.online.rule.model.RuleCondition;
import apelet.common.online.rule.model.RuleEvalContext;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.math.BigDecimal;
import java.util.*;
/**
* 反写编排器:保存 / 审核 / 撤销 / 弃审四个入口共用的唯一实现。
*
* <p>四个触发插件只负责「什么时候触发」,反写逻辑全部收敛在这里,只此一份。</p>
*
* <p>原状是两套并行实现(common-botp 的 ReverseWritingPlugIn 挂在转换插件位上、
* common-online 的 SaveOperationServicePlugIn 里整块被注释掉),加上审核/撤销/弃审三个残桩。</p>
*
* <p>流水线见 {@link #executeRule}。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
@Slf4j
public class WriteBackOrchestrator implements BotpReverseWriteFacade {
/**
* 源单字段精度取不到时的默认小数位数。
*
* <p>实际精度由 {@link #resolveScale} 从 onl_form_field.field_point 取,取不到才用本值。</p>
*/
private static final int DEFAULT_SCALE = RuleValueCalculator.DEFAULT_SCALE;
@Autowired
private IReverseWritingRulesService reverseWritingRulesService;
@Autowired
private IReverseWritingFormulaService reverseWritingFormulaService;
@Autowired
private IReverseWritingBusinessService reverseWritingBusinessService;
@Autowired
private IConvertPluginEntryService convertPluginEntryService;
@Autowired
private ConvertRelationMapper convertRelationMapper;
@Autowired
private ConvertRelationEntryMapper convertRelationEntryMapper;
@Autowired
private IOnlFormHeadService onlFormHeadService;
@Autowired
private OrmGenDataSourceUtil ormGenDataSourceUtil;
@Autowired
private BotpPlugInLoader plugInLoader;
@Autowired
private ConditionEvaluator conditionEvaluator;
@Autowired
private FunctionExecutor functionExecutor;
/**
* 执行反写。正向(保存 / 审核)与回滚(撤销 / 弃审)共用本入口。
*
* @param request 反写触发请求。
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void execute(BotpWriteBackRequest request) {
validate(request);
OnlFormHead targetHead = resolveHead(request.getTargetTableName());
List<ReverseWritingRules> rules = loadApplicableRules(targetHead, request);
if (rules.isEmpty()) {
log.debug("未匹配到反写规则,跳过。目标单={},触发时机={}", request.getTargetTableName(), request.getTriggerTiming());
return;
}
ObjectValue targetBill = loadTargetBill(request);
for (ReverseWritingRules rule : rules) {
if (request.isRollback() && !isRollbackEnabled(rule)) {
log.info("反写规则的撤销回滚已关闭,仅改单据状态、不回写。规则id={},规则={}", rule.getId(), rule.getName());
continue;
}
executeRule(rule, targetBill, targetHead, request);
}
}
/**
* 判断规则的撤销回滚开关是否打开。
*
* <p>未配置按开启处理(与列默认值一致)。</p>
*
* @param rule 反写规则。
* @return 开启返回 true。
*/
private boolean isRollbackEnabled(ReverseWritingRules rule) {
return rule.getRollbackOnRevoke() == null || rule.getRollbackOnRevoke() == 1;
}
/**
* 执行一条反写规则。
*
* <pre>
* ① 沿 convert_relation_entry 定位「目标分录行 ↔ 源分录行」的逐对关系
* ② 插件 beforeExecWriteBackRule
* ③ 业务规则三分支(前置条件 → 成立 / 不成立,各自实际写入)
* ④ 逐条公式(exec_order 升序):条件 → 取值 → BigDecimal 计算 → 超额检查 → 写入源单
* ⑤ 源单行关闭条件判定
* ⑥ 插件 afterCommitAmount(事务提交后回调)
* </pre>
*
* @param rule 反写规则。
* @param targetBill 目标单数据。
* @param targetHead 目标单元数据。
* @param request 反写触发请求。
*/
private void executeRule(ReverseWritingRules rule, ObjectValue targetBill, OnlFormHead targetHead, BotpWriteBackRequest request) {
List<ConvertRelation> relations = locateRelations(targetHead, request);
List<ConvertRelationEntry> entries = relations.isEmpty() ? Collections.emptyList() : loadRelationEntries(relations);
if (entries.isEmpty()) {
// 关系记录缺失时回退读单据上的 srcbillid / srcbillentryid(迁移期兼容)
entries = fallbackBySrcBillId(targetBill);
}
if (entries.isEmpty()) {
// 找不到关联关系记 WARN 跳过,不抛异常——历史数据可能本就没有关联记录
log.warn("反写找不到关联关系,跳过。规则id={},目标单={},单据id={}",
rule.getId(), request.getTargetTableName(), request.getTargetBillId());
return;
}
List<WriteBackPlugIn> plugins = loadPlugins(rule.getId());
WriteBackContext context = buildContext(rule, targetBill, request.isRollback());
invoke(plugins, context, WriteBackHookEnum.BEFORE_RULE);
execBusinessRules(rule, entries, context);
execFormulas(rule, entries, context);
closeSourceRows(rule, entries, context);
registerAfterCommit(plugins, context);
}
/**
* 迁移期回退:从单据上的 {@code srcbillid} / {@code srcbillentryid} 字段推导关联关系。
*
* <p>{@code srcbillid} 是下游单据上的普通在线表单字段,值是用户填的——能改、能清空、能填错,
* 所以新链路改用系统写入的 convert_relation。本分支只为存量数据兜底,
* <b>一次性切换完成后下线</b>。</p>
*
* @param targetBill 目标单数据。
* @return 推导出的关联关系;推不出来时为空列表。
*/
private List<ConvertRelationEntry> fallbackBySrcBillId(ObjectValue targetBill) {
List<ConvertRelationEntry> pairs = new ArrayList<>();
Iterator<?> keys = targetBill.getValues().keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
Object value = targetBill.getValues().get(key);
if (!(value instanceof ObjectCollection)) {
continue;
}
ObjectCollection rows = (ObjectCollection) value;
for (int i = 0; i < rows.size(); i++) {
ObjectValue row = rows.getObject(i);
Long sourceEntryId = row.getLong(BotpRuleConstant.COLUMN_SRC_ENTRY_ID);
if (sourceEntryId == null) {
continue;
}
ConvertRelationEntry pair = new ConvertRelationEntry();
pair.setTargeEntryNumber(key);
pair.setTargeEntryId(String.valueOf(row.get("id")));
pair.setSourceEntryId(String.valueOf(sourceEntryId));
pairs.add(pair);
}
}
if (!pairs.isEmpty()) {
log.info("反写走了 srcbillid 回退分支(convert_relation 无记录),共 {} 对。建议核对转换关系数据。", pairs.size());
}
return pairs;
}
/**
* 执行业务规则分录:前置条件求值后走「成立」或「不成立」分支,两者都要实际写入并持久化。
*
* <p>前置条件为空时按「成立」分支处理。</p>
*
* <p>分支表达式形如 {@code 源单表.源单表.字段 = $fun$(参数)} 或 {@code 源单表.字段 = '常量'}:
* 等号左边是回写位置(源单),右边是取值(函数 / 字段引用 / 字面量)。</p>
*
* @param rule 反写规则。
* @param entries 关联关系。
* @param context 反写上下文。
*/
private void execBusinessRules(ReverseWritingRules rule, List<ConvertRelationEntry> entries, WriteBackContext context) {
List<ReverseWritingBusiness> businesses = reverseWritingBusinessService.list(new LambdaQueryWrapper<ReverseWritingBusiness>()
.eq(ReverseWritingBusiness::getEnable, 1)
.eq(ReverseWritingBusiness::getRulesId, rule.getId()));
for (ReverseWritingBusiness business : businesses) {
boolean hit = business.getPreconditionsEnglish() == null
|| conditionHit(business.getPreconditionsEnglish(), business.getPreconditionsJson(), context.getTargetBillData());
String expression = hit ? business.getEstablishedEnglish() : business.getNotEstablishedEnglish();
String expressionJson = hit ? business.getEstablishedJson() : business.getNotEstablishedJson();
if (StringUtils.isBlank(expression)) {
continue;
}
applyBusinessExpression(expression, expressionJson, entries, context);
}
}
/**
* 执行一条业务规则表达式:解析「位置 = 取值」并写入源单。
*
* @param expression 表达式,形如 {@code 源单.分录.字段 = $fun$(...)}。
* @param json 表达式的函数映射,可空。
* @param entries 关联关系。
* @param context 反写上下文。
*/
private void applyBusinessExpression(String expression, String json, List<ConvertRelationEntry> entries, WriteBackContext context) {
String[] split = expression.split("=");
if (split.length < 2) {
log.warn("业务规则表达式缺少等号,跳过。表达式={}", expression);
return;
}
String[] targetRef = splitRef(split[0]);
if (targetRef == null) {
log.warn("业务规则回写位置不合法,跳过。表达式={}", expression);
return;
}
JSONObject expressionJson = StringUtils.isBlank(json) ? null : JSON.parseObject(json);
Object value = evaluateExpressionValue(split[1].trim(), expressionJson, context.getTargetBillData());
if (value == null) {
return;
}
for (ConvertRelationEntry entry : entries) {
writeSourceRow(targetRef[0], entry.getSourceEntryId(), targetRef[1], value);
}
}
/**
* 逐条执行反写公式,按 exec_order 升序。
*
* @param rule 反写规则。
* @param entries 关联关系。
* @param context 反写上下文。
*/
private void execFormulas(ReverseWritingRules rule, List<ConvertRelationEntry> entries, WriteBackContext context) {
List<ReverseWritingFormula> formulas = reverseWritingFormulaService.list(new LambdaQueryWrapper<ReverseWritingFormula>()
.eq(ReverseWritingFormula::getEnable, 1)
.eq(ReverseWritingFormula::getRulesId, rule.getId())
.orderByAsc(ReverseWritingFormula::getExecOrder));
for (ReverseWritingFormula formula : formulas) {
context.setFormula(formula);
if (!conditionHit(formula.getConditionEnglish(), formula.getConditionJson(), context.getTargetBillData())) {
continue;
}
applyFormula(formula, entries, context);
}
}
/**
* 执行一条反写公式。
*
* <p>逐对处理关联关系:目标分录行的值作为「本次值」,源分录行的值作为「原值」,
* 按反写方式计算后写回源单。行匹配完全由 convert_relation_entry 的主键配对决定,
* 不再用字段值的子串匹配(原先 {@code "1"} 会命中 {@code "10"})。</p>
*
* @param formula 反写公式。
* @param entries 关联关系。
* @param context 反写上下文。
*/
private void applyFormula(ReverseWritingFormula formula, List<ConvertRelationEntry> entries, WriteBackContext context) {
ReverseWriteModeEnum mode = ReverseWriteModeEnum.ofNullable(formula.getMode());
String[] targetRef = splitRef(formula.getFormulaEnglish());
String[] sourceRef = splitRef(formula.getSourceSingleField());
if (targetRef == null || sourceRef == null) {
throw new BotpMappingException("反写公式配置不完整,公式=" + formula.getFormulaEnglish()
+ ",源单字段=" + formula.getSourceSingleField());
}
List<WriteBackPlugIn> plugins = loadPlugins(context.getRule().getId());
int scale = resolveScale(sourceRef[0], sourceRef[1]);
for (ConvertRelationEntry entry : entries) {
ObjectValue targetRow = queryRow(targetRef[0], entry.getTargeEntryId());
ObjectValue sourceRow = queryRow(sourceRef[0], entry.getSourceEntryId());
if (targetRow == null || sourceRow == null) {
log.warn("反写跳过:关联的分录行已不存在。目标分录id={},源分录id={}", entry.getTargeEntryId(), entry.getSourceEntryId());
continue;
}
BigDecimal current = toBigDecimal(targetRow.get(targetRef[1]));
BigDecimal original = toBigDecimal(sourceRow.get(sourceRef[1]));
context.setOriginalValue(original);
context.setCurrentValue(current);
BigDecimal newValue = context.isRollback()
? RuleValueCalculator.revert(original, current, mode, entry.getBeforeValue(), scale)
: RuleValueCalculator.apply(original, current, mode, scale);
if (newValue == null) {
log.warn("覆盖方式缺少反写前原值,无法回滚,跳过。源分录id={}", entry.getSourceEntryId());
continue;
}
context.setNewValue(newValue);
context.setCommitted(false);
invoke(plugins, context, WriteBackHookEnum.AFTER_CALC);
invoke(plugins, context, WriteBackHookEnum.BEFORE_EXCESS);
context.setExcess(excessHit(context));
invoke(plugins, context, WriteBackHookEnum.AFTER_EXCESS);
if (Boolean.TRUE.equals(context.getExcess()) && ExcessActionEnum.ofNullable(context.getRule().getExcessAction()) == ExcessActionEnum.REJECT) {
throw new BotpMappingException("反写超额,操作已取消。规则=" + context.getRule().getName()
+ ",源分录id=" + entry.getSourceEntryId()
+ ",原值=" + original + ",本次值=" + current + ",计算后=" + newValue);
}
writeSourceRow(sourceRef[0], entry.getSourceEntryId(), sourceRef[1], newValue);
if (!context.isRollback() && mode == ReverseWriteModeEnum.OVERWRITE) {
recordBeforeValue(entry, original);
}
context.setCommitted(true);
}
}
/**
* 超额检查:对「本次写入后的值」求值,为真即判定超额。
*
* @param context 反写上下文(已填 newValue)。
* @return 超额返回 true;未配置检查公式时返回 false。
*/
private boolean excessHit(WriteBackContext context) {
String expression = context.getRule().getExcessCheckJson();
if (StringUtils.isBlank(expression)) {
return false;
}
return conditionHit(expression, null, context.getTargetBillData());
}
/**
* 源单行关闭:关闭标记始终反映「当前是否满足关闭条件」。
*
* <p><b>按源分录行逐行求值</b>,不是拿表头求值再一刀切——「已下推数量 &gt;= 数量」这类条件
* 引用的是分录行上的字段,用表头求值永远取不到值。</p>
*
* <p><b>条件成立写 1,不成立写 0</b>:撤销 / 弃审把数量退回来之后条件不再成立,
* 这里会把标记清掉、解除关闭(PRD §6.3 ④)。只写 1 不写 0 的话,被关掉的行永远关着。</p>
*
* <p>条件里的字段引用建议写成 {@code 分录表.分录表.字段} 形式(如
* {@code pur_apply_entry.pur_apply_entry.orderqty &gt;= pur_apply_entry.pur_apply_entry.qty}),
* 这样在行上下文里能直接解析。</p>
*
* @param rule 反写规则。
* @param entries 关联关系。
* @param context 反写上下文。
*/
private void closeSourceRows(ReverseWritingRules rule, List<ConvertRelationEntry> entries, WriteBackContext context) {
String expression = rule.getSourceCloseJson();
if (StringUtils.isBlank(expression)) {
return;
}
for (ConvertRelationEntry entry : entries) {
String table = entry.getSourceEntryNumber();
if (StringUtils.isBlank(table)) {
// 走了 srcbillid 回退分支时拿不到源分录表名,无法安全写回,跳过
log.warn("源分录表名缺失(可能走了 srcbillid 回退分支),跳过源单行关闭。规则id={}", rule.getId());
return;
}
ObjectValue sourceRow = queryRow(table, entry.getSourceEntryId());
if (sourceRow == null) {
continue;
}
// 关闭标记始终反映「当前是否满足关闭条件」:正向推满时置 1,
// 撤销/弃审把数量退回来之后条件不再成立,这里会写回 0 解除关闭(PRD §6.3 ④)。
boolean shouldClose = conditionHit(expression, null, sourceRow);
writeSourceRow(table, entry.getSourceEntryId(), BotpRuleConstant.COLUMN_CLOSED_FLAG, shouldClose ? 1 : 0);
}
}
/**
* 取源单字段的精度(小数位数)。
*
* <p>从元数据 onl_form_field.field_point 取;字段存在但未配小数位时按 0(整型)处理,
* 找不到字段时退回默认值。</p>
*
* @param table 源单表名。
* @param column 源单列名。
* @return 小数位数。
*/
private int resolveScale(String table, String column) {
if (StringUtils.isBlank(table) || StringUtils.isBlank(column)) {
return DEFAULT_SCALE;
}
OnlFormHead head = onlFormHeadService.getHeadTableNameCache(table);
List<OnlFormField> fields = head == null ? null : head.getOnlFormFieldList();
if (fields == null) {
return DEFAULT_SCALE;
}
for (OnlFormField field : fields) {
if (column.equals(field.getFieldName())) {
return field.getFieldPoint() == null ? 0 : field.getFieldPoint();
}
}
return DEFAULT_SCALE;
}
/**
* 覆盖方式记原值:把反写前的源单字段值写进关联关系,撤销时读出来恢复。
*
* @param entry 关联关系。
* @param beforeValue 反写前的原值。
*/
private void recordBeforeValue(ConvertRelationEntry entry, BigDecimal beforeValue) {
ConvertRelationEntry update = new ConvertRelationEntry();
update.setId(entry.getId());
update.setBeforeValue(beforeValue);
convertRelationEntryMapper.updateById(update);
entry.setBeforeValue(beforeValue);
}
/**
* 条件求值,统一走在线规则引擎的 ConditionEvaluator。
*
* @param expression 表达式。
* @param json 函数映射 JSON,可空。
* @param objectValue 求值上下文。
* @return 成立返回 true;表达式为空时返回 true。
*/
private boolean conditionHit(String expression, String json, ObjectValue objectValue) {
if (StringUtils.isBlank(expression)) {
return true;
}
if (objectValue == null) {
return false;
}
RuleCondition condition = new RuleCondition();
condition.setExpression(expression);
condition.setFunctionForm(toFunctionForm(json));
return conditionEvaluator.evaluate(condition, new RuleEvalContext(objectValue, null));
}
/**
* 求表达式右侧的取值:$fun$ 走函数执行、字段引用走目标单、其余按字面量。
*
* @param src 右侧表达式。
* @param json 函数映射。
* @param targetBill 目标单数据。
* @return 取值。
*/
private Object evaluateExpressionValue(String src, JSONObject json, ObjectValue targetBill) {
if (StringUtils.isBlank(src)) {
return null;
}
String expression = src.trim();
if (expression.contains("$")) {
// $fun$(参数) 形式:交给 FunctionExecutor 解析参数并动态编译执行
return functionExecutor.execute(toFunctionForm(json), expression, targetBill);
}
String literal = expression;
if (literal.length() >= 2
&& ((literal.startsWith("'") && literal.endsWith("'")) || (literal.startsWith("\"") && literal.endsWith("\"")))) {
return literal.substring(1, literal.length() - 1);
}
String[] ref = splitRef(literal);
if (ref == null || targetBill == null) {
return literal;
}
ObjectValue row = queryRow(ref[0], String.valueOf(targetBill.get("id")));
return row == null ? literal : row.get(ref[1]);
}
/**
* 解析 {@code 表.表.字段} / {@code 表.分录.字段} / {@code 表.字段} 形式的引用。
*
* @param ref 引用串。
* @return {@code [表名, 列名]};不合法时返回 null。
*/
private String[] splitRef(String ref) {
if (StringUtils.isBlank(ref)) {
return null;
}
String[] parts = ref.replaceAll("\\s", "").split("\\.");
if (parts.length < 2) {
return null;
}
return new String[]{parts[parts.length - 2], parts[parts.length - 1]};
}
/**
* 按主键查一行数据。
*
* @param table 表名。
* @param id 主键。
* @return 数据行;不存在时返回 null。
*/
private ObjectValue queryRow(String table, String id) {
if (StringUtils.isBlank(table) || StringUtils.isBlank(id)) {
return null;
}
try {
return ormGenDataSourceUtil.queryOne(table, Long.valueOf(id));
} catch (Exception e) {
log.warn("反写查询分录行失败,表名={},id={},原因={}", table, id, e.getMessage());
return null;
}
}
/**
* 写回源单的某个字段。
*
* @param table 表名。
* @param id 行 id。
* @param column 列名。
* @param value 值。
*/
private void writeSourceRow(String table, String id, String column, Object value) {
if (StringUtils.isBlank(table) || StringUtils.isBlank(id) || StringUtils.isBlank(column)) {
return;
}
ObjectValue update = new ObjectValue(table);
update.put("id", Long.valueOf(id));
update.put(column, value);
Selector selector = new Selector();
selector.getList().add(new SelectorItem(column));
try {
ormGenDataSourceUtil.update(table, update, selector);
} catch (Exception e) {
throw new BotpMappingException("反写源单失败,表名=" + table + ",id=" + id + ",列=" + column, e);
}
}
/**
* 加载规则下已启用的反写插件。
*
* <p>插件表与转换插件共用(靠 type 区分),这里只取 type=writeback 的行,
* 避免把转换插件误当成反写插件执行。</p>
*
* @param ruleId 反写规则 id。
* @return 插件实例列表(按 serialNumber 升序)。
*/
private List<WriteBackPlugIn> loadPlugins(Long ruleId) {
List<ConvertPluginEntry> entries = convertPluginEntryService.listEnabledByRule(ruleId, PluginTypeEnum.WRITE_BACK);
if (entries.isEmpty()) {
return Collections.emptyList();
}
entries.sort((a, b) -> Integer.compare(parseOrder(a.getSerialNumber()), parseOrder(b.getSerialNumber())));
List<WriteBackPlugIn> plugins = new ArrayList<>(entries.size());
for (ConvertPluginEntry entry : entries) {
plugins.add(plugInLoader.load(entry.getClassName(), WriteBackPlugIn.class));
}
return plugins;
}
/**
* 触发插件钩子。
*
* @param plugins 插件实例。
* @param context 反写上下文。
* @param hook 钩子。
*/
private void invoke(List<WriteBackPlugIn> plugins, WriteBackContext context, WriteBackHookEnum hook) {
for (WriteBackPlugIn plugin : plugins) {
switch (hook) {
case BEFORE_RULE:
plugin.beforeExecWriteBackRule(context);
break;
case AFTER_CALC:
plugin.afterCalcWriteValue(context);
break;
case BEFORE_EXCESS:
plugin.beforeExcessCheck(context);
break;
case AFTER_EXCESS:
plugin.afterExcessCheck(context);
break;
case AFTER_COMMIT:
plugin.afterCommitAmount(context);
break;
default:
break;
}
}
}
/**
* 注册事务提交后回调,触发 afterCommitAmount。
*
* @param plugins 插件实例。
* @param context 反写上下文。
*/
private void registerAfterCommit(List<WriteBackPlugIn> plugins, WriteBackContext context) {
if (plugins.isEmpty() || !TransactionSynchronizationManager.isSynchronizationActive()) {
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
invoke(plugins, context, WriteBackHookEnum.AFTER_COMMIT);
}
});
}
/**
* 组装反写上下文。
*
* @param rule 反写规则。
* @param targetBill 目标单数据。
* @param rollback 是否回滚方向。
* @return 上下文。
*/
private WriteBackContext buildContext(ReverseWritingRules rule, ObjectValue targetBill, boolean rollback) {
WriteBackContext context = new WriteBackContext();
context.setRule(rule);
context.setTargetBillData(targetBill);
context.setRollback(rollback);
return context;
}
/**
* 定位目标单对应的单据级关联关系。
*
* <p><b>只按「目标单标识 + 目标单 id」定位,不带 convertRuleId 条件</b>:convert_relation.convert_rule_id
* 存的是<b>转换规则</b>(convert_rule.id),与反写规则不是同一张表、id 不同源,拿反写规则 id 去比会一条都查不到。</p>
*
* <p>关系记录缺失时由 {@link #fallbackBySrcBillId} 回退读 {@code srcbillid} / {@code srcbillentryid}。
* 一次性切换完成后该回退分支下线。</p>
*
* @param targetHead 目标单元数据。
* @param request 反写触发请求。
* @return 关联关系列表,找不到时为空列表。
*/
private List<ConvertRelation> locateRelations(OnlFormHead targetHead, BotpWriteBackRequest request) {
return convertRelationMapper.selectList(new LambdaQueryWrapper<ConvertRelation>()
.eq(ConvertRelation::getTargetNumber, String.valueOf(targetHead.getId()))
.eq(ConvertRelation::getTargetId, String.valueOf(request.getTargetBillId())));
}
/**
* 查关联关系对应的分录级配对。
*
* @param relations 单据级关联关系。
* @return 分录级配对列表。
*/
private List<ConvertRelationEntry> loadRelationEntries(List<ConvertRelation> relations) {
List<String> targetIds = new ArrayList<>(relations.size());
for (ConvertRelation relation : relations) {
targetIds.add(relation.getTargetId());
}
return convertRelationEntryMapper.selectList(new LambdaQueryWrapper<ConvertRelationEntry>()
.in(ConvertRelationEntry::getTargetId, targetIds));
}
/**
* 按目标单元数据查适用的反写规则。
*
* <p>回滚(撤销 / 弃审)时<b>不按触发时机过滤</b>:一笔数量可能是保存时机的规则累加的,
* 撤销时要把它退回去;只退「当前这个触发时机」的规则会漏。</p>
*
* @param targetHead 目标单元数据。
* @param request 反写触发请求。
* @return 适用的反写规则列表。
*/
private List<ReverseWritingRules> loadApplicableRules(OnlFormHead targetHead, BotpWriteBackRequest request) {
if (targetHead == null) {
return Collections.emptyList();
}
LambdaQueryWrapper<ReverseWritingRules> wrapper = new LambdaQueryWrapper<ReverseWritingRules>()
.eq(ReverseWritingRules::getEnable, 1)
.eq(ReverseWritingRules::getTargetDoc, targetHead.getId());
if (!request.isRollback()) {
wrapper.eq(ReverseWritingRules::getTriggerTiming, String.valueOf(request.getTriggerTiming()));
}
return reverseWritingRulesService.list(wrapper);
}
/**
* 按单据 id 重新查目标单数据(拿到的才是落库后的真实数据)。
*
* @param request 反写触发请求。
* @return 目标单数据。
*/
private ObjectValue loadTargetBill(BotpWriteBackRequest request) {
ObjectValue bill = queryRow(request.getTargetTableName(), String.valueOf(request.getTargetBillId()));
if (bill == null) {
throw new BotpMappingException("反写时目标单不存在,表名=" + request.getTargetTableName() + ",id=" + request.getTargetBillId());
}
return bill;
}
/**
* 按表名解析单据元数据。
*
* @param tableName 表名。
* @return 元数据;不存在时返回 null。
*/
private OnlFormHead resolveHead(String tableName) {
if (tableName == null) {
return null;
}
return onlFormHeadService.getHeadTableNameCache(tableName);
}
/**
* 把值转成 BigDecimal,转不了返回 null。
*
* @param value 原值。
* @return BigDecimal。
*/
private BigDecimal toBigDecimal(Object value) {
if (value == null) {
return null;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof Number) {
return new BigDecimal(value.toString());
}
String text = String.valueOf(value).trim();
if (text.isEmpty() || !text.matches("-?\\d+(\\.\\d+)?")) {
return null;
}
return new BigDecimal(text);
}
/**
* 把函数映射 JSON 转成 ConditionEvaluator 需要的 Map。
*
* @param json 函数映射 JSON,可空。
* @return 函数名 → 函数 id。
*/
private Map<String, Long> toFunctionForm(String json) {
if (StringUtils.isBlank(json)) {
return new HashMap<>();
}
try {
return toFunctionForm(JSON.parseObject(json));
} catch (Exception e) {
log.warn("函数映射解析失败,按函数名兜底查找。json={}", json);
return new HashMap<>();
}
}
/**
* 把函数映射对象转成 ConditionEvaluator / FunctionExecutor 需要的 Map。
*
* @param object 函数映射对象,可空。
* @return 函数名 → 函数 id。
*/
private Map<String, Long> toFunctionForm(JSONObject object) {
Map<String, Long> functionForm = new HashMap<>();
if (object == null) {
return functionForm;
}
for (String key : object.keySet()) {
Long value = object.getLong(key);
if (value != null) {
functionForm.put(key, value);
}
}
return functionForm;
}
/**
* 解析插件执行顺序,非数字排在最后。
*
* @param serialNumber 配置里的顺序值。
* @return 可比较的数值。
*/
private static int parseOrder(String serialNumber) {
if (StringUtils.isBlank(serialNumber)) {
return Integer.MAX_VALUE;
}
try {
return Integer.parseInt(serialNumber.trim());
} catch (NumberFormatException e) {
return Integer.MAX_VALUE;
}
}
/**
* 校验请求入参。
*
* @param request 反写触发请求。
*/
private void validate(BotpWriteBackRequest request) {
if (request == null) {
throw new BotpMappingException("反写请求不能为空");
}
if (request.getTargetTableName() == null || request.getTargetBillId() == null) {
throw new BotpMappingException("反写请求缺少目标单表名或单据 id");
}
}
}

61
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertBatch.java

@ -0,0 +1,61 @@ @@ -0,0 +1,61 @@
package apelet.common.botp.service.execute.entity;
import lombok.Data;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* 转换批次:一个批次生成一张目标单据。
*
* <p>分单策略决定怎么把源单集合切成批次:</p>
* <ul>
* <li>一对一:每条源单一个批次 → 出 N 张目标单</li>
* <li>多对一:全部源单一个批次 → 出 1 张目标单</li>
* <li>按规则分组合并:按分单字段分组,每组一个批次 → 出 M 张目标单</li>
* </ul>
*
* <p>批次是「一条源单 → 一条目标单」这个旧假设的解耦点:批次内可以有多条源单,
* 它们的源行摊平后按行键归并,再按合并方式取值。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertBatch {
/**
* 分组键。一对一为源单 id;多对一为 null;按规则分组合并为分单字段的值。
*/
private String groupKey;
/**
* 本批次包含的源单 id(保持传入顺序)。
*/
private Set<String> sourceBillIds = new LinkedHashSet<>();
public ConvertBatch() {
}
public ConvertBatch(String groupKey) {
this.groupKey = groupKey;
}
/**
* 追加一条源单。
*
* @param billId 源单 id。
*/
public void add(String billId) {
this.sourceBillIds.add(billId);
}
/**
* 批次内的源单条数。
*
* @return 源单条数。
*/
public int size() {
return this.sourceBillIds.size();
}
}

35
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertColumnConfig.java

@ -1,41 +1,42 @@ @@ -1,41 +1,42 @@
package apelet.common.botp.service.execute.entity;
import apelet.common.botp.model.constant.MergeMethodEnum;
import apelet.common.botp.model.constant.ValueMethodEnum;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/**
* 一条字段映射的运行时配置:源在哪、怎么取值、多行怎么合并、落到哪个目标分录。
*
* @author Soon
* @version 1.0
* @description
* Create by 2024/1/23 22:21
*/
@Data
public class ConvertColumnConfig {
/**
* 表名
* 源表表名
*/
private String tableName;//表名 源单
private String tableName;
/**
* 字段名
* 源字段名
*/
private String columnName;//字段名 源单
private String columnName;
/**
* 取值方式
* 取值方式:源单字段 / 常量 / 计算公式 / 按条件取值
*/
private int valueMethod;//1 源字段 2 目标字段
private ValueMethodEnum valueMethod;
/**
* 字段值
* 取值:常量值(valueMethod=常量)或按条件取值的分支配置
*/
private String value;
/**
* 是否主表
* 是否源主表字段
*/
private boolean isMain;
@ -44,6 +45,18 @@ public class ConvertColumnConfig { @@ -44,6 +45,18 @@ public class ConvertColumnConfig {
*/
private JSONObject calculationFormula;
/**
* 合并方式:直接取 / 求和 / 拼接。多对一或按规则分组合并、多条源行映射到同一目标行时生效。
*/
private MergeMethodEnum mergeMethod;
/**
* 目标分录表名。目标单有多个分录表时用它指定落到哪个;只配一个分录时可空。
*/
private String entryTarget;
/**
* 执行顺序:数值越小越先执行。同一目标字段挂多条映射时按此升序依次写入。
*/
private Integer serialNumber;
}

67
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertConditionBranch.java

@ -0,0 +1,67 @@ @@ -0,0 +1,67 @@
package apelet.common.botp.service.execute.entity;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/**
* 「按条件取值」的一条分支。
*
* <p>取值方式为「按条件取值」时,映射行的 cltValue 存一个 JSON 数组,按顺序逐条判断,
* <b>命中即取</b>,未命中任何分支时目标字段为空。</p>
*
* <p>JSON 结构(约定,配置侧前端产出、执行侧消费):</p>
* <pre>
* [
* { "condition": "pur_apply.pur_apply.qty &gt; 100", "valueType": "constant", "value": "大额" },
* { "condition": "pur_apply.pur_apply.qty &gt; 0", "valueType": "source", "value": "qty" },
* { "valueType": "constant", "value": "其它" }
* ]
* </pre>
*
* <p>condition 为空视为兜底分支,必定命中。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertConditionBranch {
/**
* 取值来源:源字段。
*/
public static final String TYPE_SOURCE = "source";
/**
* 取值来源:常量。
*/
public static final String TYPE_CONSTANT = "constant";
/**
* 条件表达式。为空表示兜底分支。
*/
private String condition;
/**
* 条件的函数映射(表达式里的 $fun$ 占位 → 函数 id),可空。
*/
private JSONObject conditionJson;
/**
* 取值来源:source 源字段 / constant 常量。
*/
private String valueType;
/**
* 取值:valueType=source 时为源字段列名,valueType=constant 时为常量字面量。
*/
private String value;
/**
* 是否为兜底分支(无条件)。
*
* @return 无条件返回 true。
*/
public boolean isFallback() {
return condition == null || condition.trim().isEmpty();
}
}

78
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertMappingPlan.java

@ -0,0 +1,78 @@ @@ -0,0 +1,78 @@
package apelet.common.botp.service.execute.entity;
import lombok.Data;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 字段映射计划:把配置里的「字段 id → 字段 id」翻译成「表名.列名 → 表名.列名」后的运行时视图。
*
* <p>与旧实现的差别:旧版把所有映射塞进一个 {@code Map<MetaColumn, ConvertColumnConfig>},
* 同一目标字段配多条映射会互相覆盖;本对象用 {@link MetaColumn#getSerialNumber()} 参与唯一性,
* 并按执行顺序保留全部映射,使「同一目标字段挂多条映射依次写入」得以成立。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertMappingPlan {
/**
* 源单主表表名。
*/
private String srcMainTable;
/**
* 目标单主表表名。
*/
private String destMainTable;
/**
* 目标列 → 该列的映射配置。同列多条映射按 serialNumber 升序依次写入。
*/
private Map<MetaColumn, List<ConvertColumnConfig>> columnConfigs = new LinkedHashMap<>();
/**
* 目标分录表 → 该表下的目标列(有序,按 serialNumber)。
*/
private Map<String, List<MetaColumn>> destEntryColumns = new LinkedHashMap<>();
/**
* 涉及的源分录表集合。
*/
private Set<String> srcEntryTables = new LinkedHashSet<>();
/**
* 登记一条映射。
*
* @param destColumn 目标列。
* @param config 映射配置。
*/
public void add(MetaColumn destColumn, ConvertColumnConfig config) {
columnConfigs.computeIfAbsent(destColumn, k -> new ArrayList<>()).add(config);
if (destColumn.isMain()) {
return;
}
List<MetaColumn> columns = destEntryColumns.computeIfAbsent(destColumn.getMetaTable(), k -> new ArrayList<>());
if (!columns.contains(destColumn)) {
columns.add(destColumn);
}
if (!config.isMain() && config.getTableName() != null) {
srcEntryTables.add(config.getTableName());
}
}
/**
* 是否存在目标分录。
*
* @return 存在返回 true。
*/
public boolean hasDestEntry() {
return !destEntryColumns.isEmpty();
}
}

29
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertSourceRow.java

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
package apelet.common.botp.service.execute.entity;
import apelet.common.core.object.ObjectValue;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 一条源分录行 + 它所属的源单。
*
* <p>多对一归并后,一条目标分录行可能对应多条源行、且这些源行可能来自不同源单,
* 所以每行都要记住自己的源单——反写要按「源单 + 源行」精确定位。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
@AllArgsConstructor
public class ConvertSourceRow {
/**
* 所属源单(表头数据)。
*/
private ObjectValue bill;
/**
* 源分录行。
*/
private ObjectValue row;
}

61
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ConvertSourceRowGroup.java

@ -0,0 +1,61 @@ @@ -0,0 +1,61 @@
package apelet.common.botp.service.execute.entity;
import apelet.common.core.object.ObjectValue;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 归并到同一条目标分录行的源行组。
*
* <p>由「行键」分组而来:行键相同(或未配置行键时每行自成一组)的源行归为一组,
* 组内所有行按合并方式折算成目标行的各个字段值。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ConvertSourceRowGroup {
/**
* 组内的源行(含各自所属源单)。
*/
private final List<ConvertSourceRow> items = new ArrayList<>();
/**
* 追加一条源行。
*
* @param bill 所属源单。
* @param row 源分录行。
*/
public void add(ObjectValue bill, ObjectValue row) {
items.add(new ConvertSourceRow(bill, row));
}
/**
* 组内的源行(不含源单信息),供映射策略做合并取值。
*
* @return 源行列表。
*/
public List<ObjectValue> rows() {
if (items.isEmpty()) {
return Collections.emptyList();
}
List<ObjectValue> rows = new ArrayList<>(items.size());
for (ConvertSourceRow item : items) {
rows.add(item.getRow());
}
return rows;
}
/**
* 组内源行条数。
*
* @return 条数。
*/
public int size() {
return items.size();
}
}

40
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/MetaColumn.java

@ -5,6 +5,12 @@ import lombok.Data; @@ -5,6 +5,12 @@ import lombok.Data;
import java.util.Objects;
/**
* 字段映射的唯一标识:一张表上的一个字段。
*
* <p><b>为什么 equals/hashCode 必须带上 serialNumber</b>:映射配置存在
* {@code Map<MetaColumn, ...>} 里,若只比较「表名 + 字段名」,同一目标字段配多条映射时
* 后一条会把前一条覆盖掉——「多行明细求和到一行」「多源字段依次写入同一目标字段」这类配置
* 静默失效。带上执行顺序后,同字段的多条映射才能共存。</p>
*
* @author sunquan
* @version 1.0
@ -16,38 +22,44 @@ public class MetaColumn { @@ -16,38 +22,44 @@ public class MetaColumn {
/**
* 字段名称
*/
private String columnName;
private String columnName;
/**
* 字段类型
*/
private String columnType;
/**
* 主表
* 所属表名
*/
private String metaTable;
/**
* 主表
*/
public boolean isMain;
/**
* 执行顺序:数值越小越先执行。参与唯一性比较,使同一目标字段的多条映射不再互相覆盖。
*/
private Integer serialNumber;
@Override
public int hashCode() {
return Objects.hash(columnName, metaTable);
return Objects.hash(columnName, metaTable, serialNumber);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetaColumn user = (MetaColumn) o;
return columnName.equals(user.columnName) && metaTable
.equals(user.getMetaTable());
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MetaColumn other = (MetaColumn) o;
return Objects.equals(columnName, other.columnName)
&& Objects.equals(metaTable, other.metaTable)
&& Objects.equals(serialNumber, other.serialNumber);
}
}

41
common/common-botp/src/main/java/apelet/common/botp/service/execute/entity/ResolvedConvertRule.java

@ -0,0 +1,41 @@ @@ -0,0 +1,41 @@
package apelet.common.botp.service.execute.entity;
import apelet.common.botp.model.ConvertFieldmappingEntry;
import apelet.common.botp.model.ConvertPluginEntry;
import apelet.common.botp.model.ConvertRule;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* 解析后的转换规则:规则主表 + 字段映射 + 插件分录,外加实际使用的版本号。
*
* <p>未指定版本时取自业务表当前数据;指定版本时取自 convert_rule_ver 快照。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Data
public class ResolvedConvertRule {
/**
* 规则主表。
*/
private ConvertRule rule;
/**
* 字段映射分录。
*/
private List<ConvertFieldmappingEntry> fieldMappings = new ArrayList<>();
/**
* 插件分录。
*/
private List<ConvertPluginEntry> pluginEntries = new ArrayList<>();
/**
* 本次实际使用的规则版本。
*/
private Integer version;
}

97
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingCalculationFormulaMapping.java

@ -1,73 +1,86 @@ @@ -1,73 +1,86 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.core.object.ObjectCollection;
import apelet.common.botp.util.MappingValueMerger;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.util.ApplicationContextHolder;
import apelet.common.online.service.impl.OnlineFormServiceImpl;
import apelet.common.online.util.Jexl3Util;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.singletonList;
/**
* 取值方式「计算公式」:执行配置的 $fun$ 函数算出值写入目标行。
*
* <p>改造点:原来在线表单服务与 Jexl3Util 是在字段初始化时用
* {@code ApplicationContextHolder.getBean(...)} 手工取的(因为策略由 {@code new} 创建、不走 Spring);
* 现在策略本身是 Spring bean,直接 @Resource 注入。</p>
*
* <p>一条目标行对应多条源行时(多对一 / 按规则分组合并),逐条求值后按合并方式折算,
* 与「源单字段」类映射的合并语义保持一致。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/1/25 10:46
*/
@Component
public class BotpMappingCalculationFormulaMapping extends BotpMappingStrategy {
private final OnlineFormServiceImpl onlineFormService =
ApplicationContextHolder.getBean(OnlineFormServiceImpl.class);
private final Jexl3Util Jexl3Util =
ApplicationContextHolder.getBean(Jexl3Util.class);
@Resource
private OnlineFormServiceImpl onlineFormService;
@Resource
private Jexl3Util jexl3Util;
@Override
public ValueMethodEnum valueMethod() {
return ValueMethodEnum.EXPRESSION;
}
@Override
public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) {
ObjectCollection entryDataList = null;
if (!convertColumnConfig.isMain()) {//源表不为主表
entryDataList = srcBillData.getObjectCollection(convertColumnConfig.getTableName());
public void mapping(ConvertColumnConfig config, MetaColumn destColumn, ObjectValue destRow,
ObjectValue sourceBill, List<ObjectValue> sourceRows) {
JSONObject json = config.getCalculationFormula();
if (json == null) {
throw BotpMappingException.invalidMapping("取值方式为「计算公式」但未配置公式,目标字段=" + destColumn.getColumnName());
}
if (destMetaColumn.isMain()) {//目标字段为主表
if (convertColumnConfig.getColumnName() != null) {//源
if (convertColumnConfig.isMain()) {//源字段为主表
JSONObject json = convertColumnConfig.getCalculationFormula();
destBillData.put(destMetaColumn.getColumnName(), srcBillData.get(convertColumnConfig.getColumnName()));
destBillData.put(destMetaColumn.getColumnName(), getValue(json, srcBillData));
} else {//源字段为附表,取分录第一行
if (entryDataList != null && !entryDataList.isEmpty()) {
destBillData.put(destMetaColumn.getColumnName(), entryDataList.getObject(0).get(convertColumnConfig.getColumnName()));
// List<Map<String,Object>> = destBillData.getEntryData().get(destMetaColumn.getMetaTable().getTableName());//获取目标分录
}
}
}
} else {//目标字段为附表,对应附表分录
if (convertColumnConfig.getColumnName() != null) {//源
ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable());
for (int i = 0; i < listMap.size(); i++) {
if (convertColumnConfig.isMain()) {//源字段为主表,每行分录赋值源单表头字段
listMap.getObject(i).put(destMetaColumn.getColumnName(),
srcBillData.get(convertColumnConfig.getColumnName()));
} else {//源字段为附表,每行分录赋值目标单字段
listMap.getObject(i).put(destMetaColumn.getColumnName(),
entryDataList.getObject(i).get(convertColumnConfig.getColumnName()));
}
}
// 一条目标行对应多条源行时,逐条求值再按合并方式折算;只有一条时就是一次求值
List<ObjectValue> contexts = sourceRows == null || sourceRows.isEmpty() ? singletonList(sourceBill) : sourceRows;
List<Object> values = new ArrayList<>(contexts.size());
for (ObjectValue context : contexts) {
if (context != null) {
values.add(evaluate(json, context));
}
}
Object value = MappingValueMerger.mergeValues(values, config.getMergeMethod());
if (value != null) {
destRow.put(destColumn.getColumnName(), value);
}
}
Object getValue(JSONObject json, ObjectValue objectValue) {
/**
* 解析并执行 $fun$ 公式。
*
* @param json 公式配置(含 expressionTranslation / functionForm)。
* @param objectValue 求值上下文(源单整体)。
* @return 计算结果。
*/
private Object evaluate(JSONObject json, ObjectValue objectValue) {
String expression = json.getString("expressionTranslation");
String fun = Jexl3Util.getMySplit("\\$(.*?)\\$", expression);
List<String> funParam = Arrays.asList(Jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
Object[] objects = Jexl3Util.getFunParam(funParam, objectValue);
if (expression == null) {
throw BotpMappingException.invalidMapping("计算公式缺少 expressionTranslation");
}
String fun = jexl3Util.getMySplit("\\$(.*?)\\$", expression);
List<String> funParam = Arrays.asList(jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
Object[] objects = jexl3Util.getFunParam(funParam, objectValue);
return onlineFormService.executeFunction(json, fun, objects);
}
}

71
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingContext.java

@ -1,42 +1,61 @@ @@ -1,42 +1,61 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.core.object.ObjectValue;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.constant.ValueMethodEnum;
import org.springframework.stereotype.Component;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* 单据转换映射策略
* 字段映射策略工厂:按取值方式取到对应的策略实现。
*
* <p>改造点(修 P-5):</p>
* <ul>
* <li>原实现是 if/else 且<b>没有 else 分支</b>,取值方式是未知值时策略对象保持 null,
* 直到调用时才抛 NPE,报错信息毫无线索;现在直接抛含原值的 {@code BotpMappingException}。</li>
* <li>原来的策略是 {@code new} 出来的普通对象,拿不到 Spring 依赖,只能在字段初始化时
* 手工 {@code ApplicationContextHolder.getBean("bean名")};现在策略都是 Spring bean,
* 由构造器收集,依赖正常注入。</li>
* </ul>
*
* @author Soon
* @version 1.0
* Create by 2024/1/25 10:37
*/
@Component
public class BotpMappingContext {
public static final int valueMethod_mapping = 1;//映射
public static final int valueMethod_constant = 2;//常量
public static final int valueMethod_expression = 3;//计算公式
public BotpMappingStrategy botpMappingStrategy;
private final Map<ValueMethodEnum, BotpMappingStrategy> strategyMap = new EnumMap<>(ValueMethodEnum.class);
public BotpMappingContext(int valueMethod){
if(valueMethod == BotpMappingContext.valueMethod_mapping){
botpMappingStrategy = new BotpMappingStrategyMapping();
}else if(valueMethod == BotpMappingContext.valueMethod_constant){
botpMappingStrategy = new BotpMappingStrategyConstant();
}else if(valueMethod == BotpMappingContext.valueMethod_expression){
botpMappingStrategy = new BotpMappingCalculationFormulaMapping();
/**
* 构造器注入全部策略实现,按取值方式建索引。
*
* @param strategies Spring 容器里的全部映射策略。
*/
public BotpMappingContext(List<BotpMappingStrategy> strategies) {
for (BotpMappingStrategy strategy : strategies) {
strategyMap.put(strategy.valueMethod(), strategy);
}
}
public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData){
botpMappingStrategy.mapping(destBillData,destMetaColumn,convertColumnConfig,srcBillData);
/**
* 按取值方式编码取策略。
*
* @param valueMethodCode 配置里的取值方式原值。
* @return 策略实现。
*/
public BotpMappingStrategy strategyOf(String valueMethodCode) {
ValueMethodEnum valueMethod = ValueMethodEnum.parse(valueMethodCode);
if (valueMethod == null) {
throw BotpMappingException.unknownValueMethod(valueMethodCode);
}
BotpMappingStrategy strategy = strategyMap.get(valueMethod);
if (strategy == null) {
// 枚举有值但没注册实现,属于开发期遗漏,同样给出可读信息
throw BotpMappingException.unknownValueMethod(valueMethodCode);
}
return strategy;
}
}

27
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategy.java

@ -1,10 +1,20 @@ @@ -1,10 +1,20 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.core.object.ObjectValue;
import java.util.List;
/**
* 字段映射策略:把「一组源行」上的值按取值方式算出来,写进「一行目标行」。
*
* <p>与旧实现的关键差别:旧版把「目标分录第 i 行 ← 源分录第 i 行」写死在策略里,
* 目标行数又固定等于源行数,所以既没法合并、目标行多于源行时还会越界。
* 新版把「哪条目标行对应哪组源行」这一步提到编排层(归并),策略只负责
* 「给定一组源行,这一列取什么值」——合并、多源、一对一都收敛成同一个调用形态。</p>
*
* @author sunquan
* @version 1.0
* Create by 2024/1/25 10:40
@ -12,8 +22,21 @@ import apelet.common.core.object.ObjectValue; @@ -12,8 +22,21 @@ import apelet.common.core.object.ObjectValue;
public abstract class BotpMappingStrategy {
/**
* 映射转换
* 本策略负责的取值方式。
*
* @return 取值方式枚举。
*/
public abstract void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData);
public abstract ValueMethodEnum valueMethod();
/**
* 求值并写入目标行。
*
* @param config 本条映射的运行时配置(源表、源字段、合并方式、常量/公式等)。
* @param destColumn 目标列(含表名、列名、是否主表)。
* @param destRow 目标行(表头对象,或目标分录的某一行)。
* @param sourceBill 源单整体数据,供公式求值等需要跨行取值的场景使用。
* @param sourceRows 本条目标行对应的源行组,供合并取值使用。
*/
public abstract void mapping(ConvertColumnConfig config, MetaColumn destColumn, ObjectValue destRow,
ObjectValue sourceBill, List<ObjectValue> sourceRows);
}

150
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyCondition.java

@ -0,0 +1,150 @@ @@ -0,0 +1,150 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.exception.BotpMappingException;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.ConvertConditionBranch;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.botp.util.MappingValueMerger;
import apelet.common.core.object.ObjectValue;
import apelet.common.online.rule.condition.ConditionEvaluator;
import apelet.common.online.rule.model.RuleCondition;
import apelet.common.online.rule.model.RuleEvalContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 取值方式「按条件取值」:按分支顺序逐条判断,<b>命中即取</b>,未命中任何分支时目标字段为空。
*
* <p>分支配置的结构见 {@link ConvertConditionBranch}。</p>
*
* <p>条件求值复用在线规则引擎的 {@link ConditionEvaluator},不另起一套——条件口径必须唯一,
* 否则转换和在线表单规则会对同一个表达式给出不同结果。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
public class BotpMappingStrategyCondition extends BotpMappingStrategy {
@Resource
private ConditionEvaluator conditionEvaluator;
@Override
public ValueMethodEnum valueMethod() {
return ValueMethodEnum.CONDITION;
}
@Override
public void mapping(ConvertColumnConfig config, MetaColumn destColumn, ObjectValue destRow,
ObjectValue sourceBill, List<ObjectValue> sourceRows) {
List<ConvertConditionBranch> branches = parseBranches(config.getValue(), destColumn.getColumnName());
if (branches.isEmpty()) {
return;
}
// 主表目标按源单整体求值;分录目标按本条目标行对应的源行求值
ObjectValue evalTarget = destColumn.isMain() ? sourceBill : firstRow(sourceRows, sourceBill);
for (ConvertConditionBranch branch : branches) {
if (!branch.isFallback() && !hit(branch, evalTarget)) {
continue;
}
Object value = resolveValue(branch, sourceRows);
if (value != null) {
destRow.put(destColumn.getColumnName(), value);
}
return;
}
}
/**
* 判断一条分支的条件是否成立。
*
* @param branch 分支。
* @param evalTarget 求值上下文。
* @return 成立返回 true;上下文为空时不成立。
*/
private boolean hit(ConvertConditionBranch branch, ObjectValue evalTarget) {
if (evalTarget == null) {
return false;
}
RuleCondition condition = new RuleCondition();
condition.setExpression(branch.getCondition());
condition.setFunctionForm(toFunctionForm(branch.getConditionJson()));
return conditionEvaluator.evaluate(condition, new RuleEvalContext(evalTarget, null));
}
/**
* 解析命中分支的取值。
*
* @param branch 分支。
* @param sourceRows 本条目标行对应的源行组。
* @return 取值;取不到时返回 null。
*/
private Object resolveValue(ConvertConditionBranch branch, List<ObjectValue> sourceRows) {
if (ConvertConditionBranch.TYPE_SOURCE.equals(branch.getValueType())) {
return MappingValueMerger.merge(sourceRows, branch.getValue(), null);
}
return branch.getValue();
}
/**
* 解析分支数组。
*
* @param json 映射行 cltValue 里的分支 JSON。
* @param destField 目标字段名,仅用于报错定位。
* @return 分支列表,未配置时返回空列表。
*/
private List<ConvertConditionBranch> parseBranches(String json, String destField) {
if (json == null || json.trim().isEmpty()) {
throw BotpMappingException.invalidMapping("取值方式为「按条件取值」但未配置条件分支,目标字段=" + destField);
}
try {
List<ConvertConditionBranch> branches = JSON.parseArray(json, ConvertConditionBranch.class);
return branches == null ? Collections.emptyList() : branches;
} catch (Exception e) {
throw new BotpMappingException("「按条件取值」的分支配置不是合法 JSON,目标字段=" + destField, e);
}
}
/**
* 把条件里的 $fun$ 函数映射转成 FunctionExecutor 需要的 Map。
*
* @param conditionJson 函数映射 JSON,可空。
* @return 函数名 → 函数 id;无配置时返回空 Map。
*/
private Map<String, Long> toFunctionForm(JSONObject conditionJson) {
Map<String, Long> functionForm = new HashMap<>();
if (conditionJson == null) {
return functionForm;
}
for (String key : conditionJson.keySet()) {
try {
functionForm.put(key, conditionJson.getLong(key));
} catch (Exception ignored) {
// 非数字的函数映射忽略,交由求值阶段按函数名兜底查找
}
}
return functionForm;
}
/**
* 取源行组的第一条作为求值上下文,组内无源行时退回源单整体。
*
* @param sourceRows 源行组。
* @param sourceBill 源单整体。
* @return 求值上下文。
*/
private ObjectValue firstRow(List<ObjectValue> sourceRows, ObjectValue sourceBill) {
if (sourceRows != null && !sourceRows.isEmpty()) {
return sourceRows.get(0);
}
return sourceBill;
}
}

27
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyConstant.java

@ -1,28 +1,31 @@ @@ -1,28 +1,31 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 取值方式「常量」:直接写入配置的固定值,与源行组无关。
*
* @author Soon
* @version 1.0
* Create by 2024/1/25 10:47
*/
public class BotpMappingStrategyConstant extends BotpMappingStrategy{
@Component
public class BotpMappingStrategyConstant extends BotpMappingStrategy {
@Override
public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) {
if(destMetaColumn.isMain()){//目标字段为主表,直接赋值常量
destBillData.put(
destMetaColumn.getColumnName(),convertColumnConfig.getValue());
}else{//目标字段为附表,对应附表分录,赋值常量
ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable());
for (int i = 0 ; i < listMap.size() ; i++){
listMap.getObject(i).put(destMetaColumn.getColumnName(),convertColumnConfig.getValue());
}
}
public ValueMethodEnum valueMethod() {
return ValueMethodEnum.CONSTANT;
}
@Override
public void mapping(ConvertColumnConfig config, MetaColumn destColumn, ObjectValue destRow,
ObjectValue sourceBill, List<ObjectValue> sourceRows) {
destRow.put(destColumn.getColumnName(), config.getValue());
}
}

55
common/common-botp/src/main/java/apelet/common/botp/service/execute/mapping/BotpMappingStrategyMapping.java

@ -1,51 +1,38 @@ @@ -1,51 +1,38 @@
package apelet.common.botp.service.execute.mapping;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.execute.entity.ConvertColumnConfig;
import apelet.common.botp.service.execute.entity.MetaColumn;
import apelet.common.core.object.ObjectCollection;
import apelet.common.botp.util.MappingValueMerger;
import apelet.common.core.object.ObjectValue;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 取值方式「源单字段」:从源行组上取同名字段,按合并方式折算后写入目标行。
*
* <p>合并方式在这里生效:多对一 / 按规则分组合并时,一条目标行对应多条源行,
* 按 mergeMethod 决定取第一条、求和还是拼接。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/1/25 10:46
*/
public class BotpMappingStrategyMapping extends BotpMappingStrategy{
@Component
public class BotpMappingStrategyMapping extends BotpMappingStrategy {
@Override
public void mapping(ObjectValue destBillData, MetaColumn destMetaColumn, ConvertColumnConfig convertColumnConfig, ObjectValue srcBillData) {
ObjectCollection entryDataList = null;
if( !convertColumnConfig.isMain() ){//源表不为主表
entryDataList = srcBillData.getObjectCollection(convertColumnConfig.getTableName());
}
if(destMetaColumn.isMain()){//目标字段为主表
if(convertColumnConfig.getColumnName() != null){//源
if(convertColumnConfig.isMain()){//源字段为主表
destBillData.put(destMetaColumn.getColumnName()
,srcBillData.get(convertColumnConfig.getColumnName()));
}else{//源字段为附表,取分录第一行
if( entryDataList.size() > 0){
if(entryDataList != null){
destBillData.put(destMetaColumn.getColumnName(),entryDataList.getObject(0).get(convertColumnConfig.getColumnName()));
// List<Map<String,Object>> = destBillData.getEntryData().get(destMetaColumn.getMetaTable().getTableName());//获取目标分录
}
}
public ValueMethodEnum valueMethod() {
return ValueMethodEnum.MAPPING;
}
}
}
}else{//目标字段为附表,对应附表分录
if(convertColumnConfig.getColumnName() != null) {//源
ObjectCollection listMap = destBillData.getObjectCollection(destMetaColumn.getMetaTable());
for (int i = 0 ; i < listMap.size() ; i++){
if (convertColumnConfig.isMain()) {//源字段为主表,每行分录赋值源单表头字段
listMap.getObject(i).put(destMetaColumn.getColumnName()
,srcBillData.get(convertColumnConfig.getColumnName()));
}else{//源字段为附表,每行分录赋值目标单字段
listMap.getObject(i).put(destMetaColumn.getColumnName(),entryDataList.getObject(i).get(convertColumnConfig.getColumnName()));
}
}
}
@Override
public void mapping(ConvertColumnConfig config, MetaColumn destColumn, ObjectValue destRow,
ObjectValue sourceBill, List<ObjectValue> sourceRows) {
Object value = MappingValueMerger.merge(sourceRows, config.getColumnName(), config.getMergeMethod());
if (value != null) {
destRow.put(destColumn.getColumnName(), value);
}
}
}

34
common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertPluginEntryServiceImpl.java

@ -2,6 +2,8 @@ package apelet.common.botp.service.impl; @@ -2,6 +2,8 @@ package apelet.common.botp.service.impl;
import apelet.common.botp.dao.ConvertPluginEntryMapper;
import apelet.common.botp.model.ConvertPluginEntry;
import apelet.common.botp.model.constant.BotpRuleConstant;
import apelet.common.botp.model.constant.PluginTypeEnum;
import apelet.common.botp.service.IConvertPluginEntryService;
import apelet.common.core.base.dao.BaseDaoMapper;
import apelet.common.core.base.service.BaseService;
@ -14,6 +16,7 @@ import com.github.pagehelper.Page; @@ -14,6 +16,7 @@ import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -72,4 +75,35 @@ public class ConvertPluginEntryServiceImpl extends BaseService<ConvertPluginEntr @@ -72,4 +75,35 @@ public class ConvertPluginEntryServiceImpl extends BaseService<ConvertPluginEntr
this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
return resultList;
}
@Override
public List<ConvertPluginEntry> listByRule(Long ruleId, PluginTypeEnum type) {
if (ruleId == null || type == null) {
return new ArrayList<>();
}
return this.list(new LambdaQueryWrapper<ConvertPluginEntry>()
.eq(ConvertPluginEntry::getType, type.getCode())
.eq(ConvertPluginEntry::getParentId, String.valueOf(ruleId)));
}
@Override
public List<ConvertPluginEntry> listEnabledByRule(Long ruleId, PluginTypeEnum type) {
if (ruleId == null || type == null) {
return new ArrayList<>();
}
return this.list(new LambdaQueryWrapper<ConvertPluginEntry>()
.eq(ConvertPluginEntry::getType, type.getCode())
.eq(ConvertPluginEntry::getEnable, BotpRuleConstant.SWITCH_ON_VALUE)
.eq(ConvertPluginEntry::getParentId, String.valueOf(ruleId)));
}
@Override
public void removeByRule(Long ruleId, PluginTypeEnum type) {
if (ruleId == null || type == null) {
return;
}
this.remove(new LambdaQueryWrapper<ConvertPluginEntry>()
.eq(ConvertPluginEntry::getType, type.getCode())
.eq(ConvertPluginEntry::getParentId, String.valueOf(ruleId)));
}
}

170
common/common-botp/src/main/java/apelet/common/botp/service/impl/ConvertRuleServiceImpl.java

@ -6,10 +6,12 @@ import apelet.common.botp.dao.ConvertRuleMapper; @@ -6,10 +6,12 @@ import apelet.common.botp.dao.ConvertRuleMapper;
import apelet.common.botp.dao.ConvertRuleVerMapper;
import apelet.common.botp.dto.*;
import apelet.common.botp.model.*;
import apelet.common.botp.model.constant.BotpRuleConstant;
import apelet.common.botp.model.constant.SplitMergeStrategyEnum;
import apelet.common.botp.model.constant.ValueMethodEnum;
import apelet.common.botp.service.*;
import apelet.common.botp.service.execute.BotpService;
import apelet.common.botp.service.execute.ConvertOrchestrator;
import apelet.common.botp.service.execute.entity.BillData;
import apelet.common.botp.service.execute.entity.BtpTransformResult;
import apelet.common.botp.util.Constant;
@ -82,6 +84,12 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem @@ -82,6 +84,12 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem
@Autowired
private BotpService botpService;
/**
* 转换编排器:多源单、分单策略、合并取值、按版本执行都在它里面。
*/
@Autowired
private ConvertOrchestrator convertOrchestrator;
@Override
public List<ConvertRule> selectAll(String id) {
return null;
@ -481,139 +489,55 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem @@ -481,139 +489,55 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem
@Override
public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId) {
Set<String> srcBillList = new HashSet<>();
srcBillList.add(srcBillId);
return transform(botpId,srcBill,destBill,srcBillList);
public ConvertResult convert(ConvertRequest request) {
return convertOrchestrator.transform(request);
}
/**
* 兼容入口:老前端按「单张目标单」消费结果。
*
* <p>多目标单时只返回第一张并记 WARN,不静默丢——原实现在转换层就把多选源单砍成第一条,
* 用户以为转了 5 张实际只转了 1 张且毫无提示。新代码请改用 {@link #convert(ConvertRequest)}。</p>
*
* @param botpId 转换规则 id。
* @param srcBill 源单元数据 id(新链路从规则取,此参数保留仅为兼容)。
* @param destBill 目标单元数据 id(同上)。
* @param srcBillId 源单 id。
* @return 单张目标单的转换结果。
*/
@Override
public TransformResultDto transform(String botpId, String srcBill, String destBill, Set<String> srcBillList) {
ConvertRule convertRule = convertRuleMapper.selectById(botpId);//查询转换规则
//查询转换规则字段映射
List<ConvertFieldmappingEntry> convertFieldmappingEntryList = convertFieldmappingEntryMapper.selectList(
new LambdaQueryWrapper<ConvertFieldmappingEntry>()
.eq(ConvertFieldmappingEntry::getParentId, convertRule.getId()));
List<ConvertPluginEntry> convertPluginEntryList = convertPluginEntryMapper.selectList(
new LambdaQueryWrapper<ConvertPluginEntry>()
.eq(ConvertPluginEntry::getEnable, "true")
.eq(ConvertPluginEntry::getParentId, convertRule.getId()));
OnlFormHead srcFormHead = onlFormHeadMapper.selectById(convertRule.getSourceEntityId());//源单元数据
OnlFormHead destFormHead = onlFormHeadMapper.selectById(convertRule.getTargetEntityId());//目标单元数据
BtpTransformResult btpTransformResult = botpService.transform(
convertRule, convertFieldmappingEntryList, convertPluginEntryList, srcFormHead, destFormHead, srcBillList);
TransformResultDto transformResultDto = new TransformResultDto();
ObjectValue objectValue = btpTransformResult.getBillDataList().getObject(0);
transformResultDto.setBillData(convertOvToBillData(objectValue));
if (convertRule.getAutoSave().equals("1")) {//自动保存
transformResultDto.setFormStatus(Constant.FormStatus_AddNew);
} else {
transformResultDto.setFormStatus(Constant.FormStatus_Save);
}
transformResultDto.setFormType(convertRule.getDownInterfaceType());
if (transformResultDto.getFormType().equals(Constant.InterfaceType_ROUTE)) {
toCamelCase(transformResultDto.getBillData());
}
return transformResultDto;
}
private BillData convertOvToBillData(ObjectValue objectValue){
BillData billData = new BillData();
Map<String,Object> headData = new HashMap<>();
Map<String,List<Map<String,Object>>> entryDataCol = new HashMap<>();
if(objectValue.size() > 0){
Iterator it = objectValue.getValues().keySet().iterator();
while (it.hasNext()){
String fieldKey = (String)it.next();
if(objectValue.get(fieldKey) == null){
continue;
}
if(objectValue.get(fieldKey) instanceof ObjectCollection){
ObjectCollection objectCollection = objectValue.getObjectCollection(fieldKey);
List<Map<String,Object>> entryList = new ArrayList<>();
Map<String,Object> entryMap = new HashMap<>();
for(int i = 0; i < objectCollection.size() ; i++){
ObjectValue entryValue = objectCollection.getObject(i);
Iterator entryIt = entryValue.getValues().keySet().iterator();
while(entryIt.hasNext()){
String entryFiledKey = (String)entryIt.next();
if(entryValue.get(entryFiledKey) instanceof ObjectValue ){
ObjectValue entityValue = (ObjectValue)entryValue.get(entryFiledKey);
Long pk = entityValue.getPkValue();
if(pk == null || pk == 0L){
continue;
}
entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(),pk);
if(entityValue == null){
continue;
}
entryMap.put(entryFiledKey,entityValue.get("id"));
entryMap.put(entryFiledKey+"_",entityValue.getValues());
}else{
entryMap.put(entryFiledKey,entryValue.get(entryFiledKey));
}
}
entryList.add(entryMap);
}
entryDataCol.put(fieldKey,entryList);
}else if(objectValue.get(fieldKey) instanceof ObjectValue){
ObjectValue entityValue = (ObjectValue)objectValue.get(fieldKey);
Long pk = entityValue.getPkValue();
if(pk == null || pk == 0L){
continue;
}
entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(),pk);
if(entityValue == null){
continue;
}
headData.put(fieldKey,entityValue.get("id"));
headData.put(fieldKey+"_",entityValue.getValues());
}else{
headData.put(fieldKey,objectValue.get(fieldKey));
}
}
}
billData.setHeadData(headData);
billData.setEntryData(entryDataCol);
return billData;
@Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId) {
return transform(botpId, srcBill, destBill, new LinkedHashSet<>(Collections.singletonList(srcBillId)));
}
/**
* 数据集合的键值,转换成驼峰形式
* @param billData 数据集
* 兼容入口,见 {@link #transform(String, String, String, String)}。
*
* @param botpId 转换规则 id。
* @param srcBill 源单元数据 id。
* @param destBill 目标单元数据 id。
* @param srcBillList 源单 id 集合。
* @return 单张目标单的转换结果。
*/
private void toCamelCase(BillData billData){
billData.setHeadData(toCamelCase(billData.getHeadData()));
Map<String,List<Map<String,Object>>> entryData = billData.getEntryData();
for (String key:entryData.keySet()){
List<Map<String,Object>> dataList = new ArrayList<>();
for(Map<String,Object> datamap:entryData.get(key)){
dataList.add(toCamelCase(datamap));
}
entryData.put(key,dataList);
@Override
@Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, Set<String> srcBillList) {
ConvertResult result = convertOrchestrator.transform(ConvertRequest.of(botpId, srcBillList));
TransformResultDto dto = new TransformResultDto();
dto.setFormStatus(result.getFormStatus());
dto.setFormType(result.getFormType());
if (result.getBills().isEmpty()) {
return dto;
}
billData.setEntryData(toCamelCase(entryData));
}
private Map toCamelCase(Map dataMap){
Map aftTransformData = new HashMap<>();
Iterator<String> iterator = dataMap.keySet().iterator();
while (iterator.hasNext()){
String key = iterator.next();
aftTransformData.put(StrUtil.toCamelCase(key),dataMap.get(key));
if (result.getBills().size() > 1) {
log.warn("本次转换生成了 {} 张目标单,兼容接口只返回第一张;请改用 convert 接口。规则id={}",
result.getBills().size(), botpId);
}
return aftTransformData;
dto.setBillData(result.getBills().get(0).getBillData());
return dto;
}
@Override
public boolean removeAllRelation(ConvertRelationDelDto dto) {
//删除单据关联关系-主表-> 转换规则id等于billId And (源单标识等于billtype或者目标单标识等于billtype)
@ -700,7 +624,7 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem @@ -700,7 +624,7 @@ public class ConvertRuleServiceImpl extends BaseService<ConvertRule,Long> implem
@Override
public List<Map<String, Object>> getPushBillList(ConvertRelationDelDto dto) {
//查询当前单据作为源单并且已启用的转换规则
List<ConvertRule> list = this.list(new LambdaQueryWrapper<ConvertRule>().eq(ConvertRule::getEnabled, "true"));
List<ConvertRule> list = this.list(new LambdaQueryWrapper<ConvertRule>().eq(ConvertRule::getEnabled, BotpRuleConstant.SWITCH_ON_VALUE));
//查询单据名称
//全量在线表单数据 == 转map当临时表用
List<OnlFormHead> allOnlFormHeadsList = onlFormHeadService.list(new LambdaQueryWrapper<OnlFormHead>());

141
common/common-botp/src/main/java/apelet/common/botp/util/BillDataConverter.java

@ -0,0 +1,141 @@ @@ -0,0 +1,141 @@
package apelet.common.botp.util;
import apelet.common.botp.service.execute.entity.BillData;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 把转换产出的 {@link ObjectValue} 转成前端打开单据要用的 {@link BillData}。
*
* <p>从 ConvertRuleServiceImpl 抽出来,让编排器与兼容入口共用一份,避免两处各写一套。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Component
public class BillDataConverter {
@Autowired
private OrmGenDataSourceUtil ormGenDataSourceUtil;
/**
* 转换单据数据。
*
* @param objectValue 转换产出的单据数据。
* @return 前端用的单据数据。
*/
public BillData convert(ObjectValue objectValue) {
BillData billData = new BillData();
Map<String, Object> headData = new HashMap<>();
Map<String, List<Map<String, Object>>> entryDataCol = new HashMap<>();
if (objectValue != null && objectValue.size() > 0) {
Iterator<?> it = objectValue.getValues().keySet().iterator();
while (it.hasNext()) {
String fieldKey = (String) it.next();
if (objectValue.get(fieldKey) == null) {
continue;
}
if (objectValue.get(fieldKey) instanceof ObjectCollection) {
entryDataCol.put(fieldKey, convertEntries(objectValue.getObjectCollection(fieldKey)));
} else if (objectValue.get(fieldKey) instanceof ObjectValue) {
ObjectValue entityValue = (ObjectValue) objectValue.get(fieldKey);
Long pk = entityValue.getPkValue();
if (pk == null || pk == 0L) {
continue;
}
entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(), pk);
if (entityValue == null) {
continue;
}
headData.put(fieldKey, entityValue.get("id"));
headData.put(fieldKey + "_", entityValue.getValues());
} else {
headData.put(fieldKey, objectValue.get(fieldKey));
}
}
}
billData.setHeadData(headData);
billData.setEntryData(entryDataCol);
return billData;
}
/**
* 转换分录集合。
*
* @param objectCollection 分录集合。
* @return 前端用的分录行列表。
*/
private List<Map<String, Object>> convertEntries(ObjectCollection objectCollection) {
List<Map<String, Object>> entryList = new ArrayList<>();
Map<String, Object> entryMap = new HashMap<>();
for (int i = 0; i < objectCollection.size(); i++) {
ObjectValue entryValue = objectCollection.getObject(i);
Iterator<?> entryIt = entryValue.getValues().keySet().iterator();
while (entryIt.hasNext()) {
String entryFiledKey = (String) entryIt.next();
if (entryValue.get(entryFiledKey) instanceof ObjectValue) {
ObjectValue entityValue = (ObjectValue) entryValue.get(entryFiledKey);
Long pk = entityValue.getPkValue();
if (pk == null || pk == 0L) {
continue;
}
entityValue = ormGenDataSourceUtil.queryOne(entityValue.getTableName(), pk);
if (entityValue == null) {
continue;
}
entryMap.put(entryFiledKey, entityValue.get("id"));
entryMap.put(entryFiledKey + "_", entityValue.getValues());
} else {
entryMap.put(entryFiledKey, entryValue.get(entryFiledKey));
}
}
entryList.add(entryMap);
}
return entryList;
}
/**
* 把单据数据的键转成驼峰(路由表单需要)。
*
* @param billData 单据数据。
*/
public void toCamelCase(BillData billData) {
billData.setHeadData(toCamelCase(billData.getHeadData()));
Map<String, List<Map<String, Object>>> entryData = billData.getEntryData();
for (String key : entryData.keySet()) {
List<Map<String, Object>> dataList = new ArrayList<>();
for (Map<String, Object> datamap : entryData.get(key)) {
dataList.add(toCamelCase(datamap));
}
entryData.put(key, dataList);
}
billData.setEntryData(toCamelCase(entryData));
}
/**
* Map 的键转驼峰。
*
* @param dataMap 原 Map。
* @return 转换后的 Map。
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private Map toCamelCase(Map dataMap) {
Map aftTransformData = new HashMap<>();
Iterator<String> iterator = dataMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
aftTransformData.put(StrUtil.toCamelCase(key), dataMap.get(key));
}
return aftTransformData;
}
}

195
common/common-botp/src/main/java/apelet/common/botp/util/MappingValueMerger.java

@ -0,0 +1,195 @@ @@ -0,0 +1,195 @@
package apelet.common.botp.util;
import apelet.common.botp.model.constant.MergeMethodEnum;
import apelet.common.core.object.ObjectValue;
import java.math.BigDecimal;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* 合并取值器:把「一组源行」上的某个字段按合并方式折算成一个值,写进目标行。
*
* <p>这是分录合并的核心——多对一或按规则分组合并时,多条源行会归并到同一目标行,
* 该目标行的每个字段都要决定取这组源行的哪个值:</p>
*
* <ul>
* <li>直接取:组内第一条非空值</li>
* <li>求和:组内所有数值相加(忽略空值与非数值)</li>
* <li>拼接:组内所有值用英文逗号连接,重复值去重</li>
* </ul>
*
* <p>表头字段同样走这套——多对一时表头对应的「源行组」就是各源单的表头,语义一致。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public final class MappingValueMerger {
/**
* 拼接时的分隔符。
*/
public static final String CONCAT_SEPARATOR = ",";
private MappingValueMerger() {
}
/**
* 按合并方式折算一组源行上的字段值。
*
* @param sourceRows 源行组,可为 null 或空。
* @param sourceColumn 源字段列名。
* @param mergeMethod 合并方式,为 null 时按「直接取」处理。
* @return 折算后的值;无可用值时返回 null。
*/
public static Object merge(List<ObjectValue> sourceRows, String sourceColumn, MergeMethodEnum mergeMethod) {
MergeMethodEnum actual = mergeMethod == null ? MergeMethodEnum.DIRECT : mergeMethod;
if (sourceRows == null || sourceRows.isEmpty() || sourceColumn == null) {
return null;
}
if (actual == MergeMethodEnum.SUM) {
return sum(sourceRows, sourceColumn);
}
if (actual == MergeMethodEnum.CONCAT) {
return concat(sourceRows, sourceColumn);
}
return firstNonNull(sourceRows, sourceColumn);
}
/**
* 按合并方式折算一组「已经算好的值」。
*
* <p>用于计算公式、按条件取值这类先求值再合并的场景:每个源行各自算出结果,再折算成一个。</p>
*
* @param values 已算好的值列表,可为 null 或空。
* @param mergeMethod 合并方式,为 null 时按「直接取」处理。
* @return 折算后的值;无可用值时返回 null。
*/
public static Object mergeValues(List<?> values, MergeMethodEnum mergeMethod) {
MergeMethodEnum actual = mergeMethod == null ? MergeMethodEnum.DIRECT : mergeMethod;
if (values == null || values.isEmpty()) {
return null;
}
if (actual == MergeMethodEnum.SUM) {
BigDecimal total = null;
for (Object value : values) {
BigDecimal number = toBigDecimal(value);
if (number == null) {
continue;
}
total = total == null ? number : total.add(number);
}
return total;
}
if (actual == MergeMethodEnum.CONCAT) {
Set<String> distinct = new LinkedHashSet<>();
for (Object value : values) {
if (value == null) {
continue;
}
String text = String.valueOf(value);
if (!text.isEmpty()) {
distinct.add(text);
}
}
return distinct.isEmpty() ? null : String.join(CONCAT_SEPARATOR, distinct);
}
for (Object value : values) {
if (value != null) {
return value;
}
}
return null;
}
/**
* 直接取:组内第一条非空值。
*
* @param sourceRows 源行组。
* @param sourceColumn 源字段列名。
* @return 值;全为空时返回 null。
*/
private static Object firstNonNull(List<ObjectValue> sourceRows, String sourceColumn) {
for (ObjectValue row : sourceRows) {
if (row == null) {
continue;
}
Object value = row.get(sourceColumn);
if (value != null) {
return value;
}
}
return null;
}
/**
* 求和:组内所有可解析为数值的值相加。
*
* @param sourceRows 源行组。
* @param sourceColumn 源字段列名。
* @return 求和结果;全组都非数值时返回 null。
*/
private static BigDecimal sum(List<ObjectValue> sourceRows, String sourceColumn) {
BigDecimal total = null;
for (ObjectValue row : sourceRows) {
if (row == null) {
continue;
}
BigDecimal value = toBigDecimal(row.get(sourceColumn));
if (value == null) {
continue;
}
total = total == null ? value : total.add(value);
}
return total;
}
/**
* 拼接:组内所有非空值用逗号连接,重复值去重(保持首次出现顺序)。
*
* @param sourceRows 源行组。
* @param sourceColumn 源字段列名。
* @return 拼接结果;全为空时返回 null。
*/
private static String concat(List<ObjectValue> sourceRows, String sourceColumn) {
Set<String> distinct = new LinkedHashSet<>();
for (ObjectValue row : sourceRows) {
if (row == null) {
continue;
}
Object value = row.get(sourceColumn);
if (value == null) {
continue;
}
String text = String.valueOf(value);
if (!text.isEmpty()) {
distinct.add(text);
}
}
return distinct.isEmpty() ? null : String.join(CONCAT_SEPARATOR, distinct);
}
/**
* 把值转成 BigDecimal,转不了返回 null。
*
* @param value 原值。
* @return BigDecimal;非数值返回 null。
*/
private static BigDecimal toBigDecimal(Object value) {
if (value == null) {
return null;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof Number) {
return new BigDecimal(value.toString());
}
String text = String.valueOf(value).trim();
if (text.isEmpty() || !text.matches("-?\\d+(\\.\\d+)?")) {
return null;
}
return new BigDecimal(text);
}
}

106
common/common-botp/src/main/java/apelet/common/botp/util/RuleValueCalculator.java

@ -0,0 +1,106 @@ @@ -0,0 +1,106 @@
package apelet.common.botp.util;
import apelet.common.botp.model.constant.ReverseWriteModeEnum;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 反写数值计算器:反写公式的累加 / 扣减 / 覆盖,以及撤销时的反向计算。
*
* <p>修复原实现的两个问题:</p>
* <ul>
* <li>用 {@code Integer.parseInt} 做加减,反写数量带小数(如 0.5)直接抛 NumberFormatException;</li>
* <li>计算结果不按目标字段精度处理,小数位数随运算漂移。</li>
* </ul>
*
* <p>统一用 BigDecimal 计算,并按目标字段精度 HALF_UP 四舍五入。</p>
*
* <p>空值一律按 0 处理(与现有 FormulaAssignExecutor、ReverseWritingPlugIn 的空值语义一致)。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public final class RuleValueCalculator {
/**
* 目标字段精度无法确定时的默认小数位数。
*/
public static final int DEFAULT_SCALE = 2;
private RuleValueCalculator() {
}
/**
* 正向计算:按反写方式算出写入源单的新值。
*
* <ul>
* <li>累加:源值 + 本次值</li>
* <li>扣减:源值 - 本次值</li>
* <li>覆盖:本次值</li>
* </ul>
*
* @param original 源单字段当前值,允许为 null(按 0 处理)。
* @param current 本次写入值,允许为 null(按 0 处理)。
* @param mode 反写方式,为 null 时按「累加」处理。
* @param scale 目标字段精度(小数位数)。
* @return 计算后的新值,已按精度四舍五入。
*/
public static BigDecimal apply(BigDecimal original, BigDecimal current, ReverseWriteModeEnum mode, int scale) {
ReverseWriteModeEnum actualMode = mode == null ? ReverseWriteModeEnum.ACCUMULATE : mode;
BigDecimal base = nullToZero(original);
BigDecimal delta = nullToZero(current);
BigDecimal result;
if (actualMode == ReverseWriteModeEnum.SUBTRACT) {
result = base.subtract(delta);
} else if (actualMode == ReverseWriteModeEnum.OVERWRITE) {
result = delta;
} else {
result = base.add(delta);
}
return round(result, scale);
}
/**
* 回滚计算:撤销 / 弃审下游单据时,把已写入的值回退。
*
* <p>累加与扣减互为逆运算,直接反向计算即可;覆盖不可逆,必须依赖反写时记录的原值
* (convert_relation_entry.before_value)。</p>
*
* @param original 源单字段当前值,允许为 null(按 0 处理)。
* @param current 本次写入值,允许为 null(按 0 处理)。
* @param mode 反写方式,为 null 时按「累加」处理。
* @param beforeValue 覆盖模式下反写前的原值;为 null 表示历史数据未记录原值。
* @param scale 目标字段精度(小数位数)。
* @return 回滚后的值;覆盖模式且 {@code beforeValue} 为 null 时返回 null,
* 表示无法回滚,调用方应记 WARN 后跳过本次写入,而不是写 0。
*/
public static BigDecimal revert(BigDecimal original, BigDecimal current, ReverseWriteModeEnum mode, BigDecimal beforeValue, int scale) {
ReverseWriteModeEnum actualMode = mode == null ? ReverseWriteModeEnum.ACCUMULATE : mode;
if (actualMode == ReverseWriteModeEnum.OVERWRITE) {
return beforeValue == null ? null : round(beforeValue, scale);
}
return apply(original, current, actualMode.reverse(), scale);
}
/**
* 按精度四舍五入。
*
* @param value 待处理的值。
* @param scale 小数位数。
* @return 处理后的值。
*/
public static BigDecimal round(BigDecimal value, int scale) {
return nullToZero(value).setScale(scale < 0 ? DEFAULT_SCALE : scale, RoundingMode.HALF_UP);
}
/**
* 空值转 0。
*
* @param value 原值,允许为 null。
* @return 非 null 的 BigDecimal。
*/
public static BigDecimal nullToZero(BigDecimal value) {
return value == null ? BigDecimal.ZERO : value;
}
}

30
common/common-core/src/main/java/apelet/common/core/botp/BotpReverseWriteFacade.java

@ -0,0 +1,30 @@ @@ -0,0 +1,30 @@
package apelet.common.core.botp;
/**
* 反写执行门面(依赖反转用)。
*
* <p><b>为什么放在 common-core</b>:反写规则的配置与执行都收敛在 common-botp,而触发它的四个业务操作插件
* 在 common-online。若 common-online 直接依赖 common-botp 就成环,所以这里只放一个空接口做依赖反转:
* 实现在 common-botp,common-online 运行时经 ApplicationContextHolder 取。</p>
*
* <p><b>取不到实现时静默跳过</b>,不抛 BeanNotFoundException——未挂载 botp 的应用(如 upms)
* 没有反写入口是预期部署形态,不是错误。</p>
*
* <p>调用方(保存 / 审核 / 撤销 / 弃审插件)应通过
* {@link apelet.common.core.botp.BotpReverseWriteSupport#execute} 调用,不要自己 getBean。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public interface BotpReverseWriteFacade {
/**
* 执行反写。
*
* <p>正向(保存 / 审核)与回滚(撤销 / 弃审)共用本入口,由
* {@link BotpWriteBackRequest#isRollback()} 区分方向。</p>
*
* @param request 反写触发请求。
*/
void execute(BotpWriteBackRequest request);
}

70
common/common-core/src/main/java/apelet/common/core/botp/BotpReverseWriteSupport.java

@ -0,0 +1,70 @@ @@ -0,0 +1,70 @@
package apelet.common.core.botp;
import apelet.common.core.exception.MyRuntimeException;
import apelet.common.core.util.ApplicationContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
/**
* 反写门面的安全取用工具。
*
* <p>common-online 的四个触发插件(保存 / 审核 / 撤销 / 弃审)统一经本类调用反写,
* 不要自己写 {@code ApplicationContextHolder.getBean(BotpReverseWriteFacade.class)}——
* 那样在未挂载 botp 的应用里会抛 {@code BeanNotFoundException}。</p>
*
* <p><b>取不到实现时静默跳过并记 DEBUG 日志</b>:upms 等未挂 botp 的应用没有反写入口是
* 预期部署形态,不是错误。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
@Slf4j
public final class BotpReverseWriteSupport {
private BotpReverseWriteSupport() {
}
/**
* 执行反写;当前应用未挂载 botp 时静默跳过。
*
* @param request 反写触发请求。
*/
public static void execute(BotpWriteBackRequest request) {
BotpReverseWriteFacade facade = getFacadeQuietly();
if (facade == null) {
log.debug("当前应用未挂载 BOTP 反写服务,跳过反写。触发时机={},目标单={},单据id={}",
request == null ? null : request.getTriggerTiming(),
request == null ? null : request.getTargetTableName(),
request == null ? null : request.getTargetBillId());
return;
}
facade.execute(request);
}
/**
* 反写入口是否可用。
*
* <p>供需要"先判定、后执行"的场景使用(例如调用方想区分「跳过了」和「执行了」)。</p>
*
* @return 可用返回 true。
*/
public static boolean isAvailable() {
return getFacadeQuietly() != null;
}
/**
* 从 Spring 容器取反写门面实现,取不到返回 null(不抛异常)。
*
* <p>ApplicationContextHolder 没有安全取法,这里同时兜住两类异常:容器里没有该 bean
* (BeansException),以及容器本身尚未就绪(MyRuntimeException)。</p>
*
* @return 门面实现;未挂载时为 null。
*/
private static BotpReverseWriteFacade getFacadeQuietly() {
try {
return ApplicationContextHolder.getBean(BotpReverseWriteFacade.class);
} catch (BeansException | MyRuntimeException e) {
return null;
}
}
}

113
common/common-core/src/main/java/apelet/common/core/botp/BotpWriteBackRequest.java

@ -0,0 +1,113 @@ @@ -0,0 +1,113 @@
package apelet.common.core.botp;
/**
* 反写触发请求。
*
* <p>由 common-online 的四个触发插件(保存 / 审核 / 撤销 / 弃审)构造,交给
* {@link BotpReverseWriteFacade} 执行。放在 common-core 是为了让 common-online 能在
* 不依赖 common-botp 的前提下传参。</p>
*
* <p>只带定位信息(表名 + 单据 id),不带单据数据——反写编排器按 id 重新查目标单,
* 拿到的才是落库后的真实数据(触发时点可能在保存之后)。</p>
*
* @author chenchuchuan
* @since 2026-10-21
*/
public class BotpWriteBackRequest {
/**
* 触发时机:保存即反写。对应 reverse_writing_rules.trigger_timing。
*/
public static final int TIMING_SAVE = 1;
/**
* 触发时机:审核即反写。
*/
public static final int TIMING_AUDIT = 2;
/**
* 目标单表名。
*/
private String targetTableName;
/**
* 目标单 id。
*/
private Long targetBillId;
/**
* 触发时机:1 保存 / 2 审核。
*/
private Integer triggerTiming;
/**
* 是否为回滚方向:撤销 / 弃审时为 true,此时按反写方式的逆运算回退已写入的值。
*/
private boolean rollback;
public BotpWriteBackRequest() {
}
public BotpWriteBackRequest(String targetTableName, Long targetBillId, Integer triggerTiming, boolean rollback) {
this.targetTableName = targetTableName;
this.targetBillId = targetBillId;
this.triggerTiming = triggerTiming;
this.rollback = rollback;
}
/**
* 构造正向(非回滚)请求。
*
* @param targetTableName 目标单表名。
* @param targetBillId 目标单 id。
* @param triggerTiming 触发时机。
* @return 请求对象。
*/
public static BotpWriteBackRequest of(String targetTableName, Long targetBillId, Integer triggerTiming) {
return new BotpWriteBackRequest(targetTableName, targetBillId, triggerTiming, false);
}
/**
* 构造回滚(撤销 / 弃审)请求。
*
* @param targetTableName 目标单表名。
* @param targetBillId 目标单 id。
* @param triggerTiming 触发时机。
* @return 请求对象。
*/
public static BotpWriteBackRequest rollback(String targetTableName, Long targetBillId, Integer triggerTiming) {
return new BotpWriteBackRequest(targetTableName, targetBillId, triggerTiming, true);
}
public String getTargetTableName() {
return targetTableName;
}
public void setTargetTableName(String targetTableName) {
this.targetTableName = targetTableName;
}
public Long getTargetBillId() {
return targetBillId;
}
public void setTargetBillId(Long targetBillId) {
this.targetBillId = targetBillId;
}
public Integer getTriggerTiming() {
return triggerTiming;
}
public void setTriggerTiming(Integer triggerTiming) {
this.triggerTiming = triggerTiming;
}
public boolean isRollback() {
return rollback;
}
public void setRollback(boolean rollback) {
this.rollback = rollback;
}
}

11
common/common-generator/src/main/java/apelet/common/generator/service/impl/OnlFormHeadServiceImpl.java

@ -853,6 +853,17 @@ public class OnlFormHeadServiceImpl extends ServiceImpl<OnlFormHeadMapper, OnlFo @@ -853,6 +853,17 @@ public class OnlFormHeadServiceImpl extends ServiceImpl<OnlFormHeadMapper, OnlFo
seq.setIsEmpty(1);
seq.setIsDefault(1);
list.add(seq);
// 源单行关闭标记:反写规则「源单行关闭条件」成立时置 1,撤销/弃审不满足条件时置回 0。
// 用于让推满的行不再出现在选单候选里(可在转换规则的「选单过滤」中引用 closed_flag = 0)。
OnlFormField closedFlag = new OnlFormField();
closedFlag.setFieldName("closed_flag");
closedFlag.setFieldRemark("源单行关闭标记(1:已关闭 0:未关闭)");
closedFlag.setFieldType(CustomUtil.FieldType_int);
closedFlag.setRowDisabled(1);
closedFlag.setIsEmpty(1);
closedFlag.setIsDefault(1);
list.add(closedFlag);
}
// //流程表单需要添加的参数

150
common/common-online/src/main/java/apelet/common/online/plugin/pre/AuditOperationServicePlugIn.java

@ -1,143 +1,45 @@ @@ -1,143 +1,45 @@
package apelet.common.online.plugin.pre;
import apelet.common.core.util.ApplicationContextHolder;
import apelet.common.generator.service.IOnlFormHeadService;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.core.botp.BotpReverseWriteSupport;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.object.ObjectValue;
import apelet.common.online.plugin.BeginOperationTransactionArgs;
import apelet.common.online.plugin.OperationServicePlugIn;
import apelet.common.online.plugin.OperationServicePlugInArgs;
import apelet.common.online.service.impl.OnlineFormServiceImpl;
import apelet.common.online.util.Jexl3Util;
import lombok.extern.slf4j.Slf4j;
/**
* 单据审核:触发「审核即反写」。
*
* <p><b>改造点(FR-6.2 / P-8)</b>:原来的 beginOperationTransaction 整块是注释掉的,
* 里面还有 {@code if (srcbillid 存在) { } } 这样的空 if 块、以及拿一个查出来没改过的对象
* 直接 update 的写法——审核反写实际是残桩。现在反写收口到 WriteBackOrchestrator,
* 这里只负责按 {@code triggerTiming=2} 触发。</p>
*
* <p>不改动单据状态:状态流转是既有行为,本次只补齐反写触发。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/4/22 17:22
*/
@Slf4j
public class AuditOperationServicePlugIn extends OperationServicePlugIn {
private OnlineFormServiceImpl onlineFormService;
// private IReverseWritingRulesService reverseWritingRulesService;
// private IReverseWritingBusinessService businessService;
// private IReverseWritingFormulaService formulaService;
private OrmGenDataSourceUtil ormGenDataSourceUtil;
private IOnlFormHeadService onlFormHeadService;
private Jexl3Util jexl3Util;
public AuditOperationServicePlugIn() {
onlineFormService = ApplicationContextHolder.getBean("onlineFormService");
// reverseWritingRulesService = ApplicationContextHolder.getBean("reverseWritingRulesServiceImpl");
// businessService = ApplicationContextHolder.getBean("reverseWritingBusinessServiceImpl");
// formulaService = ApplicationContextHolder.getBean("reverseWritingFormulaServiceImpl");
ormGenDataSourceUtil = ApplicationContextHolder.getBean("ormGenDataSourceUtil");
onlFormHeadService = ApplicationContextHolder.getBean("onlFormHeadServiceImpl");
jexl3Util = ApplicationContextHolder.getBean("jexl3Util");
}
@Override
public void onPreparePropertys(OperationServicePlugInArgs e) {
e.addFiledKey("id");
e.addFiledKey("billstatus");
}
// @Override
// public void beginOperationTransaction(BeginOperationTransactionArgs e) {
//
// ObjectValue objectValue = e.getModel();
// if (!objectValue.get("billstatus").equals("B")) {
// throw new RuntimeException("只有提交状态才能审核");
// }
// try {
// objectValue.put("billstatus", "C");
// Selector selector = new Selector();
// selector.getList().add(new SelectorItem("billstatus"));
// ormGenDataSourceUtil().update(objectValue.getTableName(), objectValue, selector);
//
// OnlFormHead onlFormHead = onlFormHeadService.getOne(new LambdaQueryWrapper<OnlFormHead>().eq(OnlFormHead::getTableName, objectValue.getTableName()));
// List<ReverseWritingRules> list = reverseWritingRulesService.list(
// new LambdaQueryWrapper<ReverseWritingRules>()
// .eq(ReverseWritingRules::getTargetDoc, onlFormHead.getId())
// .eq(ReverseWritingRules::getTriggerTiming, 2)
// .eq(ReverseWritingRules::getEnable, 1)
// );
// if (list.isEmpty()) {
// return;
// }
// objectValue = ormGenDataSourceUtil.queryOne(objectValue.getTableName(), objectValue.getLong("id"));
//
//
// for (ReverseWritingRules rules : list) {
// List<ReverseWritingBusiness> businesses = businessService.list(
// new LambdaQueryWrapper<ReverseWritingBusiness>()
// .eq(ReverseWritingBusiness::getRulesId, rules.getId())
// .eq(ReverseWritingBusiness::getEnable, 1)
// );
// List<ReverseWritingFormula> formulaList = formulaService.list(
// new LambdaQueryWrapper<ReverseWritingFormula>()
// .eq(ReverseWritingFormula::getRulesId, rules.getId())
// .eq(ReverseWritingFormula::getEnable, 1)
// );
// OnlFormHead srcForm = onlFormHeadService.getOne(
// new LambdaQueryWrapper<OnlFormHead>().eq(OnlFormHead::getId, rules.getSourceDocuments())
// );
// if (objectValue.getValues().containsKey("srcbillid")) {
//
// } else {
// Map map = objectValue.getValues();
// for (Object key : map.keySet()) {
// if (map.get(key) instanceof ObjectCollection) {
// ObjectCollection entryList = (ObjectCollection) map.get(key);
// Iterator iterator = entryList.iterator();
// while (iterator.hasNext()) {
// ObjectValue next = (ObjectValue) iterator.next();
// if (next.containsKey("srcbillid")) {
// ObjectValue srcObjectValue = ormGenDataSourceUtil.queryOne(srcForm.getTableName(), next.getLong("srcbillid"));
// ObjectValue finalObjectValue = objectValue;
// businesses.forEach(b -> {
// try {
// boolean bool = (boolean) onlineFormService.func(b.getPreconditionsEnglish(), JSON.parseObject(b.getPreconditionsJson()), finalObjectValue);
// String expressionTransl = bool ? b.getEstablishedEnglish() : b.getNotEstablishedEnglish();
// String jsonObj = bool ? b.getEstablishedJson() : b.getNotEstablishedJson();
// List<String> split = Arrays.asList(expressionTransl.split("="));
// String fun = "";
// for (String s : split) {
// s = s.trim();
// if (s.startsWith("$") && s.endsWith("$")) {
// fun = s;
// }
// }
// fun = jexl3Util.getMySplit("\\$(.*?)\\$", fun);
// List<String> funParam = Arrays.asList(jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
// Object[] objects = jexl3Util.getFunParam(funParam, finalObjectValue);
// Object o = onlineFormService.executeFunction(JSON.parseObject(jsonObj), fun, objects);
// ormGenDataSourceUtil.update(srcObjectValue.getTableName(), srcObjectValue, null);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// });
// formulaList.forEach(f -> {
//
// try {
// ormGenDataSourceUtil.update(srcObjectValue.getTableName(), srcObjectValue, null);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// });
// }
// }
// }
// }
//
// }
// }
//
//
// // 审核反写规则
//
// } catch (Exception e1) {
// throw new MyRuntimeException(e1);
// }
//
// }
@Override
public void beginOperationTransaction(BeginOperationTransactionArgs e) {
ObjectValue objectValue = e.getModel();
String tableName = objectValue.getTableName();
Long billId = objectValue.getLong("id");
if (billId == null) {
log.debug("审核时未取得单据 id,跳过反写。表名={}", tableName);
return;
}
BotpReverseWriteSupport.execute(BotpWriteBackRequest.of(tableName, billId, BotpWriteBackRequest.TIMING_AUDIT));
}
}

57
common/common-online/src/main/java/apelet/common/online/plugin/pre/RevokeOperationServicePlugIn.java

@ -1,5 +1,7 @@ @@ -1,5 +1,7 @@
package apelet.common.online.plugin.pre;
import apelet.common.core.botp.BotpReverseWriteSupport;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.object.CallResult;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.object.TokenData;
@ -10,32 +12,36 @@ import apelet.common.flow.model.FlowWorkOrder; @@ -10,32 +12,36 @@ import apelet.common.flow.model.FlowWorkOrder;
import apelet.common.flow.service.FlowApiService;
import apelet.common.generator.model.OnlFormHead;
import apelet.common.generator.service.IOnlFormHeadService;
//import apelet.common.generator.service.IReverseWritingBusinessService;
//import apelet.common.generator.service.IReverseWritingFormulaService;
//import apelet.common.generator.service.IReverseWritingRulesService;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.online.plugin.BeginOperationTransactionArgs;
import apelet.common.online.plugin.OperationServicePlugIn;
import apelet.common.online.plugin.OperationServicePlugInArgs;
import apelet.common.online.service.impl.OnlineFormServiceImpl;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
/**
* 单据撤销:状态下沉 + 停流程 + 触发反写回滚。
*
* <p><b>改造点(FR-6.3 / P-9)</b>:原来这里 import 并声明了三个反写 Service,但构造器里
* 从未注入、方法体里从未使用——撤销后已累加的数量不会回收,源单数量只增不减。
* 现在按 {@code rollback_on_revoke} 回滚。</p>
*
* <p>是否真的回滚由反写编排器按规则上的 {@code rollback_on_revoke} 决定,
* 关闭时编排器只记 INFO 日志、不改数据。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/4/22 17:27
*/
@Slf4j
public class RevokeOperationServicePlugIn extends OperationServicePlugIn {
// private IReverseWritingRulesService reverseWritingRulesService;
// private IReverseWritingBusinessService businessService;
// private IReverseWritingFormulaService formulaService;
private OnlineFormServiceImpl onlineFormService;
private OrmGenDataSourceUtil ormGenDataSourceUtil;
private IOnlFormHeadService onlFormHeadService;
public RevokeOperationServicePlugIn() {
@ -43,20 +49,18 @@ public class RevokeOperationServicePlugIn extends OperationServicePlugIn { @@ -43,20 +49,18 @@ public class RevokeOperationServicePlugIn extends OperationServicePlugIn {
onlFormHeadService = ApplicationContextHolder.getBean("onlFormHeadServiceImpl");
}
public void onPreparePropertys(OperationServicePlugInArgs e){
@Override
public void onPreparePropertys(OperationServicePlugInArgs e) {
e.addFiledKey("id");
e.addFiledKey("billstatus");
}
@Override
public void beginOperationTransaction(BeginOperationTransactionArgs e) {
ObjectValue objectValue = e.getModel();
String tableName = objectValue.getTableName();
OnlFormHead onlFormHead = onlFormHeadService.getHeadTableNameCache(tableName);
// 判断 数据源
if (onlFormHead != null && onlFormHead.getIsomerismMark() != null) {
// eas数据
HashMap<String, Object> map = new HashMap<>();
map.put("method", "drawbackData");
map.put("bosType", onlFormHead.getIsomerismMark());
@ -64,33 +68,34 @@ public class RevokeOperationServicePlugIn extends OperationServicePlugIn { @@ -64,33 +68,34 @@ public class RevokeOperationServicePlugIn extends OperationServicePlugIn {
ormGenDataSourceUtil.drawbackData("eas", onlFormHead.getTableName(), objectValue.getString("id"), map);
return;
}
if(!objectValue.get("billstatus").equals("B")){
if (!"B".equals(objectValue.get("billstatus"))) {
throw new RuntimeException("只有提交状态才能撤销");
}
try{
objectValue.put("billstatus","A");
try {
objectValue.put("billstatus", "A");
Selector selector = new Selector();
selector.getList().add(new SelectorItem("billstatus"));
ormGenDataSourceUtil().update(objectValue.getTableName(),objectValue,selector);
ormGenDataSourceUtil().update(tableName, objectValue, selector);
LambdaQueryWrapper<FlowWorkOrder> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(FlowWorkOrder::getBusinessKey, objectValue.get("id"));
queryWrapper.in(FlowWorkOrder::getFlowStatus,
FlowTaskStatus.SUBMITTED,FlowTaskStatus.APPROVING);
queryWrapper.in(FlowWorkOrder::getFlowStatus, FlowTaskStatus.SUBMITTED, FlowTaskStatus.APPROVING);
FlowWorkOrderMapper flowWorkOrderMapper = ApplicationContextHolder.getBean("flowWorkOrderMapper");
FlowWorkOrder flowWorkOrder = flowWorkOrderMapper.selectOne(queryWrapper);
if(flowWorkOrder != null){
if (flowWorkOrder != null) {
FlowApiService flowApiService = ApplicationContextHolder.getBean("flowApiService");
CallResult result = flowApiService.stopProcessInstance(flowWorkOrder.getProcessInstanceId(), "撤销", false);
if (!result.isSuccess()) {
throw new RuntimeException(result.getErrorMessage());
throw new RuntimeException(result.getErrorMessage());
}
}
}catch (Exception e1){
e1.printStackTrace();;
throw new RuntimeException(e1);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
Long billId = objectValue.getLong("id");
if (billId == null) {
log.debug("撤销时未取得单据 id,跳过反写回滚。表名={}", tableName);
return;
}
BotpReverseWriteSupport.execute(BotpWriteBackRequest.rollback(tableName, billId, BotpWriteBackRequest.TIMING_SAVE));
}
}

198
common/common-online/src/main/java/apelet/common/online/plugin/pre/SaveOperationServicePlugIn.java

@ -1,13 +1,14 @@ @@ -1,13 +1,14 @@
package apelet.common.online.plugin.pre;
import apelet.common.core.botp.BotpReverseWriteSupport;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.exception.MyRuntimeException;
import apelet.common.core.object.ColumnEncodedRule;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.object.TokenData;
import apelet.common.core.util.ApplicationContextHolder;
import apelet.common.generator.model.*;
import apelet.common.generator.service.*;
import apelet.common.generator.model.OnlFormHead;
import apelet.common.generator.service.IOnlFormHeadService;
import apelet.common.generator.utils.OrmGenDataSourceUtil;
import apelet.common.online.model.OnlineColumn;
import apelet.common.online.model.OnlineTable;
@ -17,52 +18,45 @@ import apelet.common.online.plugin.OperationServicePlugIn; @@ -17,52 +18,45 @@ import apelet.common.online.plugin.OperationServicePlugIn;
import apelet.common.online.plugin.OperationServicePlugInArgs;
import apelet.common.online.service.OnlineColumnService;
import apelet.common.online.service.OnlineTableService;
import apelet.common.online.service.impl.OnlineFormServiceImpl;
import apelet.common.online.util.Jexl3Util;
import apelet.common.redis.util.CommonRedisUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.util.*;
import java.util.List;
/**
* 单据保存:落库 + 触发「保存即反写」。
*
* <p><b>改造点(FR-6.1 / E5.1)</b>:原来这里有一段几百行的反写实现,整块被注释掉了——
* 保存路径实际上完全不反写(业务规则那半段即使放开也只 {@code System.out.println})。
* 现在反写收口到 common-botp 的 WriteBackOrchestrator,这里只负责「什么时候触发」。</p>
*
* <p>未挂载 botp 的应用(如 upms)没有反写实现,{@link BotpReverseWriteSupport} 会静默跳过,
* 不抛 BeanNotFoundException——这是预期部署形态。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/4/24 11:16
*/
@Slf4j
public class SaveOperationServicePlugIn extends OperationServicePlugIn {
private OrmGenDataSourceUtil ormGenDataSourceUtil;
private IOnlFormHeadService onlFormHeadService;
private OnlineFormServiceImpl onlineFormService;
private CommonRedisUtil commonRedisUtil;
private OnlineTableService onlineTableService;
private OnlineColumnService onlineColumnService;
private Jexl3Util jexl3Util;
private CommonRedisUtil commonRedisUtil;
// private IReverseWritingRulesService reverseWritingRulesService;
// private IReverseWritingBusinessService businessService;
// private IReverseWritingFormulaService formulaService;
public SaveOperationServicePlugIn() {
ormGenDataSourceUtil = ApplicationContextHolder.getBean("ormGenDataSourceUtil");
onlFormHeadService = ApplicationContextHolder.getBean("onlFormHeadServiceImpl");
onlineFormService = ApplicationContextHolder.getBean("onlineFormService");
// reverseWritingRulesService = ApplicationContextHolder.getBean("reverseWritingRulesServiceImpl");
// businessService = ApplicationContextHolder.getBean("reverseWritingBusinessServiceImpl");
// formulaService = ApplicationContextHolder.getBean("reverseWritingFormulaServiceImpl");
jexl3Util = ApplicationContextHolder.getBean("jexl3Util");
commonRedisUtil = ApplicationContextHolder.getBean("commonRedisUtil");
onlineTableService = ApplicationContextHolder.getBean("onlineTableService");
onlineColumnService = ApplicationContextHolder.getBean("onlineColumnService");
@ -76,33 +70,44 @@ public class SaveOperationServicePlugIn extends OperationServicePlugIn { @@ -76,33 +70,44 @@ public class SaveOperationServicePlugIn extends OperationServicePlugIn {
@Override
public void beginOperationTransaction(BeginOperationTransactionArgs e) {
ObjectValue objectValue = e.getModel();
String tableName = objectValue.getTableName();
try {
ObjectValue objectValue = e.getModel();
String tableName = objectValue.getTableName();
OnlFormHead onlFormHead = onlFormHeadService.getHeadTableNameCache(tableName);
// 判断 数据源
if (onlFormHead != null && onlFormHead.getIsomerismMark() != null) {
// eas数据
ormGenDataSourceUtil.saveData(tableName, objectValue);
this.getOperationResult().setInfo(objectValue.get("id")+"");
this.getOperationResult().setInfo(objectValue.get("id") + "");
} else {
// orm 数据
ormSaveOrUpdate(objectValue, onlFormHead);
this.getOperationResult().setInfo(objectValue.get("id")+"");
this.getOperationResult().setInfo(objectValue.get("id") + "");
}
} catch (Exception ex) {
throw new MyRuntimeException(ex.getMessage());
}
triggerWriteBack(tableName, objectValue);
}
/**
* 触发「保存即反写」。
*
* <p>按单据 id 重新查数据由反写编排器负责,这里只传定位信息。</p>
*
* @param tableName 单据表名。
* @param objectValue 保存后的单据数据。
*/
private void triggerWriteBack(String tableName, ObjectValue objectValue) {
Long billId = objectValue.getLong("id");
if (billId == null) {
log.debug("保存后未取得单据 id,跳过反写。表名={}", tableName);
return;
}
BotpReverseWriteSupport.execute(BotpWriteBackRequest.of(tableName, billId, BotpWriteBackRequest.TIMING_SAVE));
}
private ObjectValue ormSaveOrUpdate(ObjectValue objectValue, OnlFormHead onlFormHead) throws Exception {
ObjectValue queryOne = ormGenDataSourceUtil.queryOne(objectValue.getTableName(), objectValue.getLong("id"));
ObjectValue jsonObject=new ObjectValue("xy_sys_user");
jsonObject.put("id", TokenData.takeFromRequest().getUserId());
jsonObject.put("name",TokenData.takeFromRequest().getLoginName());
if (queryOne != null) {
objectValue.put("update_time", DateUtil.now());
// objectValue.put("update_user_id", jsonObject);
objectValue = ormGenDataSourceUtil.update(objectValue.getTableName(), objectValue, null);
} else {
OnlineTable onlineTable = onlineTableService.getOne(new LambdaQueryWrapper<OnlineTable>().eq(OnlineTable::getTableName, objectValue.getTableName()));
@ -111,137 +116,14 @@ public class SaveOperationServicePlugIn extends OperationServicePlugIn { @@ -111,137 +116,14 @@ public class SaveOperationServicePlugIn extends OperationServicePlugIn {
if (onlineColumn.getFieldKind() != null && onlineColumn.getFieldKind().equals(FieldKind.AUTO_CODE)) {
if (StringUtils.isNotBlank(onlineColumn.getEncodedRule())) {
ColumnEncodedRule rule = JSON.parseObject(onlineColumn.getEncodedRule(), ColumnEncodedRule.class);
String code = commonRedisUtil.generateTransId(
rule.getPrefix(), rule.getPrecisionTo(), rule.getMiddle(), rule.getIdWidth());
String code = commonRedisUtil.generateTransId(rule.getPrefix(), rule.getPrecisionTo(), rule.getMiddle(), rule.getIdWidth());
objectValue.put(onlineColumn.getColumnName(), code);
}
}
}
objectValue.put("create_time", DateUtil.now());
//objectValue.put("create_user_id", jsonObject);
objectValue = ormGenDataSourceUtil.addNew(objectValue.getTableName(), objectValue);
}
// reverseWriting(objectValue, onlFormHead);
return objectValue;
}
// 反写规则
// void reverseWriting(ObjectValue objectValue, OnlFormHead onlFormHead) {
// // 判断是否存在源单单据ID
// if (StringUtils.isEmpty(objectValue.getString("srcbillid"))) {
// return;
// }
// // 反写规则
// List<ReverseWritingRules> rules = reverseWritingRulesService.list(
// new LambdaQueryWrapper<ReverseWritingRules>()
// .eq(ReverseWritingRules::getEnable, 1)
// .eq(ReverseWritingRules::getTriggerTiming, 1)
// .eq(ReverseWritingRules::getTargetDoc, onlFormHead.getId()));
// ObjectValue finalObjectValue = objectValue;
// rules.forEach(rule -> {
// // 反写公式
// List<ReverseWritingFormula> formulaList = formulaService.list(
// new LambdaQueryWrapper<ReverseWritingFormula>()
// .eq(ReverseWritingFormula::getEnable, 1)
// .eq(ReverseWritingFormula::getRulesId, rule.getId()));
// for (ReverseWritingFormula formula : formulaList) {
// if (formula.getEnable() == 0) continue;
// JSONObject conditionJson = JSON.parseObject(formula.getConditionJson());
// String expressionTranslation = conditionJson.getString("expressionTranslation");
// boolean funValue = (Boolean) onlineFormService.func(expressionTranslation, conditionJson, finalObjectValue);
// if (funValue) {
// String sourceSingleField = formula.getSourceSingleField();
// String formulaField = formula.getFormulaEnglish();
// String[] s = sourceSingleField.split("\\."); // 上游单据
// String[] f = formulaField.split("\\."); // 下游单据
// if (s[0].equals(s[1])) {
// //修改表头
// ObjectValue srcObjectValue = new ObjectValue(s[1]);
// srcObjectValue.put("id", finalObjectValue.getLong("srcbillid"));
// srcObjectValue.put(s[2], finalObjectValue.get(s[2]));
// try {
// ormGenDataSourceUtil.update(srcObjectValue.getTableName(), srcObjectValue, null);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// } else {
// //修改分录
// ObjectCollection collection = (ObjectCollection) finalObjectValue.get(f[1]);
// Iterator iterator = collection.iterator();
// while (iterator.hasNext()) {
// ObjectValue next = (ObjectValue) iterator.next();
// Object value = getValue(formula.getFormulaJson(), next);
// // 反写原单据
// ObjectValue srcObjectValue = new ObjectValue(s[1]);
// srcObjectValue.put("id", next.getLong("srcbillentryid"));
// srcObjectValue.put(s[2], value);
// try {
// ormGenDataSourceUtil.update(srcObjectValue.getTableName(), srcObjectValue, null);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// }
// }
// // 业务规则
// List<ReverseWritingBusiness> businessList = businessService.list(
// new LambdaQueryWrapper<ReverseWritingBusiness>()
// .eq(ReverseWritingBusiness::getEnable, 1)
// .eq(ReverseWritingBusiness::getRulesId, rule.getId()));
// for (ReverseWritingBusiness business : businessList) {
// if (business.getEnable() == 0) continue;
// String preconditionsEnglish = business.getPreconditionsEnglish();
// JSONObject jsonObject = JSONObject.parseObject(business.getPreconditionsJson());
// boolean p = (Boolean) onlineFormService.func(preconditionsEnglish, jsonObject, finalObjectValue);
// String expression;
// JSONObject expressionJson;
// if (p) {
// expression = business.getEstablishedEnglish();
// expressionJson = JSON.parseObject(business.getEstablishedJson());
// } else {
// expression = business.getNotEstablishedEnglish();
// expressionJson = JSON.parseObject(business.getNotEstablishedJson());
// }
// List<String> split = Arrays.asList(expression.split("="));
// String fun = "";
// String tableName = "";
// for (String s : split) {
// s = s.trim();
// tableName = s.split("\\.")[0];
// if (s.startsWith("$") && s.endsWith("$")) {
// fun = s;
// }
// }
// ObjectValue srcObjectValue = ormGenDataSourceUtil.queryOne(tableName, objectValue.getLong("srcbillid"), null);
// fun = jexl3Util.getMySplit("\\$(.*?)\\$", fun);
// List<String> funParam = Arrays.asList(jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
// Object[] objects = jexl3Util.getFunParam(funParam, srcObjectValue);
// Object o = onlineFormService.executeFunction(expressionJson, fun, objects);
// System.out.println(o);
// }
//
// });
// }
Object getValue(String json, ObjectValue objectValue) {
// 计算反写公式
JSONObject jsonObject = JSON.parseObject(json);
String expression = jsonObject.getString("expressionTranslation");
if (expression.startsWith("$")) {
String fun = jexl3Util.getMySplit("\\$(.*?)\\$", expression);
List<String> funParam = Arrays.asList(jexl3Util.getMySplit("\\((.*?)\\)", fun).split(","));
Object[] objects = jexl3Util.getFunParam(funParam, objectValue);
//执行函数
return onlineFormService.executeFunction(jsonObject, fun, objects);
} else {
String[] split = expression.split("\\.");
return objectValue.get(split[2]);
}
}
}

41
common/common-online/src/main/java/apelet/common/online/plugin/pre/UnAuditOperationServicePlugIn.java

@ -1,43 +1,58 @@ @@ -1,43 +1,58 @@
package apelet.common.online.plugin.pre;
import apelet.common.core.botp.BotpReverseWriteSupport;
import apelet.common.core.botp.BotpWriteBackRequest;
import apelet.common.core.object.ObjectValue;
import apelet.common.online.plugin.BeginOperationTransactionArgs;
import apelet.common.online.plugin.OperationServicePlugIn;
import apelet.common.online.plugin.OperationServicePlugInArgs;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import lombok.extern.slf4j.Slf4j;
/**
* 单据弃审:状态下沉 + 触发反写回滚。
*
* <p><b>改造点(FR-6.3 / P-9)</b>:原来这里完全没有反写逻辑——连 import 都没有。
* 弃审后已累加的数量不会回收,源单数量只增不减。现在按 {@code rollback_on_revoke} 回滚。</p>
*
* <p>是否真的回滚由反写编排器按规则上的 {@code rollback_on_revoke} 决定,
* 关闭时编排器只记 INFO 日志、不改数据。</p>
*
* @author Soon
* @version 1.0
* Create by 2024/4/22 17:28
*/
@Slf4j
public class UnAuditOperationServicePlugIn extends OperationServicePlugIn {
public void onPreparePropertys(OperationServicePlugInArgs e){
@Override
public void onPreparePropertys(OperationServicePlugInArgs e) {
e.addFiledKey("id");
e.addFiledKey("billstatus");
}
@Override
public void beginOperationTransaction(BeginOperationTransactionArgs e) {
ObjectValue objectValue = e.getModel();
if(!objectValue.get("billstatus").equals("C")){
String tableName = objectValue.getTableName();
Object billstatus = objectValue.get("billstatus");
if (!"C".equals(billstatus)) {
throw new RuntimeException("只有审核状态才能反审核");
}
try{
objectValue.put("billstatus","A");
try {
objectValue.put("billstatus", "A");
Selector selector = new Selector();
selector.getList().add(new SelectorItem("billstatus"));
ormGenDataSourceUtil().update(objectValue.getTableName(),objectValue,selector);
}catch (Exception e1){
e1.printStackTrace();;
throw new RuntimeException(e1);
ormGenDataSourceUtil().update(tableName, objectValue, selector);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
Long billId = objectValue.getLong("id");
if (billId == null) {
log.debug("弃审时未取得单据 id,跳过反写回滚。表名={}", tableName);
return;
}
BotpReverseWriteSupport.execute(BotpWriteBackRequest.rollback(tableName, billId, BotpWriteBackRequest.TIMING_AUDIT));
}
}

Loading…
Cancel
Save