Browse Source
- 将映射策略接口改为按单行目标+源行组求值,解耦编排层与策略层 - BotpMappingContext 由 if/else 工厂改为 EnumMap 策略工厂,修复未知取值方式抛 NPE 的问题 - 各策略实现改为 Spring bean,依赖通过 @Resource 注入替代手工 getBean - 新增按条件取值策略(BotpMappingStrategyCondition),复用在线规则引擎求值 - AbstractTransformPlugIn 改为实现 ConvertPlugIn 接口的兼容桥,存量插件无需改代码 - 回写插件分录表名从映射计划动态获取,修复 Long 对象引用比较的 bug - 新增 BotpMappingException 替代 NPE,提供含配置原值的可读报错 - 抽取 BillDataConverter 工具类,编排器与兼容入口共用单据数据转换逻辑dev-lml
55 changed files with 5063 additions and 1286 deletions
@ -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; |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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); |
||||
} |
||||
} |
||||
@ -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"; |
||||
} |
||||
@ -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(" ")); |
||||
} |
||||
} |
||||
@ -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(" ")); |
||||
} |
||||
} |
||||
@ -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(" ")); |
||||
} |
||||
} |
||||
@ -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(" ")); |
||||
} |
||||
} |
||||
@ -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(" ")); |
||||
} |
||||
} |
||||
@ -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> |
||||
* @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"); |
||||
} |
||||
} |
||||
|
||||
@ -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); |
||||
} |
||||
} |
||||
} |
||||
@ -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()); |
||||
} |
||||
} |
||||
|
||||
@ -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) { |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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) { |
||||
} |
||||
} |
||||
File diff suppressed because it is too large
Load Diff
@ -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); |
||||
} |
||||
} |
||||
@ -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>,不是拿表头求值再一刀切——「已下推数量 >= 数量」这类条件 |
||||
* 引用的是分录行上的字段,用表头求值永远取不到值。</p> |
||||
* |
||||
* <p><b>条件成立写 1,不成立写 0</b>:撤销 / 弃审把数量退回来之后条件不再成立, |
||||
* 这里会把标记清掉、解除关闭(PRD §6.3 ④)。只写 1 不写 0 的话,被关掉的行永远关着。</p> |
||||
* |
||||
* <p>条件里的字段引用建议写成 {@code 分录表.分录表.字段} 形式(如 |
||||
* {@code pur_apply_entry.pur_apply_entry.orderqty >= 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"); |
||||
} |
||||
} |
||||
} |
||||
@ -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(); |
||||
} |
||||
} |
||||
@ -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 > 100", "valueType": "constant", "value": "大额" }, |
||||
* { "condition": "pur_apply.pur_apply.qty > 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(); |
||||
} |
||||
} |
||||
@ -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(); |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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(); |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
@ -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); |
||||
} |
||||
} |
||||
|
||||
@ -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; |
||||
} |
||||
|
||||
} |
||||
|
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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()); |
||||
} |
||||
} |
||||
|
||||
@ -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); |
||||
} |
||||
|
||||
} |
||||
} |
||||
|
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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); |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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); |
||||
} |
||||
@ -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; |
||||
} |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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)); |
||||
} |
||||
} |
||||
|
||||
@ -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…
Reference in new issue