@mldong/jeeflow 1.8.64 → 1.8.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { TypeStart, TypeEnd, TypeTask, TypeDecision, TypeFork, TypeJoin, TypeCustom, KnownNodeTypes, TaskFormPrefix, ProcessInstance, InstanceState, TaskState, SubmitType, } from './model.js';
2
+ import { TypeStart, TypeEnd, TypeTask, TypeDecision, TypeFork, TypeJoin, TypeCustom, KnownNodeTypes, TaskFormPrefix, ProcessInstance, InstanceState, TaskState, SubmitType, TaskType, PerformType, } from './model.js';
3
3
  import { attachCreated, buildScopes, createTaskAt, executeReapply, mergeReady, newContext, parseMode, reapplyOf, RETURN_TO_SOURCE, scopesOf, stripReserved, withInstanceLock, VAR_BRANCH_CTX, VAR_REAPPLY_CTX, } from './reapply.js';
4
4
  // 后加签(可重复):判据/账本/解析期校验的落点在本模块,形状基准=java `AddSignSupport`
5
5
  import { AddSignRoundKey, abandonDoingOnNode, allowAddSignOf, appendHistory, checkFlowConfig, hasDoingOnNode, operators as addSignOperators, roundOf as addSignRoundOf, validateSubmission, } from './addsign.js';
