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());
}
}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugIn.java
new file mode 100644
index 0000000..bc3651d
--- /dev/null
+++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugIn.java
@@ -0,0 +1,44 @@
+package apelet.common.botp.plugin.spi;
+
+/**
+ * 转换插件扩展点。
+ *
+ * 插件是「配置化字段映射覆盖不了时的逃生舱」:跨表计算、多字段联动、落库前的数据修正等,
+ * 用字段映射表达不了的逻辑写在这里。
+ *
+ * 插件不硬编码在流程里,而是配置在 convert_plugin_entry(type=convert)中,可挂 0~N 个,
+ * 每个能单独开关、单独排序(按 serialNumber 升序执行)。
+ *
+ * 两个钩子的时序语义不同,选错会不生效:
+ *
+ * - {@link #afterFieldMapping} —— 字段映射完成、尚未落库。可以改数据,改了会一起落库。
+ * - {@link #afterTransform} —— 转换完成、已落库。只能做副作用(发通知、写日志、调外部系统),
+ * 此时再改 destBillData 不会写进数据库。
+ *
+ *
+ * 插件不可覆盖:条件求值与数值计算内核、精度规则、事务边界、规则的启用/过滤判定。
+ * 插件是扩展点,不是覆盖点——内核必须唯一,否则每个插件各算一套,口径就散了。
+ *
+ * 钩子方法均有 default 空实现,插件只实现自己关心的钩子即可。
+ *
+ * @author chenchuchuan
+ * @since 2026-10-21
+ */
+public interface ConvertPlugIn {
+
+ /**
+ * 目标字段赋值完毕后事件(落库前,可改数据)。
+ *
+ * @param context 转换上下文。
+ */
+ default void afterFieldMapping(ConvertPlugInContext context) {
+ }
+
+ /**
+ * 单据转换后事件(落库后,只做副作用)。
+ *
+ * @param context 转换上下文。
+ */
+ default void afterTransform(ConvertPlugInContext context) {
+ }
+}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugInContext.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugInContext.java
new file mode 100644
index 0000000..381718b
--- /dev/null
+++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/ConvertPlugInContext.java
@@ -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;
+
+/**
+ * 转换插件上下文。
+ *
+ * 每次转换生成一份,按钩子传给插件。插件通过它拿到规则信息与单据数据;
+ *
+ * 元数据({@link OnlFormHead})用于替代原先插件里硬编码的表名/字段名——插件不应再写死
+ * {@code pur_order_entry}、{@code orderqty} 这类具体单据的表名字段名,而应从规则上下文与元数据推导,
+ * 这样同一套插件换单据就能复用。
+ *
+ * @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;
+
+ /**
+ * 本次转换的字段映射计划。
+ *
+ * 插件取表名/字段名从这里取,不要写死 {@code pur_order_entry}、{@code orderqty} 这类具体单据的
+ * 表名字段名——写死意味着换单据就得改 Java 重新发版,「任意表单可配置」就不成立了。
+ * {@code mappingPlan.getDestEntryColumns().keySet()} 即目标单的全部分录表名。
+ */
+ private ConvertMappingPlan mappingPlan;
+}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackContext.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackContext.java
new file mode 100644
index 0000000..77cef3f
--- /dev/null
+++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackContext.java
@@ -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;
+
+/**
+ * 反写插件上下文。
+ *
+ * 反写是一条有严格顺序的流水线(定位关联 → 业务规则 → 逐条公式 → 超额检查 → 写入源单 → 关闭源单行),
+ * 每次反写生成一份上下文,随流水线推进逐步填充字段,各钩子阶段可读到的内容不同:
+ *
+ *
+ * 各钩子阶段可用的字段
+ * | 钩子 | 已填充 |
+ * | beforeExecWriteBackRule | rule / srcBillData / destBillData |
+ * | afterCalcWriteValue | + formula / originalValue / currentValue / newValue |
+ * | beforeExcessCheck | 同上 |
+ * | afterExcessCheck | + excess |
+ * | afterCommitAmount | + committed(是否已实际写入源单) |
+ *
+ *
+ * 未被填充的字段为 null,插件取用前需自行判空。
+ *
+ * @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;
+}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackPlugIn.java b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackPlugIn.java
new file mode 100644
index 0000000..a0a601a
--- /dev/null
+++ b/common/common-botp/src/main/java/apelet/common/botp/plugin/spi/WriteBackPlugIn.java
@@ -0,0 +1,90 @@
+package apelet.common.botp.plugin.spi;
+
+/**
+ * 反写插件扩展点。
+ *
+ * 反写流水线在关键节点留出 5 个钩子,插件可在这些点插入定制逻辑,但内核始终握着关键部分
+ * (条件求值、数值计算、精度、超额判定、事务边界)。
+ *
+ * 流水线与钩子的位置:
+ *
+ *
+ * 定位关联单据
+ * ↓
+ * beforeExecWriteBackRule ← 钩子 1
+ * ↓
+ * 业务规则前置条件 → 成立 / 不成立分支
+ * ↓
+ * 逐条公式(按 exec_order 升序):条件求值 → 求源单字段值 → BigDecimal 计算
+ * ↓
+ * afterCalcWriteValue ← 钩子 2(新值已算出,尚未写入源单)
+ * ↓
+ * beforeExcessCheck ← 钩子 3
+ * ↓
+ * 超额检查(拦截报错 / 仅告警)
+ * ↓
+ * afterExcessCheck ← 钩子 4
+ * ↓
+ * 写入源单(按行主键精确匹配)
+ * ↓
+ * 源单行关闭条件判定
+ * ↓
+ * 事务提交
+ * ↓
+ * afterCommitAmount ← 钩子 5(事务提交后回调)
+ *
+ *
+ * 钩子方法均有 default 空实现,插件只实现自己关心的钩子即可。
+ *
+ * 插件配置在 convert_plugin_entry(type=writeback)中,按 serialNumber 升序执行、按 enable 过滤。
+ *
+ * @author chenchuchuan
+ * @since 2026-10-21
+ */
+public interface WriteBackPlugIn {
+
+ /**
+ * 反写规则开始执行前。
+ *
+ * @param context 反写上下文。
+ */
+ default void beforeExecWriteBackRule(WriteBackContext context) {
+ }
+
+ /**
+ * 数值算完、尚未做超额检查与写入。
+ *
+ * 此时可读到 {@code formula}、{@code originalValue}、{@code currentValue}、{@code newValue},
+ * 但改 {@code newValue} 是否生效由编排器决定——插件不应依赖能改值。
+ *
+ * @param context 反写上下文。
+ */
+ default void afterCalcWriteValue(WriteBackContext context) {
+ }
+
+ /**
+ * 超额检查前。
+ *
+ * @param context 反写上下文。
+ */
+ default void beforeExcessCheck(WriteBackContext context) {
+ }
+
+ /**
+ * 超额检查后,可读到 {@code excess} 判定结果。
+ *
+ * @param context 反写上下文。
+ */
+ default void afterExcessCheck(WriteBackContext context) {
+ }
+
+ /**
+ * 值已写入源单、事务提交后回调。
+ *
+ * 典型的副作用场景:发通知、写外部系统。此时回滚已不可能。
+ *
+ * @param context 反写上下文。
+ */
+ default void afterCommitAmount(WriteBackContext context) {
+ }
+}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java
index a125eb5..f7d68d6 100644
--- a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java
+++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertPluginEntryService.java
@@ -1,6 +1,7 @@
package apelet.common.botp.service;
import apelet.common.botp.model.ConvertPluginEntry;
+import apelet.common.botp.model.constant.PluginTypeEnum;
import apelet.common.core.base.service.IBaseService;
import java.util.List;
@@ -13,4 +14,34 @@ public interface IConvertPluginEntryService extends IBaseService getConvertPluginEntryRelation(Long id);
List getConvertPluginEntryListWithRelation(ConvertPluginEntry convertPluginEntryFilter, String buildOrderBy);
+
+ /**
+ * 查某规则下指定类型的全部插件。
+ *
+ * 转换插件与反写插件共用 convert_plugin_entry,parentId 分别指向 convert_rule.id 与
+ * reverse_writing_rules.id —— 两张表主键值域重叠,只能靠 type 区分。
+ * 所有查询/删除都必须走本类的这三个方法,不要各处手写 wrapper,漏一处就会串数据。
+ *
+ * @param ruleId 规则 id。
+ * @param type 插件类型。
+ * @return 插件分录列表。
+ */
+ List listByRule(Long ruleId, PluginTypeEnum type);
+
+ /**
+ * 查某规则下指定类型且已启用的插件。
+ *
+ * @param ruleId 规则 id。
+ * @param type 插件类型。
+ * @return 已启用的插件分录列表。
+ */
+ List listEnabledByRule(Long ruleId, PluginTypeEnum type);
+
+ /**
+ * 删除某规则下指定类型的全部插件。
+ *
+ * @param ruleId 规则 id。
+ * @param type 插件类型。
+ */
+ void removeByRule(Long ruleId, PluginTypeEnum type);
}
diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java
index dac7552..cf099f5 100644
--- a/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java
+++ b/common/common-botp/src/main/java/apelet/common/botp/service/IConvertRuleService.java
@@ -2,6 +2,8 @@ package apelet.common.botp.service;
import apelet.common.botp.dto.ConvertRelationDelDto;
import apelet.common.botp.dto.ConvertRelationListDto;
+import apelet.common.botp.dto.ConvertRequest;
+import apelet.common.botp.dto.ConvertResult;
import apelet.common.botp.dto.RuleVersionDiffDto;
import apelet.common.botp.dto.TransformResultDto;
import apelet.common.botp.model.*;
@@ -71,12 +73,25 @@ public interface IConvertRuleService extends IBaseService {
public boolean removeAllRelation(ConvertRelationDelDto dto);
/**
+ * 执行转换:支持多源单、分单策略、合并取值、按版本执行。
+ *
+ * 推式(下推)与拉式(选单)共用本入口,差异只在源单 id 从哪来。
+ *
+ * @param request 转换请求。
+ * @return 转换结果,含每个目标单的 id 与单号、实际使用的规则版本。
+ */
+ ConvertResult convert(ConvertRequest request);
+
+ /**
* @botpId 转准规则id
* @srcBill 源单据元数据id
* @destBill 目标单据元数据id
* @srcbillId 源单据id
* @return
+ * @deprecated 兼容老前端:只返回单张目标单。多目标单时只取第一张并记 WARN,
+ * 请改用 {@link #convert(ConvertRequest)}。
*/
+ @Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, String srcBillId);
/**
@@ -85,7 +100,10 @@ public interface IConvertRuleService extends IBaseService {
* @destBill 目标单据元数据id
* @srcbillId 源单据id集合
* @return
+ * @deprecated 兼容老前端:只返回单张目标单。多目标单时只取第一张并记 WARN,
+ * 请改用 {@link #convert(ConvertRequest)}。
*/
+ @Deprecated
public TransformResultDto transform(String botpId, String srcBill, String destBill, Set srcBillList);
diff --git a/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java b/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java
index 51362b4..367b437 100644
--- a/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java
+++ b/common/common-botp/src/main/java/apelet/common/botp/service/execute/BotpService.java
@@ -2,45 +2,57 @@ package apelet.common.botp.service.execute;
import apelet.common.botp.dao.ConvertRelationEntryMapper;
import apelet.common.botp.dao.ConvertRelationMapper;
-import apelet.common.botp.db.object.*;
-import apelet.common.botp.db.util.DbUtil;
-import apelet.common.botp.model.*;
+import apelet.common.botp.exception.BotpMappingException;
+import apelet.common.botp.model.ConvertFieldmappingEntry;
+import apelet.common.botp.model.ConvertPluginEntry;
+import apelet.common.botp.model.ConvertRelation;
+import apelet.common.botp.model.ConvertRelationEntry;
+import apelet.common.botp.model.ConvertRule;
+import apelet.common.botp.model.constant.BotpRuleConstant;
+import apelet.common.botp.model.constant.MergeMethodEnum;
+import apelet.common.botp.model.constant.ValueMethodEnum;
+import apelet.common.botp.plugin.BotpPlugInLoader;
import apelet.common.botp.plugin.entity.BotpRule;
+import apelet.common.botp.plugin.spi.ConvertPlugIn;
+import apelet.common.botp.plugin.spi.ConvertPlugInContext;
import apelet.common.botp.service.execute.entity.*;
import apelet.common.botp.service.execute.mapping.BotpMappingContext;
-import apelet.common.core.config.DataSourceInfo;
+import apelet.common.botp.service.execute.mapping.BotpMappingStrategy;
import apelet.common.core.object.ObjectCollection;
import apelet.common.core.object.ObjectValue;
import apelet.common.core.object.TokenData;
-import apelet.common.dbutil.constant.DblinkType;
-import apelet.common.dbutil.provider.DataSourceProvider;
import apelet.common.generator.dao.OnlFormFieldMapper;
import apelet.common.generator.dao.OnlFormHeadMapper;
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.model.constant.FieldFilterType;
import apelet.common.orm.impl.Selector;
import apelet.common.orm.impl.SelectorItem;
import apelet.common.sequence.wrapper.IdGeneratorWrapper;
-import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-
import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.time.LocalDateTime;
import java.util.*;
-import java.util.stream.Collectors;
/**
+ * 单据转换器:把一个批次(一条或多条源单)转成一张目标单。
+ *
+ * 流程:
+ *
+ * ① 翻译映射:字段 id → 字段名 → 表名,得到「源表.源列 → 目标表.目标列」
+ * ② 加载批次内全部源单(表头 + 分录)
+ * ③ 建目标骨架:目标分录行按「行键」归并,不再是源行 1:1
+ * ④ 逐列映射:每条映射按 serialNumber 顺序写入,同列多条依次覆盖为叠加
+ * ⑤ 插件 afterFieldMapping(落库前,可改数据)
+ * ⑥ autoSave 开启时落库 + 写转换关系
+ * ⑦ 插件 afterTransform(落库后,只做副作用)
+ *
+ *
* @author sunquan
* @version 1.0
* Create by 2024/1/22 16:00
@@ -49,6 +61,14 @@ import java.util.stream.Collectors;
@Slf4j
public class BotpService {
+ /**
+ * 插件执行顺序:按 serialNumber 数值升序。
+ *
+ * serialNumber 在库里是 varchar,直接按字符串比较会得到 {@code "10" < "2"} 的错误顺序;
+ * 这里解析成数值再排。解析不了的排在最后。彻底修法是把它改成整型列(需存量数据迁移)。
+ */
+ private static final Comparator PLUGIN_ORDER =
+ Comparator.comparingInt(entry -> parseOrder(entry.getSerialNumber()));
@Autowired
private ConvertRelationMapper convertRelationMapper;
@@ -57,548 +77,647 @@ public class BotpService {
@Autowired
private IdGeneratorWrapper idGenerator;
@Autowired
- private DbUtil dbUtil;
-
- @Autowired
private OnlFormHeadMapper onlFormHeadMapper;
@Autowired
private OnlFormFieldMapper onlFormFieldMapper;
-
@Autowired
private OrmGenDataSourceUtil ormGenDataSourceUtil;
-
@Autowired
- private IOnlFormHeadService onlFormHeadService;
+ private BotpMappingContext botpMappingContext;
+ @Autowired
+ private BotpPlugInLoader plugInLoader;
/**
- * @param convertRule 规则
- * @param convertFieldmappingEntryList 映射分录
- * @param convertPluginEntryList 插件分录
- * @param srcFormHead 源元数据
- * @param destFormHead 目标元数据
- * @param srcBillId 源单据id
- * @return 返回实体数据
+ * 执行一个批次的转换。
+ *
+ * @param convertRule 转换规则。
+ * @param convertFieldmappingEntryList 字段映射分录。
+ * @param convertPluginEntryList 已启用的插件分录。
+ * @param srcFormHead 源单元数据。
+ * @param destFormHead 目标单元数据。
+ * @param srcBillIds 本批次的源单 id。
+ * @return 转换结果。
*/
@Transactional(rollbackFor = Exception.class)
- public BtpTransformResult transform(
- ConvertRule convertRule,
- List convertFieldmappingEntryList,
- List convertPluginEntryList,
- OnlFormHead srcFormHead,
- OnlFormHead destFormHead,
- Set srcBillId) {
-
- String srcTable = srcFormHead.getTableName();//源元数据表名
- List
- mappingFieldList =
- convertFieldmappingEntryList.stream().filter(item -> StringUtils.isNotEmpty(item.getOldfieldNumber())
- && StringUtils.isNotEmpty(item.getNewfieldNumber())
- ).collect(Collectors.toList());//过滤掉没有配置字段映射的行
- Map selectTableMap = new HashMap<>();
- Map insertTableMap = new HashMap<>();
-
- Map convertColumnConfigs = new HashMap<>();
- Map tableMap = new HashMap<>();
- for (ConvertFieldmappingEntry convertFieldmappingEntry : mappingFieldList) {//构建单据转换参数
- String oldfieldNumber = convertFieldmappingEntry.getOldfieldNumber();
- String newfieldNumber = convertFieldmappingEntry.getNewfieldNumber();
+ public BtpTransformResult transform(ConvertRule convertRule,
+ List convertFieldmappingEntryList,
+ List convertPluginEntryList,
+ OnlFormHead srcFormHead,
+ OnlFormHead destFormHead,
+ Set srcBillIds) {
+ if (srcBillIds == null || srcBillIds.isEmpty()) {
+ throw new BotpMappingException("源单 id 不能为空");
+ }
+ ConvertMappingPlan plan = buildMappingPlan(convertFieldmappingEntryList, srcFormHead, destFormHead);
+ List sourceBills = loadSourceBills(plan, srcFormHead, srcBillIds);
+ Map> entryGroups = buildEntryGroups(plan, sourceBills, convertRule);
+ BtpTransformResult result = initDestBillData(plan, sourceBills, convertRule, entryGroups);
+ ObjectValue destBillData = result.getBillDataList().getObject(0);
+ applyMappings(plan, destBillData, sourceBills, convertRule, entryGroups);
+ ConvertPlugInContext context = buildContext(convertRule, srcFormHead, destFormHead, sourceBills.get(0), destBillData, plan);
+ executePlugins(convertPluginEntryList, context, true);
+ if (isAutoSaveOn(convertRule)) {
+ addNew(result, destBillData.getTableName());
+ saveRelation(result.getBillRelationList().get(0), destBillData);
+ }
+ executePlugins(convertPluginEntryList, context, false);
+ return result;
+ }
- String srcTableNumber = null;//源单表名
- String srcColumnNumber = null;//源单字段
- if (StringUtils.isNotEmpty(oldfieldNumber)) {
- OnlFormField onlFormField = onlFormFieldMapper.selectById(oldfieldNumber);
- OnlFormHead onlFormHead = tableMap.get(onlFormField.getHeadId());
- if (onlFormHead == null) {
- onlFormHead = onlFormHeadMapper.selectById(onlFormField.getHeadId());
- tableMap.put(onlFormField.getHeadId(), onlFormHead);
- }
- srcTableNumber = onlFormHead.getTableName();
- srcColumnNumber = onlFormField.getFieldName();
- } else {//配置的源字段为空,则跳过
+ /**
+ * 翻译字段映射:把字段 id 换成「表名.列名」,并按目标列归组。
+ *
+ * 注意不再要求源字段必须配置——取值方式为「常量」的映射本就没有源字段,
+ * 旧实现用 {@code oldfieldNumber 非空} 过滤会把常量映射整条丢掉,导致常量配了不生效。
+ *
+ * @param mappings 字段映射分录。
+ * @param srcFormHead 源单元数据。
+ * @param destFormHead 目标单元数据。
+ * @return 映射计划。
+ */
+ private ConvertMappingPlan buildMappingPlan(List mappings, OnlFormHead srcFormHead, OnlFormHead destFormHead) {
+ ConvertMappingPlan plan = new ConvertMappingPlan();
+ plan.setSrcMainTable(srcFormHead.getTableName());
+ plan.setDestMainTable(destFormHead.getTableName());
+ Map headCache = new HashMap<>();
+ for (ConvertFieldmappingEntry mapping : mappings) {
+ if (StringUtils.isBlank(mapping.getNewfieldNumber())) {
continue;
}
-
- OnlFormField onlFormField = onlFormFieldMapper.selectById(newfieldNumber);
- OnlFormHead onlFormHead = tableMap.get(onlFormField.getHeadId());
- if (onlFormHead == null) {
- onlFormHead = onlFormHeadMapper.selectById(onlFormField.getHeadId());
- tableMap.put(onlFormField.getHeadId(), onlFormHead);
- }
- String destTableNumber = onlFormHead.getTableName();
- String destColumnNumber = onlFormField.getFieldName();
-
- MetaColumn srcMainColumn = this.genMetaTable(selectTableMap, srcTableNumber, srcColumnNumber, srcFormHead);
- MetaColumn destMainColumn = this.genMetaTable(insertTableMap, destTableNumber, destColumnNumber, destFormHead);
-
- ConvertColumnConfig convertColumnConfig = new ConvertColumnConfig();
- convertColumnConfig.setColumnName(srcColumnNumber);//源表字段
- convertColumnConfig.setTableName(srcTableNumber);//源表
- convertColumnConfig.setMain(srcMainColumn == null ? false : srcMainColumn.isMain());//是否主表字段
- convertColumnConfig.setValueMethod(Integer.parseInt(convertFieldmappingEntry.getValueMethod()));//方法
- convertColumnConfig.setValue(convertFieldmappingEntry.getCltValue());//默认值
- convertColumnConfig.setValue(convertFieldmappingEntry.getCltValue());//默认值
-
- if (org.apache.commons.lang3.StringUtils.isNotEmpty(convertFieldmappingEntry.getCalculationJson())) {
- convertColumnConfig.setCalculationFormula(JSON.parseObject(convertFieldmappingEntry.getCalculationJson()));
+ ValueMethodEnum valueMethod = ValueMethodEnum.parse(mapping.getValueMethod());
+ if (valueMethod == null) {
+ throw BotpMappingException.unknownValueMethod(mapping.getValueMethod());
}
- convertColumnConfigs.put(destMainColumn, convertColumnConfig);
-
+ MetaColumn destColumn = buildMetaColumn(mapping.getNewfieldNumber(), destFormHead, headCache, mapping.getSerialNumber());
+ ConvertColumnConfig config = buildColumnConfig(mapping, valueMethod, srcFormHead, headCache);
+ plan.add(destColumn, config);
}
- ObjectValue srcBillData = getBillData(selectTableMap, srcBillId.iterator().next());//源单数据
- ConvertConfig convertConfig = new ConvertConfig();
- convertConfig.setSrcMetaTable(selectTableMap.get(srcFormHead.getTableName()));
- convertConfig.setDestMetaTable(insertTableMap.get(destFormHead.getTableName()));
- convertConfig.setColumnConfigMap(convertColumnConfigs);
-
- BtpTransformResult btpTransformResult = this.convertToDestBill(srcBillData, insertTableMap, convertConfig, convertRule);//转换
- //转换插件
- executePlugin(srcBillData, btpTransformResult.getBillDataList().getObject(0), convertPluginEntryList, convertRule, "afterFieldMapping");//映射完成执行
- if (convertRule.getAutoSave().equals("true")) {//转后直接保存单据
- addNew(btpTransformResult, insertTableMap.get(destFormHead.getTableName()));
- }
- //转换插件
- executePlugin(srcBillData, btpTransformResult.getBillDataList().getObject(0), convertPluginEntryList, convertRule, "afterTransform");//转换后执行
- return btpTransformResult;
+ plan.getColumnConfigs().values().forEach(list -> list.sort(Comparator.comparing(ConvertColumnConfig::getSerialNumber, Comparator.nullsLast(Comparator.naturalOrder()))));
+ return plan;
}
/**
- * 执行转换规则
+ * 构建一条映射的运行时配置。
*
- * @param convertPluginEntryList
+ * @param mapping 映射分录。
+ * @param valueMethod 取值方式。
+ * @param srcFormHead 源单元数据。
+ * @param headCache 元数据缓存。
+ * @return 运行时配置。
*/
- private void executePlugin(
- ObjectValue srcObjectValue,
- ObjectValue destObjectValue,
- List convertPluginEntryList//转换规则
- , ConvertRule convertRule,
- String method
- ) {
- BotpRule botpRule = new BotpRule();
- botpRule.setId(convertRule.getId());
- botpRule.setName(convertRule.getName());
- botpRule.setNumber(convertRule.getNumber());
- botpRule.setSourceBillType(convertRule.getSourceEntityId());
- botpRule.setDestBillType(convertRule.getTargetEntityId());
+ private ConvertColumnConfig buildColumnConfig(ConvertFieldmappingEntry mapping, ValueMethodEnum valueMethod,
+ OnlFormHead srcFormHead, Map headCache) {
+ ConvertColumnConfig config = new ConvertColumnConfig();
+ config.setValueMethod(valueMethod);
+ config.setValue(mapping.getCltValue());
+ config.setMergeMethod(MergeMethodEnum.ofNullable(mapping.getMergeMethod()));
+ config.setEntryTarget(mapping.getEntryTarget());
+ config.setSerialNumber(mapping.getSerialNumber());
+ if (StringUtils.isNotBlank(mapping.getCalculationJson())) {
+ config.setCalculationFormula(JSON.parseObject(mapping.getCalculationJson()));
+ }
+ if (StringUtils.isBlank(mapping.getOldfieldNumber())) {
+ return config;
+ }
+ OnlFormField srcField = onlFormFieldMapper.selectById(mapping.getOldfieldNumber());
+ if (srcField == null) {
+ throw BotpMappingException.invalidMapping("源字段不存在,oldfieldNumber=" + mapping.getOldfieldNumber());
+ }
+ OnlFormHead srcFieldHead = resolveHead(srcField.getHeadId(), headCache);
+ config.setTableName(srcFieldHead.getTableName());
+ config.setColumnName(srcField.getFieldName());
+ config.setMain(srcFieldHead.getTableName().equals(srcFormHead.getTableName()));
+ return config;
+ }
- List list =
- convertPluginEntryList.stream().sorted(Comparator.comparing(ConvertPluginEntry::getSerialNumber)).collect(Collectors.toList());
- for (ConvertPluginEntry sortDto : list) {
- try {
- Class> clazz = Class.forName(sortDto.getClassName());
- Class superClass = clazz.getSuperclass();
- Class[] parameterTypes = new Class[3];
- parameterTypes[0] = ObjectValue.class;
- parameterTypes[1] = ObjectValue.class;
- parameterTypes[2] = BotpRule.class;
- Method ctxMethod = superClass.getDeclaredMethod("setContext", parameterTypes);
+ /**
+ * 构建目标列的元数据标识。
+ *
+ * @param newfieldNumber 目标字段 id。
+ * @param destFormHead 目标单元数据。
+ * @param headCache 元数据缓存。
+ * @param serialNumber 执行顺序。
+ * @return 目标列。
+ */
+ private MetaColumn buildMetaColumn(String newfieldNumber, OnlFormHead destFormHead,
+ Map headCache, Integer serialNumber) {
+ OnlFormField destField = onlFormFieldMapper.selectById(newfieldNumber);
+ if (destField == null) {
+ throw BotpMappingException.invalidMapping("目标字段不存在,newfieldNumber=" + newfieldNumber);
+ }
+ OnlFormHead destFieldHead = resolveHead(destField.getHeadId(), headCache);
+ MetaColumn column = new MetaColumn();
+ column.setMetaTable(destFieldHead.getTableName());
+ column.setColumnName(destField.getFieldName());
+ column.setMain(destFieldHead.getTableName().equals(destFormHead.getTableName()));
+ column.setSerialNumber(serialNumber);
+ return column;
+ }
- Object ob = clazz.newInstance();
- ctxMethod.invoke(ob, srcObjectValue, destObjectValue, botpRule);
- Method exeMethod = superClass.getDeclaredMethod(method);
- exeMethod.invoke(ob);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
+ /**
+ * 加载批次内全部源单(表头 + 全部分录行)。
+ *
+ * @param plan 映射计划。
+ * @param srcFormHead 源单元数据。
+ * @param srcBillIds 源单 id 集合。
+ * @return 源单数据列表。
+ */
+ private List loadSourceBills(ConvertMappingPlan plan, OnlFormHead srcFormHead, Set srcBillIds) {
+ List bills = new ArrayList<>(srcBillIds.size());
+ for (String billId : srcBillIds) {
+ ObjectValue bill = querySourceBill(plan, srcFormHead, billId);
+ if (bill == null) {
+ throw new BotpMappingException("源单不存在,表名=" + srcFormHead.getTableName() + ",id=" + billId);
}
+ bills.add(bill);
}
+ return bills;
}
/**
- * 新增数据
+ * 查询一条源单:用到的源表与源列由映射计划决定。
*
- * @param btpTransformResul
- * @param metaTable
+ * @param plan 映射计划。
+ * @param srcFormHead 源单元数据。
+ * @param billId 源单 id。
+ * @return 源单数据。
*/
- private void addNew(BtpTransformResult btpTransformResult, MetaTable metaTable) {
-
- try {
- ObjectValue destBillData = btpTransformResult.getBillDataList().getObject(0);
- ormGenDataSourceUtil.addNew(metaTable.getTableName(), destBillData);
- this.saveRelation(btpTransformResult.getBillRelationList().get(0), destBillData);
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
+ private ObjectValue querySourceBill(ConvertMappingPlan plan, OnlFormHead srcFormHead, String billId) {
+ Set mainColumns = new LinkedHashSet<>();
+ Map> entryColumns = new LinkedHashMap<>();
+ for (List configs : plan.getColumnConfigs().values()) {
+ for (ConvertColumnConfig config : configs) {
+ if (config.getColumnName() == null) {
+ continue;
+ }
+ if (config.isMain()) {
+ mainColumns.add(config.getColumnName());
+ } else {
+ entryColumns.computeIfAbsent(config.getTableName(), k -> new LinkedHashSet<>()).add(config.getColumnName());
+ }
+ }
}
-
+ return querySourceBill(mainColumns, entryColumns, srcFormHead.getTableName(), billId);
}
- private void saveRelation(BillRelation billRelation, ObjectValue destBillData) {
-
- ConvertRelation convertRelation = new ConvertRelation();
- convertRelation.setId(billRelation.getId());
- convertRelation.setConvertRuleId(billRelation.getConvertRuleId());
- convertRelation.setSourceId(billRelation.getSourceId());
- convertRelation.setSourceNumber(billRelation.getSourceNumber());
- convertRelation.setTargetId(String.valueOf(destBillData.getPkValue()));
- convertRelation.setTargetNumber(billRelation.getTargetNumber());
- convertRelation.setCreateUserId(TokenData.takeFromRequest().getUserId());
- convertRelation.setCreateTime(new Date());
- convertRelation.setUpdateUserId(TokenData.takeFromRequest().getUserId());
- convertRelation.setUpdateTime(new Date());
- convertRelationMapper.insert(convertRelation);
-
- for (BillRelationEntry billRelationEntry : billRelation.getBillRelationEntryList()) {
- ConvertRelationEntry convertRelationEntry = new ConvertRelationEntry();
- convertRelationEntry.setId(billRelationEntry.getId());
- convertRelationEntry.setConvertRuleId(billRelationEntry.getConvertRuleId());
- convertRelationEntry.setSourceEntryId(billRelationEntry.getSourceEntryId());
- convertRelationEntry.setSourceEntryNumber(billRelationEntry.getSourceEntryNumber());
- convertRelationEntry.setSourceId(billRelationEntry.getSourceId());
- convertRelationEntry.setSourceNumber(billRelationEntry.getSourceNumber());
- convertRelationEntry.setTargeEntryId(billRelationEntry.getTargeEntryId());
- convertRelationEntry.setTargetId(String.valueOf(destBillData.getPkValue()));
- convertRelationEntry.setTargeEntryNumber(billRelationEntry.getTargeEntryNumber());
- convertRelationEntry.setTargetNumber(billRelationEntry.getTargetNumber());
- convertRelationEntry.setCreateUserId(TokenData.takeFromRequest().getUserId());
- convertRelationEntry.setCreateTime(new Date());
- convertRelationEntry.setUpdateUserId(TokenData.takeFromRequest().getUserId());
- convertRelationEntry.setUpdateTime(new Date());
- convertRelationEntryMapper.insert(convertRelationEntry);
+ /**
+ * 按「主表列 + 分录列」查询一条源单(表头字段平铺,分录为 ObjectCollection)。
+ *
+ * @param mainColumns 主表列。
+ * @param entryColumns 分录表 → 分录列。
+ * @param srcTable 源单主表表名。
+ * @param billId 源单 id。
+ * @return 源单数据。
+ */
+ private ObjectValue querySourceBill(Set mainColumns, Map> entryColumns, String srcTable, String billId) {
+ Selector selector = new Selector();
+ Set columns = new LinkedHashSet<>(mainColumns);
+ columns.add("id");
+ for (String column : columns) {
+ selector.getList().add(new SelectorItem(column));
}
-
+ for (Map.Entry> entry : entryColumns.entrySet()) {
+ for (String column : entry.getValue()) {
+ selector.getList().add(new SelectorItem(entry.getKey() + "." + column));
+ }
+ }
+ return ormGenDataSourceUtil.queryOne(srcTable, Long.valueOf(billId), selector);
}
/**
- * 插入数据
+ * 加载源单完整数据,供选单过滤 / 规则启用条件求值使用。
+ *
+ * 带上映射涉及的源分录,条件里引用分录字段才能取到值——只查表头的话,
+ * 「明细里有某物料」这类条件永远为假。
*
- * @param tableName
- * @param columnNames
- * @param columnValueList
+ * @param mappings 字段映射分录。
+ * @param srcFormHead 源单元数据。
+ * @param srcBillIds 源单 id 集合。
+ * @return 源单数据列表,查不到的源单不返回。
*/
- private ObjectSqlData doInsert(String tableName, String columnNames, List