@mldong/jeeflow 1.8.65 → 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.
@@ -8,7 +8,7 @@ export interface ActionPermissionProvider {
8
8
  permissionCodes(action: string): string[] | null;
9
9
  }
10
10
  /**
11
- * OR 规则表(对齐 java DefaultActionPermissionProvider.OR_RULES,7 条——
11
+ * OR 规则表(对齐 java DefaultActionPermissionProvider.OR_RULES,8 条——
12
12
  * boot3 `@SaCheckPermission(value={...}, mode=OR)` 语义的 action,任选其一即有权)。
13
13
  * 条目数在测试里钉死:加一条规则要八栈同批改。
14
14
  */
@@ -14,7 +14,7 @@
14
14
  // laravel WfPermission.php/salvo wf_permission.rs/csharp WfEndpoints.cs),
15
15
  // 新 action 或粒度调整要改十处+引擎,且"只用引擎、自写集成层"的客户跨栈读出两套码。
16
16
  /**
17
- * OR 规则表(对齐 java DefaultActionPermissionProvider.OR_RULES,7 条——
17
+ * OR 规则表(对齐 java DefaultActionPermissionProvider.OR_RULES,8 条——
18
18
  * boot3 `@SaCheckPermission(value={...}, mode=OR)` 语义的 action,任选其一即有权)。
19
19
  * 条目数在测试里钉死:加一条规则要八栈同批改。
20
20
  */
package/dist/engine.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type FlowModel, type FlowNode, ProcessInstance, type ProcessTask } from './model.js';
2
2
  import type { ProcessRepository, ProcessExtRepository, UserProvider, IDGenerator, ExpressionEvaluator } from './spi.js';
3
+ import type { TimeActionSink } from './spi.js';
3
4
  import { type EngineExtensions, type ProcessEvent } from './extensions.js';
4
5
  import { HandlerRegistry } from './registry.js';
5
6
  export declare const KeySubmitType = "submitType";
@@ -66,6 +67,10 @@ export interface EngineOptions {
66
67
  surrogateRepository?: SurrogateLookup | null;
67
68
  /** 委托自动生效开关,**默认 true(引擎内置开启)**;显式传 false → 回到"仅台账"行为 */
68
69
  surrogateEnabled?: boolean;
70
+ /** 时限动作凭证(spec 04);不传 = 全部时限动作静默跳过 */
71
+ timeActionSink?: TimeActionSink;
72
+ /** 引擎时钟(spec 04 · 时间基准);不传 = this.now() */
73
+ clock?: () => Date;
69
74
  }