@@ -9,6 +9,10 @@ import { allowRecallOf, appendRecallHistory, inRoster, isPrivilegedOperator, MSG
9
9
  // 动态会签(issues/247,征询模式):成员行识别/计数/投影在 collect.ts,建成员行走本文件的
10
10
  // 建单腿(`createCollectMemberRows`),推进闸复用上面后加签那一条
11
11
  import { dynamicCountersignOf, KeyAddSignReason } from './collect.js';
12
+ // 动态协办(issues/253):协办行识别/计数/投影/账本的纯函数家族在 aidant.ts,派生腿与
13
+ // 推进闸/等待闸/清场腿在本文件(形状基准=java `core/AidantSupport` +
14
+ // `JeeflowEngineImpl.aidantTask`/`completeAidantWithoutDrive`/`TaskModel.abandonAidantOnLeave`)
15
+ import { aidantRows, appendAbandonHistory, appendAidantHistory, filterOutAidant, gateWait, isAidantRow, lastRound as aidantLastRound, KeyAidantReason, KeyAidantWait, MSG_DUPLICATE as MSG_AIDANT_DUPLICATE, MSG_NO_ACTORS as MSG_AIDANT_NO_ACTORS, MSG_NO_PERMISSION as MSG_AIDANT_NO_PERMISSION, MSG_NO_RECURSION as MSG_AIDANT_NO_RECURSION, MSG_NOT_DOING as MSG_AIDANT_NOT_DOING, MSG_TASK_NOT_FOUND as MSG_AIDANT_TASK_NOT_FOUND, } from './aidant.js';
12
16
  // issues/141 G2:cc 写侧判重的 java `default` 方法在 TS 里的对应物(第三方仓储未实现判重 SPI 时兜旧行为)
13
17
  // issues/141 G10:归属值单值/集合归一的**那一份**判据(漏斗层与写侧层共用;issues/142 B 批
14
18
  // 按 spec 06 §2.11 从"只挂 cc 一支"升为 cc 腿与任务腿共用同一枚,见 spi.normalizeActors)
@@ -133,6 +137,10 @@ export class EngineImpl {
133
137
  registry;
134
138
  // issues/116:委托代理自动生效——内置能力,注入查询源后默认开启
135
139
  surrogateRepo;
140
+ /** 时限动作凭证(spec 04):不传=全部时限动作静默跳过 */
141
+ timeActionSink;
142
+ /** 引擎时钟(spec 04):不传=系统钟 */
143
+ clock = () => new Date();
136
144
  surrogateOn = true;
137
145
  constructor(repo, userProv, idGen, exprEval, opts) {
138
146
  this.repo = repo;
@@ -143,6 +151,10 @@ export class EngineImpl {
143
151
  this.surrogateRepo = opts.surrogateRepository;
144
152
  if (opts?.surrogateEnabled !== undefined)
145
153
  this.surrogateOn = opts.surrogateEnabled;
154
+ if (opts?.timeActionSink !== undefined)
155
+ this.timeActionSink = opts.timeActionSink;
156
+ if (opts?.clock !== undefined)
157
+ this.clock = opts.clock;
146
158
  }
147
159
  /**
148
160
  * issues/116:注入/摘除委托查询源(ProcessExtRepository 或任何实现 getSurrogate 的对象)。
@@ -395,7 +407,7 @@ export class EngineImpl {
395
407
  const vars = { ...args };
396
408
  await this.addUserInfo(operator, vars);
397
409
  this.addAutoGenTitle(def.displayName, vars);
398
- const now = new Date();
410
+ const now = this.now();
399
411
  // 聚合根工厂创建实例
400
412
  const inst = ProcessInstance.create(this.nextId(), defineId, operator, vars, now);
401
413
  // issues/137 A · 裁定 A(批二 §3-4)· **实例级 expire_time 的唯一写点**:
@@ -435,6 +447,10 @@ export class EngineImpl {
435
447
  async executeProcessTaskInner(taskId, operator, args = {}) {
436
448
  args = stripReserved(args);
437
449
  const pre = await this.repo.findTaskById(taskId);
450
+ // issues/253 推进闸:协办行(task_type=1)办结不产生执行对象、不跑输出变迁
451
+ if (pre && pre.taskState === TaskState.Doing && isAidantRow(pre)) {
452
+ return await this.completeAidantWithoutDrive(taskId, operator, args);
453
+ }
438
454
  if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables))
439
455
  return await executeReapply(this, pre, operator, args);
440
456
  const { task, inst, flow, vars, args: execArgs } = await this.prepareExecuteTask(taskId, operator, args);
@@ -447,7 +463,7 @@ export class EngineImpl {
447
463
  await this.handleCcActors(inst.id, operator, args[KeyCcActors]);
448
464
  return (await this.repo.findInstanceById(inst.id));
449
465
  };
450
- const now = new Date();
466
+ const now = this.now();
451
467
  const curNode = findNode(flow, task.taskName);
452
468
  if (curNode) {
453
469
  // 1.8.0:任务完成节点自身的后置拦截器(SYNC 同步演进——任务节点推进更新状态/字段)。
@@ -472,7 +488,8 @@ export class EngineImpl {
472
488
  const csVeto = !!ct && csCond.toUpperCase() === 'ONE_VOTE_VETO' &&
473
489
  Number(vars[KeySubmitType]) === Number(SubmitType.CountersignDisagree);
474
490
  if (ct === 'SEQUENTIAL' && !csVeto) {
475
- const doing = await this.repo.findDoingTasks(inst.id);
491
+ // issues/253:协办行(task_type=1)不是表决票,不算"本节点还有未完成待办"
492
+ const doing = filterOutAidant(await this.repo.findDoingTasks(inst.id));
476
493
  if (doing.length === 0) {
477
494
  const [actors, lc] = getCsState(vars, curNode.id);
478
495
  if (actors && lc + 1 < actors.length) {
@@ -496,6 +513,7 @@ export class EngineImpl {
496
513
  applyNodeExpireTime(nt, curNode.properties?.expireTime, inst.variables, now);
497
514
  await this.repo.saveTask(nt);
498
515
  this.createdScope.getStore()?.push(nt);
516
+ await this.scheduleTimeActions(nt, curNode, inst);
499
517
  // PROCESS_TASK_START:顺序会签推进新任务落库后 fire(对齐 Java CreateTaskHandler / Rust)
500
518
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: curNode.id, operator, actors: [...nt.actorIds] });
501
519
  return finishExecute();
@@ -514,7 +532,9 @@ export class EngineImpl {
514
532
  // buildCountersignVars:total=该节点全部成员行、activate=DOING、completed=已完成
515
533
  // (读 inst.tasks:prepareExecuteTask 里 completeTask+syncTaskToAggregate 已把
516
534
  // 本单同步进聚合,计数是新鲜的)。
517
- const members = inst.tasks.filter(t => t.taskName === curNode.id);
535
+ // issues/253:会签合并判据显式排除协办行(task_type=1)——snaker 按同节点同名行
536
+ // 全算会把协办行误当表决票挡住合并(规范 04「不计入会签合并计数」)。
537
+ const members = inst.tasks.filter(t => t.taskName === curNode.id && !isAidantRow(t));
518
538
  const evalVars = {
519
539
  ...vars,
520
540
  nrOfInstances: members.length,
@@ -533,7 +553,8 @@ export class EngineImpl {
533
553
  // merged ⇒ 落穿到下面的 abandon+跟进边(与"全部完成"走同一出口)
534
554
  }
535
555
  else {
536
- const doing = await this.repo.findDoingTasks(inst.id);
556
+ // issues/253:协办行不是表决票(同上,合并判据显式排除 task_type=1)
557
+ const doing = filterOutAidant(await this.repo.findDoingTasks(inst.id));
537
558
  if (doing.length > 0)
538
559
  return finishExecute();
539
560
  }
@@ -571,6 +592,11 @@ export class EngineImpl {
571
592
  // 废弃该节点剩余 DOING 任务(对齐内置引擎 abandonProcessTask):
572
593
  // SEQUENTIAL 逐人创建天然 no-op;PARALLEL 全员预创建,否决时废弃其余成员
573
594
  // (刚完成者已 Done 不会误伤)。逐条持久化并回写聚合副本(E25:防 updateInstance 级联回写旧状态)
595
+ // issues/253:离开节点先清场未办结协办行(废弃+往主办行账本记废弃),再清剩余会签行——
596
+ // 顺序不能反,先被下面循环置 99 的协办行就记不上账了(java CountersignHandler 同序)。
597
+ // 本点覆盖四档(会签 merged/加签 merged/征询 merged/普通放行出边)=java
598
+ // TaskModel.abandonAidantOnLeave 的四个调用位;上面各"留在本节点"的早返回分支不调。
599
+ await this.abandonAidantOnNode(inst, curNode.id, operator);
574
600
  if (ct) {
575
601
  const remaining = await this.repo.findDoingTasks(inst.id, [curNode.id]);
576
602
  for (const t of remaining) {
@@ -599,15 +625,22 @@ export class EngineImpl {
599
625
  }
600
626
  async executeAndJumpToEndInner(taskId, operator, args = {}) {
601
627
  const pre = await this.repo.findTaskById(taskId);
628
+ // issues/253 推进闸:协办行拒绝同样不驱动流程(任何 submitType 都只办结自己那一行)
629
+ if (pre && pre.taskState === TaskState.Doing && isAidantRow(pre)) {
630
+ return await this.completeAidantWithoutDrive(taskId, operator, args);
631
+ }
602
632
  if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
603
633
  throw new Error("带重提直返标记的申请待办不允许拒绝,只接受重新提交(submitType=5)");
604
634
  }
605
635
  const { task, inst, flow } = await this.prepareExecuteTask(taskId, operator, args);
606
636
  // 拒绝结束:本节点未完成的加签任务一并废弃,不留孤儿待办(规范 04 · 后加签/语义边界表)
607
- await this.abandonAddSignDoing(flow, inst, task.taskName, new Date());
637
+ // issues/253:离开节点先清场未办结协办行(废弃+账本记废弃),再走后加签/征询的既有废弃腿
638
+ await this.abandonAidantOnNode(inst, task.taskName, operator);
639
+ await this.abandonAddSignDoing(flow, inst, task.taskName, this.now());
608
640
  // 门面 submitType=2 REJECT 唯一入口(对齐 Java executeAndJumpToEnd 语义)
609
- inst.reject(new Date());
641
+ inst.reject(this.now());
610
642
  await this.repo.updateInstance(inst);
643
+ await this.cancelInstanceTimeActions(inst.id);
611
644
  // §11.3 code 2:拒绝也是"实例进入终态"(state=45 落库后 fire,靠载荷 state 与办结分家);
612
645
  // "任务被退回"这一事实另由 prepareExecuteTask 的 TASK_REJECT(6) 承载(场景 31/32 两支并存)
613
646
  await this.notifyInstanceEnd(inst, operator);
@@ -626,6 +659,11 @@ export class EngineImpl {
626
659
  async executeAndJumpTaskInner(taskId, operator, args = {}, targetTaskName) {
627
660
  // 带直返上下文的进行中申请待办只接受重新提交(5):命名跳转/退回上一步都在改状态前拒绝
628
661
  const pre = await this.repo.findTaskById(taskId);
662
+ // issues/253 推进闸:四入口同闸(照 snaker,别只堵 execute 一路)——协办行跳转/退回
663
+ // 同样不驱动流程,且必须排在血缘/目标守卫之前,免得协办行被守卫的文案误拦。
664
+ if (pre && pre.taskState === TaskState.Doing && isAidantRow(pre)) {
665
+ return await this.completeAidantWithoutDrive(taskId, operator, args);
666
+ }
629
667
  if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
630
668
  throw new Error("带重提直返标记的申请待办不允许跳转,只接受重新提交(submitType=5)");
631
669
  }
@@ -639,6 +677,8 @@ export class EngineImpl {
639
677
  await this.checkJumpTargetExists(pre, targetTaskName);
640
678
  }
641
679
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
680
+ // issues/253:跳转/退回离开本节点 ⇒ 未办结协办行随废弃腿清场(账本记废弃)
681
+ await this.abandonAidantOnNode(inst, task.taskName, operator);
642
682
  if (!targetTaskName) {
643
683
  // issues/121 P2:ROLLBACK 走血缘版——复活 task.parentTaskId 指的那条历史行,
644
684
  // 参与者=该行办结人(首任务节点行取该行 u_userId)。无血缘/守卫不过显式报错,
@@ -674,6 +714,10 @@ export class EngineImpl {
674
714
  args = stripReserved(args);
675
715
  // 校验放在任何状态变更之前:带直返上下文的申请待办不得再次退回
676
716
  const pre = await this.repo.findTaskById(taskId);
717
+ // issues/253 推进闸:协办行退回发起人同样不驱动流程
718
+ if (pre && pre.taskState === TaskState.Doing && isAidantRow(pre)) {
719
+ return await this.completeAidantWithoutDrive(taskId, operator, args);
720
+ }
677
721
  if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
678
722
  throw new Error("带重提直返标记的申请待办不允许再次退回,只接受重新提交(submitType=5)");
679
723
  }
@@ -689,7 +733,9 @@ export class EngineImpl {
689
733
  }
690
734
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
691
735
  // 退回发起人:本节点未完成的加签任务一并废弃,不留孤儿待办(规范 04 · 后加签/语义边界表)
692
- await this.abandonAddSignDoing(flow, inst, task.taskName, new Date());
736
+ // issues/253:退回发起人离开本节点 ⇒ 未办结协办行随废弃腿清场(账本记废弃)
737
+ await this.abandonAidantOnNode(inst, task.taskName, operator);
738
+ await this.abandonAddSignDoing(flow, inst, task.taskName, this.now());
693
739
  if (direct) {
694
740
  if (sourceNode.type !== TypeTask)
695
741
  throw new Error(`节点[${sourceNode.id}]不是普通审批任务,不支持重提直返`);
@@ -753,6 +799,9 @@ export class EngineImpl {
753
799
  return resurrected;
754
800
  }
755
801
  async recallTaskInner(taskId, operator) {
802
+ // 实例级事务排他(spec 04 · 并发保护):先锁再读
803
+ const preForLock = await this.repo.findTaskById(taskId);
804
+ await this.lockInstance(preForLock?.processInstanceId);
756
805
  // 判据 1:目标行存在且已办结(不存在/进行中/已废弃同档)
757
806
  const target = await this.repo.findTaskById(taskId);
758
807
  if (!target || !target.isFinished())
@@ -778,7 +827,7 @@ export class EngineImpl {
778
827
  // 内存与 SQL 两仓同形状)
779
828
  const doingDescendants = validateWindow(await this.repo.findHistoryTasks(inst.id), target);
780
829
  // ── 判据全过,以下才允许写 ──
781
- const now = new Date();
830
+ const now = this.now();
782
831
  // 写 1:下游全部 DOING 行废弃(后加签/征询成员行、并行分支多支自然覆盖;updateUser 记真实撤回人,
783
832
  // 照 java `ProcessTask.abandon(operator)`/py `t.updateUser = operator` 同尺)
784
833
  for (const t of doingDescendants) {
@@ -798,6 +847,7 @@ export class EngineImpl {
798
847
  nt.actorIds = eff;
799
848
  await this.repo.saveTask(nt);
800
849
  this.createdScope.getStore()?.push(nt);
850
+ await this.scheduleTimeActions(nt, node, inst);
801
851
  // 码 3:复活行的待办另走既有建单腿(issues/246 参考实现 14674d7 补的那一腿——只 fire 10
802
852
  // 不 fire 3 ⇒ 集成方的待办角标/站内信拿不到这一手新待办)
803
853
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id,
@@ -815,12 +865,169 @@ export class EngineImpl {
815
865
  nodeId: target.taskName, operator });
816
866
  return nt;
817
867
  }
868
+ // ─── 动态协办(issues/253)─────────────────────────────────────────────────
869
+ /**
870
+ * 动态协办(issues/253,规范 04 · 动态协办):主办把"这活"交给别人干——按人派生
871
+ * `task_type=1` 协办子行,**主办行原样保留 DOING**,节点推进仍由主办行办结触发。
872
+ *
873
+ * 判据全部排在任何状态变更之前(报错即零写入——与后加签/征询/撤回同一规矩):
874
+ * 任务存在 → 禁递归(协办行不能再派生)→ 主办行 DOING → actorIds 非空 → 名册鉴权
875
+ * (auto/admin 例外)→ 逐人去重(该人已有本主办行下未办结协办行)。
876
+ * 落库顺序:协办行既有建单腿(委托并入 → saveTask → 码 3)→ 主办行盖 wait 开关+账本 updateTask。
877
+ * 建单形状照征询成员行腿(`createCollectMemberRows`),另落 task_type=1/performType=NORMAL。
878
+ */
879
+ async aidantTask(taskId, actorIds, reason, waitCompletion, operator) {
880
+ const created = [];
881
+ const pre = await this.repo.findTaskById(taskId);
882
+ // 同实例串行化(与 execute/recall 同口径):「判协办行 DOING → 建协办行」在同一临界区
883
+ await withInstanceLock(this, pre?.processInstanceId, () => this.createdScope.run(created, () => this.inTx(() => this.aidantTaskInner(taskId, actorIds, reason, waitCompletion, operator))));
884
+ return created;
885
+ }
886
+ async aidantTaskInner(taskId, actorIds, reason, waitCompletion, operator) {
887
+ let host = await this.repo.findTaskById(taskId);
888
+ await this.lockInstance(host?.processInstanceId);
889
+ if (!host)
890
+ throw new Error(MSG_AIDANT_TASK_NOT_FOUND);
891
+ // 禁递归:协办行携带派生参数 ⇒ 报错(规范 04 派生规则 4)
892
+ if (isAidantRow(host))
893
+ throw new Error(MSG_AIDANT_NO_RECURSION);
894
+ if (!host.isDoing())
895
+ throw new Error(MSG_AIDANT_NOT_DOING);
896
+ const actors = normalizeActors(actorIds);
897
+ if (actors.length === 0)
898
+ throw new Error(MSG_AIDANT_NO_ACTORS);
899
+ // 以参与者表为判据(聚合副本可能滞后于加签/转办的增量写入,与 transfer 同源)
900
+ const roster = await this.repo.findTaskActors(taskId);
901
+ if (!isPrivilegedOperator(operator) && !roster.includes(operator)) {
902
+ throw new Error(MSG_AIDANT_NO_PERMISSION);
903
+ }
904
+ const inst = await this.repo.findInstanceById(host.processInstanceId);
905
+ if (!inst)
906
+ throw new Error('流程实例不存在');
907
+ // issues/249 同一课:账本必须盖在聚合内的同一对象上——findTaskById 在 SQL 仓是独立副本,
908
+ // 后续 updateInstance 的级联会拿聚合里没账本的旧副本抹掉它。这里重指到聚合内那份。
909
+ const inAgg = (inst.tasks ?? []).find(t => t.id === taskId);
910
+ if (inAgg)
911
+ host = inAgg;
912
+ const def = await this.repo.findDefineById(inst.defineId);
913
+ if (!def)
914
+ throw new Error('流程定义不存在');
915
+ // loadFlowModel 内含解析期硬校验(节点级 taskType=1 禁配等),与 java ModelParser 同位
916
+ const flow = loadFlowModel(def.content);
917
+ const node = findNode(flow, host.taskName);
918
+ if (!node || node.type !== TypeTask)
919
+ throw new Error(MSG_AIDANT_NOT_DOING);
920
+ // 去重:该人已有本主办行下**未办结**协办行 ⇒ 报错(规范 04 派生规则 5)
921
+ const existing = aidantRows(inst.tasks ?? [], host);
922
+ for (const actor of actors) {
923
+ for (const t of existing) {
924
+ if (t.isDoing() && (t.actorIds ?? []).includes(actor))
925
+ throw new Error(MSG_AIDANT_DUPLICATE);
926
+ }
927
+ }
928
+ // ── 判据全过,以下才允许写 ──
929
+ const now = this.now();
930
+ const round = aidantLastRound(host) + 1;
931
+ const isFirst = this.isFirstTaskNode(flow, node);
932
+ const form = node.properties?.form ?? '';
933
+ const agents = await this.surrogateAgents(actors, await this.surrogateProcessName(flow, inst));
934
+ const created = [];
935
+ for (const actor of actors) {
936
+ const nt = inst.createTask(this.nextId(), node.id, node.text?.value ?? '', actor, operator, form, now, host.id, isFirst);
937
+ nt.taskType = TaskType.Secondary;
938
+ nt.performType = PerformType.Normal;
939
+ const eff = mergeAgents([actor], agents);
940
+ if (eff.length > 1)
941
+ nt.actorIds = eff;
942
+ // 分支归属与每一次普通建单同一条腿(照征询成员行):并行范围内的协办行继承父任务归属
943
+ nt.variables[VAR_BRANCH_CTX] = buildScopes(flow, node.id, host.variables, host.id, nt.id);
944
+ if (reason !== '')
945
+ nt.variables[KeyAidantReason] = reason;
946
+ applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now);
947
+ await this.repo.saveTask(nt);
948
+ this.createdScope.getStore()?.push(nt);
949
+ await this.scheduleTimeActions(nt, node, inst, false);
950
+ await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
951
+ taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
952
+ created.push(nt);
953
+ }
954
+ // 等待闸开关+账本落主办行(主办不办结,变量合并序保证账本活到办结后)
955
+ host.variables[KeyAidantWait] = !!waitCompletion;
956
+ appendAidantHistory(host, operator, actors, round, reason ?? '', now);
957
+ // ⚠️ 严禁覆写任务 actor_id/operator 列(转办那条 ⚠️ 同尺):进行中任务该列恒无值是家族
958
+ // 不变量,派生协办不改主办行的办理人归属,审计由 update_user+账本 operator 承载。
959
+ host.updateUser = operator;
960
+ host.updateTime = now;
961
+ await this.repo.updateTask(host);
962
+ syncTaskToAggregate(inst, host);
963
+ return created;
964
+ }
965
+ /**
966
+ * 协办行办结的**推进闸**(issues/253,规范 04「推进闸与等待闸」;参照 snaker
967
+ * `SnakerEngineImpl.execute` 的「协办任务完成不产生执行对象」):只完成任务行
968
+ * (`prepareExecuteTask` 内含 completeTask/updateTask/fire 码 5 或 6),
969
+ * **不跑节点执行、不跑输出变迁**,本次动作产出列表为空(无 saveTask ⇒ ALS sink 空)。
970
+ *
971
+ * 四入口同闸:executeProcessTask/executeAndJumpTask/executeAndJumpToEnd/
972
+ * executeAndJumpToFirstTaskNode——协办行任何 submitType 都不得驱动流程。
973
+ */
974
+ async completeAidantWithoutDrive(taskId, operator, args) {
975
+ const { inst } = await this.prepareExecuteTask(taskId, operator, args);
976
+ return inst;
977
+ }
978
+ /**
979
+ * 离开节点时清场未办结协办行(规范 04:waitCompletion=false 时主办可随时推进,未办结协办行
980
+ * 随废弃腿清场、账本记废弃,不留孤儿待办)。
981
+ *
982
+ * 只对协办行(task_type=1)动手,且**不要求节点开任何开关**——协办无节点开关,普通节点上的
983
+ * 协办行同样要清(这是与 `abandonAddSignDoing` 的关键差别,后者有双开关守卫)。按 parent 分组,
984
+ * 废弃事实追加到各自主办行的账本上。幂等:已废弃(99)/已办结(20) 的行不再命中,重复调用不重复
985
+ * 记账。返回实际废弃的行数。
986
+ */
987
+ async abandonAidantOnNode(inst, nodeName, operator) {
988
+ if (!inst || !nodeName)
989
+ return 0;
990
+ // parent → 该主办行下待清场的协办行(Map 保插入序=行序,照 java LinkedHashMap)
991
+ const byHost = new Map();
992
+ for (const t of inst.tasks ?? []) {
993
+ if (t.taskName === nodeName && t.isDoing() && isAidantRow(t)) {
994
+ const key = t.parentTaskId ?? '0';
995
+ const bucket = byHost.get(key);
996
+ if (bucket)
997
+ bucket.push(t);
998
+ else
999
+ byHost.set(key, [t]);
1000
+ }
1001
+ }
1002
+ const now = this.now();
1003
+ let abandoned = 0;
1004
+ for (const [parentId, rows] of byHost) {
1005
+ const actors = [];
1006
+ for (const t of rows) {
1007
+ t.abandon(now, operator); // java abandon(operator) 同尺:update_user 回写真实清场人
1008
+ await this.repo.updateTask(t);
1009
+ syncTaskToAggregate(inst, t);
1010
+ actors.push(t.actorIds && t.actorIds.length > 0 ? t.actorIds[0] : null);
1011
+ abandoned++;
1012
+ }
1013
+ const host = (inst.tasks ?? []).find(t => t.id === parentId);
1014
+ if (host) {
1015
+ appendAbandonHistory(host, operator, actors, aidantLastRound(host), now);
1016
+ await this.repo.updateTask(host);
1017
+ syncTaskToAggregate(inst, host);
1018
+ }
1019
+ }
1020
+ return abandoned;
1021
+ }
818
1022
  // ─── Execute 公共序言(对齐 Java prepareExecution)──────────────────────────
819
1023
  // 执行公共序言(对齐 Java prepareExecution):权限校验 → f_ 字段权限过滤 →
820
1024
  // 完成任务(子实体状态转换 + 实例变量合并,经 updateInstance 级联落库)→
821
1025
  // 返回流程模型 + 合并后执行变量。Java jump 路径不废弃其余 DOING 任务
822
1026
  // (会签兄弟任务不受影响),此处保持一致。
823
1027
  async prepareExecuteTask(taskId, operator, args) {
1028
+ // 实例级事务排他(spec 04 · 并发保护):先锁再读,堵"读后锁前"的二次推进窗口
1029
+ const pre = await this.repo.findTaskById(taskId);
1030
+ await this.lockInstance(pre?.processInstanceId);
824
1031
  const { task, inst } = await this.loadAndCheck(taskId, operator);
825
1032
  // issues/26:办理提交的 f_ 字段按任务节点字段权限过滤(只读/隐藏不入变量)
826
1033
  const def = await this.repo.findDefineById(inst.defineId);
@@ -835,18 +1042,24 @@ export class EngineImpl {
835
1042
  // 合并两面立法排除(不传播);撤回校验仍以现读定义为权威,快照仅供前端预判;
836
1043
  // 出口只投已办行。
837
1044
  stampAllowRecall(args, findNode(flow, task.taskName));
1045
+ // issues/253 等待闸:waitCompletion=true 的主办行办结前判"不存在 DOING 协办行",
1046
+ // 未齐 ⇒ 逐字文案报错、零写入。同样必须排在 completeTask 之前(内存仓储无回滚)。
1047
+ // 协办行自身不受本闸约束(它办结本来就不驱动流程);缺省 false 原样放行。
1048
+ gateWait(inst.tasks ?? [], task);
838
1049
  // issues/97:捕获原始实例变量(start 注入的发起人 u_*)——操作人 u_* 只进执行上下文
839
1050
  // 与任务行,不得整体写回实例(对齐 Java completeTask=putAll(args),args 不含 u_*)。
840
1051
  const baseVars = inst.variables;
841
1052
  const vars = { ...baseVars, ...task.variables, ...args };
842
1053
  await this.addUserInfo(operator, vars);
843
- const now = new Date();
1054
+ const now = this.now();
844
1055
  // §11.2 原则 2「码粗、载荷细」+场景 30/31 互斥:本次动作是"办掉"还是"退回"由 submitType 定,
845
1056
  // 同一动作只发其中一支(旧形状无论 submitType 一律 fire TaskComplete 即本案病灶)
846
1057
  const submitType = normalizeSubmitType(vars[KeySubmitType]);
847
1058
  // 聚合根:完成任务(子实体状态转换 + 实例变量合并)
848
1059
  inst.completeTask(task, operator, vars, now);
849
1060
  await this.repo.updateTask(task);
1061
+ // 时限动作联动(spec 04 · 写路径):任务离开 DOING ⇒ 取消该任务 pending 提醒/自动行
1062
+ await this.cancelTaskTimeActions(task.id);
850
1063
  // v1.0.1:updateInstance 级联持久化依赖聚合内任务副本为最新状态,
851
1064
  // completeTask 改的是外部任务对象,需同步回聚合根
852
1065
  syncTaskToAggregate(inst, task);
@@ -855,6 +1068,10 @@ export class EngineImpl {
855
1068
  await this.repo.updateInstance(inst);
856
1069
  // §11.2 原则 3:任务行与实例**都落库之后**才 fire(旧形状排在 updateInstance 之前,
857
1070
  // 监听器反查实例读到旧状态——与 issues/121/126 两轮"回写序"同族)
1071
+ // 完成回调(spec 04 · CALLBACK):只对应 TASK_COMPLETE 事实(退回族不触发)
1072
+ if (!isRejectSubmitType(submitType)) {
1073
+ await this.insertCallbackAction(task, findNode(flow, task.taskName));
1074
+ }
858
1075
  await this.fireEvent({
859
1076
  type: isRejectSubmitType(submitType) ? EventType.TaskReject : EventType.TaskComplete,
860
1077
  instanceId: inst.id, taskId: task.id, nodeId: task.taskName, operator, submitType,
@@ -959,7 +1176,7 @@ export class EngineImpl {
959
1176
  async rollbackToParent(flow, inst, task, operator) {
960
1177
  const { his, prev, actor, isFirst } = await this.checkRejectable(flow, inst, task);
961
1178
  // 取时基准只取一次:本行 createTime 与 expire_time 共用同一个 Date(写点内不另起时钟)
962
- const now = new Date();
1179
+ const now = this.now();
963
1180
  const nt = inst.createTask(this.nextId(), prev.id, prev.text.value, actor, his.createUser ?? '', prev.properties?.form ?? '', now, his.parentTaskId ?? '0', isFirst, his.performType);
964
1181
  // 复活行只带数据类键:tf_*(上次表单提交)与 csv_*/会签簿记都是"上次提交"的残留
965
1182
  nt.variables = { ...lineageVars(his.variables), isFirstTaskNode: isFirst };
@@ -973,6 +1190,7 @@ export class EngineImpl {
973
1190
  nt.actorIds = eff;
974
1191
  await this.repo.saveTask(nt);
975
1192
  this.createdScope.getStore()?.push(nt);
1193
+ await this.scheduleTimeActions(nt, prev, inst);
976
1194
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
977
1195
  taskId: nt.id, nodeId: prev.id, operator, actors: [...nt.actorIds] });
978
1196
  }
@@ -1013,6 +1231,7 @@ export class EngineImpl {
1013
1231
  applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now); // 加签续建
1014
1232
  await this.repo.saveTask(nt);
1015
1233
  this.createdScope.getStore()?.push(nt);
1234
+ await this.scheduleTimeActions(nt, node, inst);
1016
1235
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
1017
1236
  taskId: nt.id, nodeId, operator, actors: [...nt.actorIds] });
1018
1237
  }
@@ -1058,6 +1277,7 @@ export class EngineImpl {
1058
1277
  applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now);
1059
1278
  await this.repo.saveTask(nt);
1060
1279
  this.createdScope.getStore()?.push(nt);
1280
+ await this.scheduleTimeActions(nt, node, inst);
1061
1281
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
1062
1282
  taskId: nt.id, nodeId, operator, actors: [...nt.actorIds] });
1063
1283
  created.push(nt);
@@ -1085,12 +1305,77 @@ export class EngineImpl {
1085
1305
  * 未配置查询源、显式关闭、无参与人 → 空映射(= 原样参与者,不打断建单);
1086
1306
  * 单条查询异常只记录不传播(委托是增强能力,建单主流程不得被拖崩)。
1087
1307
  */
1308
+ // ─── 任务时限动作(spec 04 · 零 schema)────────────────────────────────
1309
+ now() {
1310
+ return this.clock();
1311
+ }
1312
+ async lockInstance(instanceId) {
1313
+ if (!instanceId)
1314
+ return;
1315
+ const fn = this.repo.lockInstance;
1316
+ if (typeof fn === 'function')
1317
+ await fn.call(this.repo, instanceId);
1318
+ }
1319
+ async cancelTaskTimeActions(taskId) {
1320
+ if (this.timeActionSink && taskId)
1321
+ await this.timeActionSink.cancelTaskTimeActions(taskId);
1322
+ }
1323
+ async cancelInstanceTimeActions(instanceId) {
1324
+ if (this.timeActionSink && instanceId)
1325
+ await this.timeActionSink.cancelInstanceTimeActions(instanceId);
1326
+ }
1327
+ /** 建单侧动作行:autoExecute=Y→AUTO_COMPLETE;有效 reminderTime→首条 REMIND。 */
1328
+ async scheduleTimeActions(nt, node, inst, allow = true) {
1329
+ if (!this.timeActionSink || !allow || !nt || !node)
1330
+ return;
1331
+ if (nt.taskState !== TaskState.Doing)
1332
+ return;
1333
+ if (String(node.properties?.autoExecute ?? '') === 'Y') {
1334
+ if (!nt.expireTime) {
1335
+ console.warn(`[jeeflow] 时限配置诊断 task=${nt.id} node=${node.id} autoExecute=Y 但无有效到期时间`);
1336
+ }
1337
+ else {
1338
+ await this.timeActionSink.insertTimeAction({
1339
+ type: 'AUTO_COMPLETE', dueAt: nt.expireTime.getTime(),
1340
+ instanceId: String(nt.processInstanceId), taskId: String(nt.id), nodeKey: node.id,
1341
+ occurrenceNo: 0, idempotencyKey: `wf:auto:${nt.id}:0`,
1342
+ });
1343
+ }
1344
+ }
1345
+ const raw = node.properties?.reminderTime;
1346
+ if (raw != null && String(raw).trim() !== '') {
1347
+ const due = firstReminderTime(String(raw), inst.variables ?? {}, nt.createTime);
1348
+ if (!due) {
1349
+ console.warn(`[jeeflow] 时限配置诊断 task=${nt.id} node=${node.id} reminderTime=${raw} 解析不出`);
1350
+ }
1351
+ else {
1352
+ await this.timeActionSink.insertTimeAction({
1353
+ type: 'REMIND', dueAt: due.getTime(),
1354
+ instanceId: String(nt.processInstanceId), taskId: String(nt.id), nodeKey: node.id,
1355
+ occurrenceNo: 1, idempotencyKey: `wf:remind:${nt.id}:1`,
1356
+ });
1357
+ }
1358
+ }
1359
+ }
1360
+ /** 任务完成(state 落 20)插入 CALLBACK(dueAt=now)。 */
1361
+ async insertCallbackAction(task, node) {
1362
+ if (!this.timeActionSink || !node || !task?.id)
1363
+ return;
1364
+ const name = String(node.properties?.callback ?? '').trim();
1365
+ if (!name)
1366
+ return;
1367
+ await this.timeActionSink.insertTimeAction({
1368
+ type: 'CALLBACK', dueAt: this.now().getTime(),
1369
+ instanceId: String(task.processInstanceId), taskId: String(task.id), nodeKey: node.id,
1370
+ occurrenceNo: 0, idempotencyKey: `wf:callback:${task.id}:0`,
1371
+ });
1372
+ }
1088
1373
  async surrogateAgents(actors, processName) {
1089
1374
  const map = new Map();
1090
1375
  const ext = this.surrogateRepo;
1091
1376
  if (!ext || !this.surrogateOn || actors.length === 0)
1092
1377
  return map;
1093
- const now = new Date();
1378
+ const now = this.now();
1094
1379
  for (const actor of actors) {
1095
1380
  try {
1096
1381
  const hit = await ext.getSurrogate(actor, processName ?? '', now);
@@ -1157,14 +1442,15 @@ export class EngineImpl {
1157
1442
  // 对齐 Java EndProcessHandler:submitType=REJECT → reject,否则 finish
1158
1443
  const submitType = inst.variables[KeySubmitType];
1159
1444
  if (submitType != null && Number(submitType) === SubmitType.Reject) {
1160
- inst.reject(new Date());
1445
+ inst.reject(this.now());
1161
1446
  }
1162
1447
  else {
1163
- inst.finish(new Date());
1448
+ inst.finish(this.now());
1164
1449
  }
1165
1450
  // issues/97:结束节点写回同样排除操作人 u_*(保留发起人 u_*,与 prepareExecuteTask 一致)
1166
1451
  inst.variables = mergeExecIntoInstance(inst.variables, vars);
1167
1452
  await this.repo.updateInstance(inst);
1453
+ await this.cancelInstanceTimeActions(inst.id);
1168
1454
  // §11.3 code 2:办结(20)/拒绝(45) 共用 PROCESS_INSTANCE_END,state 落库后 fire(§11.6)
1169
1455
  await this.notifyInstanceEnd(inst, operator);
1170
1456
  return;
@@ -1274,7 +1560,7 @@ export class EngineImpl {
1274
1560
  // 随任务一起 saveTask 落 wf_process_task_actor(严禁"事后 addTaskActor 补写")
1275
1561
  const agents = await this.surrogateAgents(actors, processName);
1276
1562
  const ct = node.properties?.countersignType;
1277
- const now = new Date();
1563
+ const now = this.now();
1278
1564
  const form = node.properties?.form ?? '';
1279
1565
  // issues/126 案 A:节点到期表达式(properties.expireTime)+ 实例变量 + 本函数取时基准 now
1280
1566
  // —— 三处写点(串行首位 / 并行全员 / 普通建单)共用 applyNodeExpireTime 这一把尺子
@@ -1293,6 +1579,7 @@ export class EngineImpl {
1293
1579
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 并行会签全员
1294
1580
  await this.repo.saveTask(nt);
1295
1581
  this.createdScope.getStore()?.push(nt);
1582
+ await this.scheduleTimeActions(nt, node, inst);
1296
1583
  // PROCESS_TASK_START:任务落库后逐个 fire(会签多任务逐个,对齐 Java CreateTaskHandler)
1297
1584
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1298
1585
  }
@@ -1312,6 +1599,7 @@ export class EngineImpl {
1312
1599
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 串行会签首位成员
1313
1600
  await this.repo.saveTask(nt);
1314
1601
  this.createdScope.getStore()?.push(nt);
1602
+ await this.scheduleTimeActions(nt, node, inst);
1315
1603
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1316
1604
  return;
1317
1605
  }
@@ -1324,6 +1612,7 @@ export class EngineImpl {
1324
1612
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 未配会签类型=全员预创建,与并行同档
1325
1613
  await this.repo.saveTask(nt);
1326
1614
  this.createdScope.getStore()?.push(nt);
1615
+ await this.scheduleTimeActions(nt, node, inst);
1327
1616
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1328
1617
  }
1329
1618
  return;
@@ -1340,6 +1629,7 @@ export class EngineImpl {
1340
1629
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 普通建单
1341
1630
  await this.repo.saveTask(nt);
1342
1631
  this.createdScope.getStore()?.push(nt);
1632
+ await this.scheduleTimeActions(nt, node, inst);
1343
1633
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1344
1634
  }
1345
1635
  /**
@@ -1400,7 +1690,7 @@ export class EngineImpl {
1400
1690
  console.warn(`[jeeflow] custom 节点未配置 clazz(缺失或空串),跳过执行、只落历史行并继续流转: ` +
1401
1691
  `nodeId=${node.id}(这是流程定义属性问题,不是注册表未命中;判据见 spec 02 §6.2 第 2 条)`);
1402
1692
  }
1403
- const now = new Date();
1693
+ const now = this.now();
1404
1694
  const ht = inst.createHistoryTask(this.nextId(), node.id, node.text?.value ?? '', operator, now, parentId, this.isFirstTaskNode(flow, node));
1405
1695
  await this.repo.saveTask(ht);
1406
1696
  // 令牌继续沿出边流转(java CustomModel 收尾那句 runOutTransition)
@@ -1502,7 +1792,7 @@ export class EngineImpl {
1502
1792
  /** issue 29:自动生成标题;issues/232 R64 拍 A 钉秒 yyyy-MM-dd HH:mm:ss(标题专用格式化点,勿并 expire_time 腿) */
1503
1793
  addAutoGenTitle(displayName, vars) {
1504
1794
  const realName = vars[KeyRealName] || '';
1505
- const now = new Date();
1795
+ const now = this.now();
1506
1796
  const pad = (n) => n.toString().padStart(2, '0');
1507
1797
  const timeStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
1508
1798
  vars[KeyAutoGenTitle] = `${realName}的${displayName}-${timeStr}`;
@@ -1737,6 +2027,41 @@ function intPrefix(s) {
1737
2027
  *
1738
2028
  * @param now 取时基准=**本栈写 createTime 用的同一个 Date**(本栈无时钟槽,与 Java 直接用系统钟同档)
1739
2029
  */
2030
+ const HHMM_RE = /^(\d{2}):(\d{2})$/;
2031
+ /**
2032
+ * 首次提醒时刻(规范 02 §4.5):变量 → 相对量(锚点=任务创建时刻)→ 严格 HH:mm → 绝对。
2033
+ * 任何一档都不得回落"当前时刻"或 expireTime。
2034
+ */
2035
+ export function firstReminderTime(expr, args, createTime) {
2036
+ const raw = expr ?? '';
2037
+ if (raw.trim() === '')
2038
+ return null;
2039
+ if (args && Object.prototype.hasOwnProperty.call(args, raw)) {
2040
+ const v = args[raw];
2041
+ if (v instanceof Date)
2042
+ return v;
2043
+ if (typeof v === 'number')
2044
+ return new Date(v);
2045
+ if (typeof v === 'string') {
2046
+ const t = new Date(v.replace(' ', 'T'));
2047
+ return isNaN(t.getTime()) ? null : t;
2048
+ }
2049
+ }
2050
+ const rel = processTime(raw, {}, createTime);
2051
+ if (rel)
2052
+ return rel;
2053
+ const m = HHMM_RE.exec(raw);
2054
+ if (m) {
2055
+ const h = Number(m[1]);
2056
+ const mi = Number(m[2]);
2057
+ if (h <= 23 && mi <= 59) {
2058
+ const t = new Date(createTime);
2059
+ t.setHours(h, mi, 0, 0);
2060
+ return t.getTime() >= createTime.getTime() ? t : new Date(t.getTime() + 86400000);
2061
+ }
2062
+ }
2063
+ return null;
2064
+ }
1740
2065
  export function processTime(expr, args, now) {
1741
2066
  const a = args ?? {};
1742
2067
  // ① 变量档:优先于相对档(args 里真有个键叫 "2h" 时取变量值)