70
75
  export declare class EngineImpl implements Engine {
71
76
  #private;
@@ -78,6 +83,10 @@ export declare class EngineImpl implements Engine {
78
83
  private ext?;
79
84
  private registry?;
80
85
  private surrogateRepo?;
86
+ /** 时限动作凭证(spec 04):不传=全部时限动作静默跳过 */
87
+ private timeActionSink?;
88
+ /** 引擎时钟(spec 04):不传=系统钟 */
89
+ private clock;
81
90
  private surrogateOn;
82
91
  constructor(repo: ProcessRepository, userProv?: UserProvider | undefined, idGen?: IDGenerator | undefined, exprEval?: ExpressionEvaluator | undefined, opts?: EngineOptions);
83
92
  /**
@@ -330,6 +339,14 @@ export declare class EngineImpl implements Engine {
330
339
  * 未配置查询源、显式关闭、无参与人 → 空映射(= 原样参与者,不打断建单);
331
340
  * 单条查询异常只记录不传播(委托是增强能力,建单主流程不得被拖崩)。
332
341
  */
342
+ private now;
343
+ private lockInstance;
344
+ private cancelTaskTimeActions;
345
+ private cancelInstanceTimeActions;
346
+ /** 建单侧动作行:autoExecute=Y→AUTO_COMPLETE;有效 reminderTime→首条 REMIND。 */
347
+ private scheduleTimeActions;
348
+ /** 任务完成(state 落 20)插入 CALLBACK(dueAt=now)。 */
349
+ private insertCallbackAction;
333
350
  private surrogateAgents;
334
351
  private loadAndCheck;
335
352
  private executeNode;
@@ -401,21 +418,8 @@ export declare function unknownEdgeWarning(from: string, to: string): string;
401
418
  * 设计器属性面板保存 'ALL' 字符串符合 Java 契约,引擎必须兼容 */
402
419
  export declare function isCountersign(v: any): boolean;
403
420
  /**
404
- * 解析期待完成时间(逐字移植 Java `FlowUtil.processTime` / C# `FlowUtil.ProcessTime`,本栈原先没有)。
405
- *
406
- * 三档语义,**顺序不能变**:
407
- * 1. `args` 里存在键名等于 expr 原串的项 ⇒ 取该项的值:Date / 毫秒时间戳 / `"yyyy-MM-dd HH:mm:ss"`
408
- * → 该时刻;字符串解析失败 → **null**(不是 now);其它类型(布尔/数组/对象/小数)→ **落穿**到下面两档
409
- * (Java/C# 都是落穿,不许当"解析失败"提前 return null)。
410
- * 2. 否则 expr 以 `s`/`m`/`h`/`d` 结尾且前缀是整数 ⇒ now + N 秒/分/时/天(`d` 走**日历加天**,不乘 86400 秒)。
411
- * 前缀**允许两端空白**(issues/137 E · owner 拍"统一 trim"):`intPrefix` 在判整数前裁掉
412
- * `expr.slice(0, -1)` 的两端空白 ⇒ `" 2h"`、`"2 h"` 照样算得出;裁的边界只到前缀,末位单位符那一位
413
- * (下面 `expr.charAt(expr.length - 1)`)**不跟着 trim** ⇒ `"2h "` 仍按误配落穿。
414
- * 3. 否则把 expr 本身按 `"yyyy-MM-dd HH:mm:ss"` 解析 → 时刻;失败 → null。
415
- * ⚠️ 档 1 的键名与档 3 的串本身**都不 trim**:那是键名/时间串本身,裁它会改的是另一件事。
416
- *
417
- * ⚠️ 任何一档都不得退回 now()——"算不出来就写当前时间"正是 issues/126 的病灶(建单即逾期,逾期统计恒失真)。
418
- *
419
- * @param now 取时基准=**本栈写 createTime 用的同一个 Date**(本栈无时钟槽,与 Java 直接用系统钟同档)
421
+ * 首次提醒时刻(规范 02 §4.5):变量 → 相对量(锚点=任务创建时刻)→ 严格 HH:mm → 绝对。
422
+ * 任何一档都不得回落"当前时刻"或 expireTime。
420
423
  */
424
+ export declare function firstReminderTime(expr: string, args: Record<string, any> | undefined, createTime: Date): Date | null;
421
425
  export declare function processTime(expr: string, args: Record<string, any> | undefined, now: Date): Date | null;
package/dist/engine.js CHANGED
@@ -137,6 +137,10 @@ export class EngineImpl {
137
137
  registry;
138
138
  // issues/116:委托代理自动生效——内置能力,注入查询源后默认开启
139
139
  surrogateRepo;
140
+ /** 时限动作凭证(spec 04):不传=全部时限动作静默跳过 */
141
+ timeActionSink;
142
+ /** 引擎时钟(spec 04):不传=系统钟 */
143
+ clock = () => new Date();
140
144
  surrogateOn = true;
141
145
  constructor(repo, userProv, idGen, exprEval, opts) {
142
146
  this.repo = repo;
@@ -147,6 +151,10 @@ export class EngineImpl {
147
151
  this.surrogateRepo = opts.surrogateRepository;
148
152
  if (opts?.surrogateEnabled !== undefined)
149
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;
150
158
  }
151
159
  /**
152
160
  * issues/116:注入/摘除委托查询源(ProcessExtRepository 或任何实现 getSurrogate 的对象)。
@@ -399,7 +407,7 @@ export class EngineImpl {
399
407
  const vars = { ...args };
400
408
  await this.addUserInfo(operator, vars);
401
409
  this.addAutoGenTitle(def.displayName, vars);
402
- const now = new Date();
410
+ const now = this.now();
403
411
  // 聚合根工厂创建实例
404
412
  const inst = ProcessInstance.create(this.nextId(), defineId, operator, vars, now);
405
413
  // issues/137 A · 裁定 A(批二 §3-4)· **实例级 expire_time 的唯一写点**:
@@ -455,7 +463,7 @@ export class EngineImpl {
455
463
  await this.handleCcActors(inst.id, operator, args[KeyCcActors]);
456
464
  return (await this.repo.findInstanceById(inst.id));
457
465
  };
458
- const now = new Date();
466
+ const now = this.now();
459
467
  const curNode = findNode(flow, task.taskName);
460
468
  if (curNode) {
461
469
  // 1.8.0:任务完成节点自身的后置拦截器(SYNC 同步演进——任务节点推进更新状态/字段)。
@@ -505,6 +513,7 @@ export class EngineImpl {
505
513
  applyNodeExpireTime(nt, curNode.properties?.expireTime, inst.variables, now);
506
514
  await this.repo.saveTask(nt);
507
515
  this.createdScope.getStore()?.push(nt);
516
+ await this.scheduleTimeActions(nt, curNode, inst);
508
517
  // PROCESS_TASK_START:顺序会签推进新任务落库后 fire(对齐 Java CreateTaskHandler / Rust)
509
518
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: curNode.id, operator, actors: [...nt.actorIds] });
510
519
  return finishExecute();
@@ -627,10 +636,11 @@ export class EngineImpl {
627
636
  // 拒绝结束:本节点未完成的加签任务一并废弃,不留孤儿待办(规范 04 · 后加签/语义边界表)
628
637
  // issues/253:离开节点先清场未办结协办行(废弃+账本记废弃),再走后加签/征询的既有废弃腿
629
638
  await this.abandonAidantOnNode(inst, task.taskName, operator);
630
- await this.abandonAddSignDoing(flow, inst, task.taskName, new Date());
639
+ await this.abandonAddSignDoing(flow, inst, task.taskName, this.now());
631
640
  // 门面 submitType=2 REJECT 唯一入口(对齐 Java executeAndJumpToEnd 语义)
632
- inst.reject(new Date());
641
+ inst.reject(this.now());
633
642
  await this.repo.updateInstance(inst);
643
+ await this.cancelInstanceTimeActions(inst.id);
634
644
  // §11.3 code 2:拒绝也是"实例进入终态"(state=45 落库后 fire,靠载荷 state 与办结分家);
635
645
  // "任务被退回"这一事实另由 prepareExecuteTask 的 TASK_REJECT(6) 承载(场景 31/32 两支并存)
636
646
  await this.notifyInstanceEnd(inst, operator);
@@ -725,7 +735,7 @@ export class EngineImpl {
725
735
  // 退回发起人:本节点未完成的加签任务一并废弃,不留孤儿待办(规范 04 · 后加签/语义边界表)
726
736
  // issues/253:退回发起人离开本节点 ⇒ 未办结协办行随废弃腿清场(账本记废弃)
727
737
  await this.abandonAidantOnNode(inst, task.taskName, operator);
728
- await this.abandonAddSignDoing(flow, inst, task.taskName, new Date());
738
+ await this.abandonAddSignDoing(flow, inst, task.taskName, this.now());
729
739
  if (direct) {
730
740
  if (sourceNode.type !== TypeTask)
731
741
  throw new Error(`节点[${sourceNode.id}]不是普通审批任务,不支持重提直返`);
@@ -789,6 +799,9 @@ export class EngineImpl {
789
799
  return resurrected;
790
800
  }
791
801
  async recallTaskInner(taskId, operator) {
802
+ // 实例级事务排他(spec 04 · 并发保护):先锁再读
803
+ const preForLock = await this.repo.findTaskById(taskId);
804
+ await this.lockInstance(preForLock?.processInstanceId);
792
805
  // 判据 1:目标行存在且已办结(不存在/进行中/已废弃同档)
793
806
  const target = await this.repo.findTaskById(taskId);
794
807
  if (!target || !target.isFinished())
@@ -814,7 +827,7 @@ export class EngineImpl {
814
827
  // 内存与 SQL 两仓同形状)
815
828
  const doingDescendants = validateWindow(await this.repo.findHistoryTasks(inst.id), target);
816
829
  // ── 判据全过,以下才允许写 ──
817
- const now = new Date();
830
+ const now = this.now();
818
831
  // 写 1:下游全部 DOING 行废弃(后加签/征询成员行、并行分支多支自然覆盖;updateUser 记真实撤回人,
819
832
  // 照 java `ProcessTask.abandon(operator)`/py `t.updateUser = operator` 同尺)
820
833
  for (const t of doingDescendants) {
@@ -834,6 +847,7 @@ export class EngineImpl {
834
847
  nt.actorIds = eff;
835
848
  await this.repo.saveTask(nt);
836
849
  this.createdScope.getStore()?.push(nt);
850
+ await this.scheduleTimeActions(nt, node, inst);
837
851
  // 码 3:复活行的待办另走既有建单腿(issues/246 参考实现 14674d7 补的那一腿——只 fire 10
838
852
  // 不 fire 3 ⇒ 集成方的待办角标/站内信拿不到这一手新待办)
839
853
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id,
@@ -871,6 +885,7 @@ export class EngineImpl {
871
885
  }
872
886
  async aidantTaskInner(taskId, actorIds, reason, waitCompletion, operator) {
873
887
  let host = await this.repo.findTaskById(taskId);
888
+ await this.lockInstance(host?.processInstanceId);
874
889
  if (!host)
875
890
  throw new Error(MSG_AIDANT_TASK_NOT_FOUND);
876
891
  // 禁递归:协办行携带派生参数 ⇒ 报错(规范 04 派生规则 4)
@@ -911,7 +926,7 @@ export class EngineImpl {
911
926
  }
912
927
  }
913
928
  // ── 判据全过,以下才允许写 ──
914
- const now = new Date();
929
+ const now = this.now();
915
930
  const round = aidantLastRound(host) + 1;
916
931
  const isFirst = this.isFirstTaskNode(flow, node);
917
932
  const form = node.properties?.form ?? '';
@@ -931,6 +946,7 @@ export class EngineImpl {
931
946
  applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now);
932
947
  await this.repo.saveTask(nt);
933
948
  this.createdScope.getStore()?.push(nt);
949
+ await this.scheduleTimeActions(nt, node, inst, false);
934
950
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
935
951
  taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
936
952
  created.push(nt);
@@ -983,7 +999,7 @@ export class EngineImpl {
983
999
  byHost.set(key, [t]);
984
1000
  }
985
1001
  }
986
- const now = new Date();
1002
+ const now = this.now();
987
1003
  let abandoned = 0;
988
1004
  for (const [parentId, rows] of byHost) {
989
1005
  const actors = [];
@@ -1009,6 +1025,9 @@ export class EngineImpl {
1009
1025
  // 返回流程模型 + 合并后执行变量。Java jump 路径不废弃其余 DOING 任务
1010
1026
  // (会签兄弟任务不受影响),此处保持一致。
1011
1027
  async prepareExecuteTask(taskId, operator, args) {
1028
+ // 实例级事务排他(spec 04 · 并发保护):先锁再读,堵"读后锁前"的二次推进窗口
1029
+ const pre = await this.repo.findTaskById(taskId);
1030
+ await this.lockInstance(pre?.processInstanceId);
1012
1031
  const { task, inst } = await this.loadAndCheck(taskId, operator);
1013
1032
  // issues/26:办理提交的 f_ 字段按任务节点字段权限过滤(只读/隐藏不入变量)
1014
1033
  const def = await this.repo.findDefineById(inst.defineId);
@@ -1032,13 +1051,15 @@ export class EngineImpl {
1032
1051
  const baseVars = inst.variables;
1033
1052
  const vars = { ...baseVars, ...task.variables, ...args };
1034
1053
  await this.addUserInfo(operator, vars);
1035
- const now = new Date();
1054
+ const now = this.now();
1036
1055
  // §11.2 原则 2「码粗、载荷细」+场景 30/31 互斥:本次动作是"办掉"还是"退回"由 submitType 定,
1037
1056
  // 同一动作只发其中一支(旧形状无论 submitType 一律 fire TaskComplete 即本案病灶)
1038
1057
  const submitType = normalizeSubmitType(vars[KeySubmitType]);
1039
1058
  // 聚合根:完成任务(子实体状态转换 + 实例变量合并)
1040
1059
  inst.completeTask(task, operator, vars, now);
1041
1060
  await this.repo.updateTask(task);
1061
+ // 时限动作联动(spec 04 · 写路径):任务离开 DOING ⇒ 取消该任务 pending 提醒/自动行
1062
+ await this.cancelTaskTimeActions(task.id);
1042
1063
  // v1.0.1:updateInstance 级联持久化依赖聚合内任务副本为最新状态,
1043
1064
  // completeTask 改的是外部任务对象,需同步回聚合根
1044
1065
  syncTaskToAggregate(inst, task);
@@ -1047,6 +1068,10 @@ export class EngineImpl {
1047
1068
  await this.repo.updateInstance(inst);
1048
1069
  // §11.2 原则 3:任务行与实例**都落库之后**才 fire(旧形状排在 updateInstance 之前,
1049
1070
  // 监听器反查实例读到旧状态——与 issues/121/126 两轮"回写序"同族)
1071
+ // 完成回调(spec 04 · CALLBACK):只对应 TASK_COMPLETE 事实(退回族不触发)
1072
+ if (!isRejectSubmitType(submitType)) {
1073
+ await this.insertCallbackAction(task, findNode(flow, task.taskName));
1074
+ }
1050
1075
  await this.fireEvent({
1051
1076
  type: isRejectSubmitType(submitType) ? EventType.TaskReject : EventType.TaskComplete,
1052
1077
  instanceId: inst.id, taskId: task.id, nodeId: task.taskName, operator, submitType,
@@ -1151,7 +1176,7 @@ export class EngineImpl {
1151
1176
  async rollbackToParent(flow, inst, task, operator) {
1152
1177
  const { his, prev, actor, isFirst } = await this.checkRejectable(flow, inst, task);
1153
1178
  // 取时基准只取一次:本行 createTime 与 expire_time 共用同一个 Date(写点内不另起时钟)
1154
- const now = new Date();
1179
+ const now = this.now();
1155
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);
1156
1181
  // 复活行只带数据类键:tf_*(上次表单提交)与 csv_*/会签簿记都是"上次提交"的残留
1157
1182
  nt.variables = { ...lineageVars(his.variables), isFirstTaskNode: isFirst };
@@ -1165,6 +1190,7 @@ export class EngineImpl {
1165
1190
  nt.actorIds = eff;
1166
1191
  await this.repo.saveTask(nt);
1167
1192
  this.createdScope.getStore()?.push(nt);
1193
+ await this.scheduleTimeActions(nt, prev, inst);
1168
1194
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
1169
1195
  taskId: nt.id, nodeId: prev.id, operator, actors: [...nt.actorIds] });
1170
1196
  }
@@ -1205,6 +1231,7 @@ export class EngineImpl {
1205
1231
  applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now); // 加签续建
1206
1232
  await this.repo.saveTask(nt);
1207
1233
  this.createdScope.getStore()?.push(nt);
1234
+ await this.scheduleTimeActions(nt, node, inst);
1208
1235
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
1209
1236
  taskId: nt.id, nodeId, operator, actors: [...nt.actorIds] });
1210
1237
  }
@@ -1250,6 +1277,7 @@ export class EngineImpl {
1250
1277
  applyNodeExpireTime(nt, node.properties?.expireTime, inst.variables, now);
1251
1278
  await this.repo.saveTask(nt);
1252
1279
  this.createdScope.getStore()?.push(nt);
1280
+ await this.scheduleTimeActions(nt, node, inst);
1253
1281
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id,
1254
1282
  taskId: nt.id, nodeId, operator, actors: [...nt.actorIds] });
1255
1283
  created.push(nt);
@@ -1277,12 +1305,77 @@ export class EngineImpl {
1277
1305
  * 未配置查询源、显式关闭、无参与人 → 空映射(= 原样参与者,不打断建单);
1278
1306
  * 单条查询异常只记录不传播(委托是增强能力,建单主流程不得被拖崩)。
1279
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
+ }
1280
1373
  async surrogateAgents(actors, processName) {
1281
1374
  const map = new Map();
1282
1375
  const ext = this.surrogateRepo;
1283
1376
  if (!ext || !this.surrogateOn || actors.length === 0)
1284
1377
  return map;
1285
- const now = new Date();
1378
+ const now = this.now();
1286
1379
  for (const actor of actors) {
1287
1380
  try {
1288
1381
  const hit = await ext.getSurrogate(actor, processName ?? '', now);
@@ -1349,14 +1442,15 @@ export class EngineImpl {
1349
1442
  // 对齐 Java EndProcessHandler:submitType=REJECT → reject,否则 finish
1350
1443
  const submitType = inst.variables[KeySubmitType];
1351
1444
  if (submitType != null && Number(submitType) === SubmitType.Reject) {
1352
- inst.reject(new Date());
1445
+ inst.reject(this.now());
1353
1446
  }
1354
1447
  else {
1355
- inst.finish(new Date());
1448
+ inst.finish(this.now());
1356
1449
  }
1357
1450
  // issues/97:结束节点写回同样排除操作人 u_*(保留发起人 u_*,与 prepareExecuteTask 一致)
1358
1451
  inst.variables = mergeExecIntoInstance(inst.variables, vars);
1359
1452
  await this.repo.updateInstance(inst);
1453
+ await this.cancelInstanceTimeActions(inst.id);
1360
1454
  // §11.3 code 2:办结(20)/拒绝(45) 共用 PROCESS_INSTANCE_END,state 落库后 fire(§11.6)
1361
1455
  await this.notifyInstanceEnd(inst, operator);
1362
1456
  return;
@@ -1466,7 +1560,7 @@ export class EngineImpl {
1466
1560
  // 随任务一起 saveTask 落 wf_process_task_actor(严禁"事后 addTaskActor 补写")
1467
1561
  const agents = await this.surrogateAgents(actors, processName);
1468
1562
  const ct = node.properties?.countersignType;
1469
- const now = new Date();
1563
+ const now = this.now();
1470
1564
  const form = node.properties?.form ?? '';
1471
1565
  // issues/126 案 A:节点到期表达式(properties.expireTime)+ 实例变量 + 本函数取时基准 now
1472
1566
  // —— 三处写点(串行首位 / 并行全员 / 普通建单)共用 applyNodeExpireTime 这一把尺子
@@ -1485,6 +1579,7 @@ export class EngineImpl {
1485
1579
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 并行会签全员
1486
1580
  await this.repo.saveTask(nt);
1487
1581
  this.createdScope.getStore()?.push(nt);
1582
+ await this.scheduleTimeActions(nt, node, inst);
1488
1583
  // PROCESS_TASK_START:任务落库后逐个 fire(会签多任务逐个,对齐 Java CreateTaskHandler)
1489
1584
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1490
1585
  }
@@ -1504,6 +1599,7 @@ export class EngineImpl {
1504
1599
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 串行会签首位成员
1505
1600
  await this.repo.saveTask(nt);
1506
1601
  this.createdScope.getStore()?.push(nt);
1602
+ await this.scheduleTimeActions(nt, node, inst);
1507
1603
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1508
1604
  return;
1509
1605
  }
@@ -1516,6 +1612,7 @@ export class EngineImpl {
1516
1612
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 未配会签类型=全员预创建,与并行同档
1517
1613
  await this.repo.saveTask(nt);
1518
1614
  this.createdScope.getStore()?.push(nt);
1615
+ await this.scheduleTimeActions(nt, node, inst);
1519
1616
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1520
1617
  }
1521
1618
  return;
@@ -1532,6 +1629,7 @@ export class EngineImpl {
1532
1629
  applyNodeExpireTime(nt, expireExpr, expireArgs, now); // 普通建单
1533
1630
  await this.repo.saveTask(nt);
1534
1631
  this.createdScope.getStore()?.push(nt);
1632
+ await this.scheduleTimeActions(nt, node, inst);
1535
1633
  await this.fireEvent({ type: EventType.ProcessTaskStart, instanceId: inst.id, taskId: nt.id, nodeId: node.id, operator, actors: [...nt.actorIds] });
1536
1634
  }
1537
1635
  /**
@@ -1592,7 +1690,7 @@ export class EngineImpl {
1592
1690
  console.warn(`[jeeflow] custom 节点未配置 clazz(缺失或空串),跳过执行、只落历史行并继续流转: ` +
1593
1691
  `nodeId=${node.id}(这是流程定义属性问题,不是注册表未命中;判据见 spec 02 §6.2 第 2 条)`);
1594
1692
  }
1595
- const now = new Date();
1693
+ const now = this.now();
1596
1694
  const ht = inst.createHistoryTask(this.nextId(), node.id, node.text?.value ?? '', operator, now, parentId, this.isFirstTaskNode(flow, node));
1597
1695
  await this.repo.saveTask(ht);
1598
1696
  // 令牌继续沿出边流转(java CustomModel 收尾那句 runOutTransition)
@@ -1694,7 +1792,7 @@ export class EngineImpl {
1694
1792
  /** issue 29:自动生成标题;issues/232 R64 拍 A 钉秒 yyyy-MM-dd HH:mm:ss(标题专用格式化点,勿并 expire_time 腿) */
1695
1793
  addAutoGenTitle(displayName, vars) {
1696
1794
  const realName = vars[KeyRealName] || '';
1697
- const now = new Date();
1795
+ const now = this.now();
1698
1796
  const pad = (n) => n.toString().padStart(2, '0');
1699
1797
  const timeStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
1700
1798
  vars[KeyAutoGenTitle] = `${realName}的${displayName}-${timeStr}`;
@@ -1929,6 +2027,41 @@ function intPrefix(s) {
1929
2027
  *
1930
2028
  * @param now 取时基准=**本栈写 createTime 用的同一个 Date**(本栈无时钟槽,与 Java 直接用系统钟同档)
1931
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
+ }
1932
2065
  export function processTime(expr, args, now) {
1933
2066
  const a = args ?? {};
1934
2067
  // ① 变量档:优先于相对档(args 里真有个键叫 "2h" 时取变量值)
@@ -76,6 +76,9 @@ export declare class JdbcRepository implements ProcessRepository {
76
76
  updateInstance(inst: ProcessInstance): Promise<void>;
77
77
  private static TASK_COLS;
78
78
  findTaskById(taskId: string): Promise<ProcessTask | null>;
79
+ /** 实例级事务排他(spec 04 · 并发保护):实例行 SELECT … FOR UPDATE,
80
+ * 锁随最外层 withTx 提交/回滚释放;行不存在不新造失败面。 */
81
+ lockInstance(instanceId: string): Promise<void>;
79
82
  saveTask(task: ProcessTask): Promise<void>;
80
83
  updateTask(task: ProcessTask): Promise<void>;
81
84
  /** 用指定连接更新任务(实例级联时与实例更新同连接) */
@@ -345,6 +345,19 @@ export class JdbcRepository {
345
345
  await this.done(conn);
346
346
  }
347
347
  }
348
+ /** 实例级事务排他(spec 04 · 并发保护):实例行 SELECT … FOR UPDATE,
349
+ * 锁随最外层 withTx 提交/回滚释放;行不存在不新造失败面。 */
350
+ async lockInstance(instanceId) {
351
+ if (!instanceId)
352
+ return;
353
+ const conn = await this.c();
354
+ try {
355
+ await conn.fetchOne(this.sql('SELECT id FROM wf_process_instance WHERE id = ? FOR UPDATE'), [instanceId]);
356
+ }
357
+ finally {
358
+ await this.done(conn);
359
+ }
360
+ }
348
361
  async saveTask(task) {
349
362
  const conn = await this.c();
350
363
  try {
package/dist/spi.d.ts CHANGED
@@ -145,6 +145,10 @@ export interface TaskStatsRow {
145
145
  expireTime: Date | string | null;
146
146
  }
147
147
  export interface ProcessRepository {
148
+ /** 实例级事务排他(spec 04);未实现的仓储退化为引擎进程内互斥 */
149
+ lockInstance?(instanceId: string): Promise<void>;
150
+ /** 实例级事务排他(spec 04);未实现的仓储退化为引擎进程内互斥 */
151
+ lockInstance?(instanceId: string): Promise<void>;
148
152
  /** 事务载体(audit8 145-2,spec/12 §12.2)——JDBC 仓储天然实现(AsyncLocalStorage);
149
153
  * 内存仓没有此方法 ⇒ 引擎 inTx 显式降级裸跑(§12.1 原则 4)。 */
150
154
  withTx?<T>(fn: () => Promise<T>): Promise<T>;
@@ -344,3 +348,20 @@ export interface ProcessExtRepository {
344
348
  pageSurrogates(pageNum?: number, pageSize?: number, filters?: Record<string, any>, conditions?: QueryCondition[]): Promise<[ProcessSurrogate[], number]>;
345
349
  getSurrogate(operator: string, processName: string, at?: Date): Promise<ProcessSurrogate | null>;
346
350
  }
351
+ /** 任务时限动作凭证(spec 04 · 任务时限动作):dueAt 用 UTC 毫秒。 */
352
+ export interface TimeAction {
353
+ type: 'REMIND' | 'AUTO_COMPLETE' | 'CALLBACK';
354
+ dueAt: number;
355
+ instanceId: string;
356
+ taskId: string;
357
+ nodeKey: string;
358
+ occurrenceNo: number;
359
+ idempotencyKey: string;
360
+ }
361
+ /** 时限动作凭证仓储侧实现(集成层按框架执行队列实现,引擎在业务事务内回调)。
362
+ * 取消只清 REMIND/AUTO_COMPLETE;CALLBACK 表达既成事实、不随失效取消。 */
363
+ export interface TimeActionSink {
364
+ insertTimeAction(action: TimeAction): Promise<void>;
365
+ cancelTaskTimeActions(taskId: string): Promise<void>;
366
+ cancelInstanceTimeActions(instanceId: string): Promise<void>;
367
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mldong/jeeflow",
3
- "version": "1.8.65",
3
+ "version": "1.8.66",
4
4
  "description": "jeeflow workflow engine — Node.js / TypeScript implementation",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,7 @@
19
19
  "scripts": {
20
20
  "build": "tsc",
21
21
  "typecheck": "tsc -p tsconfig.check.json",
22
- "test": "node --import tsx __tests__/spec.test.ts && node --import tsx --test __tests__/reapply.test.ts && node --import tsx --test __tests__/add-sign-after.test.ts && node --import tsx --test __tests__/recall.test.ts && node --import tsx --test __tests__/dynamic-countersign.test.ts && node --import tsx --test __tests__/aidant.test.ts && node --import tsx --test __tests__/action-permission.test.ts && node --import tsx --test __tests__/persist.test.ts && node --import tsx --test __tests__/tasktype-secondary-ban.test.ts",
22
+ "test": "node --import tsx __tests__/spec.test.ts && node --import tsx --test __tests__/reapply.test.ts && node --import tsx --test __tests__/add-sign-after.test.ts && node --import tsx --test __tests__/recall.test.ts && node --import tsx --test __tests__/dynamic-countersign.test.ts && node --import tsx --test __tests__/aidant.test.ts && node --import tsx --test __tests__/action-permission.test.ts && node --import tsx --test __tests__/persist.test.ts && node --import tsx --test __tests__/tasktype-secondary-ban.test.ts && node --import tsx --test __tests__/time-limit-action.test.ts",
23
23
  "test-mysql": "node --import tsx --test --test-concurrency=1 __tests__/jdbc.test.ts __tests__/tx-tier-145.test.ts __tests__/after_commit_r77.test.ts __tests__/recall-collect-mysql.test.ts __tests__/instance-state-mysql.test.ts",
24
24
  "demo": "node --import tsx demo/main.ts",
25
25
  "prepublishOnly": "npm run build"