fix: preserve intake windows and update vulnerable dependencies

This commit is contained in:
abaishu0730 committed 2026-10-26 14:50:55 +08:00
1 parent f7426c937c
commit b14fa2f4d1
11 files changed
+353 -77

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# 开发交接(2026-10-23)
## 2026-10-26 审查前两项与依赖修复
- 原通知任务在及时启动的扫描中被接收后,持久保存intakeWindow和intakeStartedAt;慢列表读取、详情采集、归档及重启均复用原窗口,不因跨过发送后60秒而直接ignored。已接收任务最多沿用既有30分钟发送宽限,超期明确受阻留证。到达截止仍提前5分钟,不接纳任意迟到历史,不扩大已冻结批次,unknown/sent不自动重发。
- 新批次扫描屏障排除removedAt历史任务,保留未移除不确定任务及活动来源的完整对账检查;原记录、归档与回执不删除。
- nodemailer升级10.2.1,mailparser升级3.12.4,smtp-server隔离测试依赖升级3.21.1;ExcelJS保持4.4.0,仅覆盖其uuid至CommonJS兼容的11.1.1。工作区及本机预装依赖均干净安装,npm audit(含dev)报告0条已知告警。验证Unicode邮件、无附件信封、Excel读写/扩展条件格式及UUID边界检查。
- 本轮仅修前两项与依赖;扫描报告中的通用“发测试到本邮箱”受限策略旁路仍未修改。真实BPM/SMTP/SMB不参与代码测试;本机测试期、收件箱、签名、标题、规则与业务数据在更新时保留,正式服务机不操作。验收和依赖切换回执保存在忽略的output/business-flow-test。
- 验证:业务回归95项通过;最终慢采集/旧屏障/惠州独立投递/五天期限专项66项通过。新增兼容测试最初使用了不触发扩展格式的Excel夹具,已按ExcelJS声明条件改为真实扩展格式路径复验;一次Windows加密初始化超时单独重跑通过。独立审查发现的普通通知sent/unknown后惠州补充通知宽限丢失已修复,保留普通冻结回执与惠州自身unknown保护。未运行旧千项全量。
## 2026-10-26 五天受限稳定性测试
- 用户授权清空旧订单中心显示后开始连续五天受限测试。旧订单、任务软移除,任务保留防重,原PDF/归档/邮件回执不删;原异常留档。仅新基线后的真实匹配通知参与,固定测试QQ、空Cc、无附件、桌面归档及BPM只读保持。
@@ -0,0 +1,9 @@
# 慢采集、旧记录屏障与依赖修复
用户确认仅处理本轮扫描的前两项问题和依赖公告;通用测试发信入口不在本轮范围。
1. 先将61秒采集/归档跨截止复现为失败测试。发现时保存原到达窗口与扫描开始证据,后续步骤复用;只允许已及时接受且尚未冻结的原任务在现有30分钟发送宽限内完成,不扩大五分钟到达截止、不补任意历史、不重发unknown/sent。超过宽限转明确受阻,保留字段和归档证据。
2. 为removedAt旧unknown任务+停用连接编写失败测试,从新批次发现源中排除已移除任务;活动来源和未移除的不确定任务仍阻塞。
3. 升级nodemailer至10.2.1、mailparser至3.12.4、smtp-server测试依赖至3.21.1;ExcelJS保留4.4.0,仅将其uuid覆盖为支持CommonJS的11.1.1,验证工作簿导入/导出及扩展条件格式。
4. 干净安装依赖,依赖审计及相关隔离SMTP/Excel/执行器测试通过后独立复核。正式状态、真实BPM、邮件和SMB不用于测试。
5. 在本机本地目录预装新依赖,备份代码和数据库后更新原测试副本;旧依赖目录保留可回滚,五天测试期限、签名、标题、规则和数据保持不变,不手动发信。
+129 -57
View File
@@ -13,18 +13,18 @@
"@whyour/qinglong-cli": "0.1.2",
"docx-preview": "0.4.1",
"exceljs": "4.4.0",
"html-to-text": "10.0.1",
"imapflow": "2.4.3",
"jszip": "3.10.1",
"mailparser": "3.9.39",
"nodemailer": "10.1.1",
"mailparser": "3.12.4",
"nodemailer": "10.2.1",
"photoswipe": "5.4.4",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"html-to-text": "10.0.1"
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
},
"devDependencies": {
"smtp-server": "3.19.22"
"smtp-server": "3.21.1"
},
"engines": {
"node": ">=22.13"
@@ -35,6 +35,7 @@
"resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.9.0"
}
@@ -44,6 +45,7 @@
"resolved": "https://registry.npmmirror.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.9.0"
}
@@ -53,6 +55,7 @@
"resolved": "https://registry.npmmirror.com/@babel/parser/-/parser-7.29.9.tgz",
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/types": "^7.29.8"
},
@@ -68,6 +71,7 @@
"resolved": "https://registry.npmmirror.com/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
@@ -81,7 +85,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/core/-/core-2.15.1.tgz",
"integrity": "sha512-jP+fqsCM+RVQ3sMe6bq0+iamA+YdHcFrXxOICLe8c+xAA+e4//U0A5ys/B/3gJIe4Z+hwcKpVhZRvZrbnH7Qcg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/engines": "2.15.1",
"@embedpdf/models": "2.15.1"
@@ -177,7 +180,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-annotation/-/plugin-annotation-2.15.1.tgz",
"integrity": "sha512-LoPqB/DNlSxjcyUqccRm6O2qP1Hiy6tLLSy7QjMVCKB4dXpD19Q6r7lTPDgW0H+9RxW2OHHBUPvuKgsSXF5TAA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1",
"@embedpdf/utils": "2.15.1"
@@ -340,7 +342,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-history/-/plugin-history-2.15.1.tgz",
"integrity": "sha512-n2uSdcdN2qu5/hY6Ngn52ic30GE6gtJCM3Rvh8YfRhTup2htQE2DOq5SN6NkP14Yuz+afXMH1oitw70R8qHUAw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -358,7 +359,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-i18n/-/plugin-i18n-2.15.1.tgz",
"integrity": "sha512-5UCmWpX+kloWhRvilOW9+8sl2NJvu83Q6kZcL69P6pJD5UDjHCt3CbVE3zoLKTSnmQZp35i1ZldicQRk7cjGdw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -376,7 +376,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-interaction-manager/-/plugin-interaction-manager-2.15.1.tgz",
"integrity": "sha512-5EgQBaZ2wnIoUKJXkzZK+Cn/aqv+maffpdv8KXWCkSqLcN8XVNudS+9c4HsRjiuhaTCWFmQu3+WivTrIse8sqA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -452,7 +451,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-render/-/plugin-render-2.15.1.tgz",
"integrity": "sha512-cb9sMRUnxEh7p+xFD5p7xkVkxDT+CP36mBd7VVjey9Pdaz+e1fC6QJElMTUES91MQj4Qpt8AD9hIy/VchzoD+g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -487,7 +485,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-scroll/-/plugin-scroll-2.15.1.tgz",
"integrity": "sha512-WEMims3x3LMPS/xZvujUdkctpXQYKe6AkkIRshqjItjBNjbgUf+ohqya/Q3drVGD5tzb1olYJ55bmwkNw+0rMQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -523,7 +520,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-selection/-/plugin-selection-2.15.1.tgz",
"integrity": "sha512-mbC7uNzRg+DHHZs+zWkpqeAcipMmV+GNEOkSmYwFY5com7CN+Utn1m31uAhkjP9zgEYu9Rykd9hJuVbLnUNqHw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1",
"@embedpdf/utils": "2.15.1"
@@ -655,7 +651,6 @@
"resolved": "https://registry.npmmirror.com/@embedpdf/plugin-viewport/-/plugin-viewport-2.15.1.tgz",
"integrity": "sha512-Po8vKNubysKTDBt0YBd87Z2YzbmMdTECT1VT8GBLfZk4Vm2P3DX0dh1sWFctkM2IjrscCH3tjH/MA5ZDtrCiAg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@embedpdf/models": "2.15.1"
},
@@ -776,6 +771,7 @@
"resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
@@ -786,6 +782,7 @@
"resolved": "https://registry.npmmirror.com/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
@@ -796,6 +793,7 @@
"resolved": "https://registry.npmmirror.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6.0.0"
}
@@ -804,13 +802,15 @@
"version": "1.6.0",
"resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
@@ -853,6 +853,7 @@
"resolved": "https://registry.npmmirror.com/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
"integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
"license": "MIT",
"peer": true,
"peerDependencies": {
"acorn": "^8.9.0"
}
@@ -885,7 +886,8 @@
"version": "1.0.9",
"resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@types/node": {
"version": "14.18.63",
@@ -898,6 +900,7 @@
"resolved": "https://registry.npmmirror.com/@vue/compiler-core/-/compiler-core-3.5.44.tgz",
"integrity": "sha512-k34nCytbK8PQ1gR2mGROYOw6Pnv/mumqIdrZ3x2tbyXZDWm7ViKGLTfdB+DRrWqEQsLgGJvn0WN9jBif5zCTLQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.29.9",
"@vue/shared": "3.5.44",
@@ -911,6 +914,7 @@
"resolved": "https://registry.npmmirror.com/entities/-/entities-7.0.1.tgz",
"integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
"license": "BSD-2-Clause",
"peer": true,
"engines": {
"node": ">=0.12"
},
@@ -923,6 +927,7 @@
"resolved": "https://registry.npmmirror.com/@vue/compiler-dom/-/compiler-dom-3.5.44.tgz",
"integrity": "sha512-W5AoBFWdw1lQAKiHowkfgFKFab82oSRT6sGsPfw/q1GRjsy/ZJFLHGhJyBRIFN9APLTUduDH9U2JAiPOIyKuYg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-core": "3.5.44",
"@vue/shared": "3.5.44"
@@ -933,6 +938,7 @@
"resolved": "https://registry.npmmirror.com/@vue/compiler-sfc/-/compiler-sfc-3.5.44.tgz",
"integrity": "sha512-dzHmQ4jXTpdr5FjIQUeykVakN/uzqFbUo9/C5ikBFg3a3PeM6uRxeczx1ZbXBML0/zJstEh3ygYipzR5Z7b2Pw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.29.9",
"@vue/compiler-core": "3.5.44",
@@ -950,6 +956,7 @@
"resolved": "https://registry.npmmirror.com/@vue/compiler-ssr/-/compiler-ssr-3.5.44.tgz",
"integrity": "sha512-xr5gb1JVHlfXJwSlRz1FeP6uxoazdzHuMTVLE7up+4Vrqxk219CvxLPxD9NXBt47yvZW7+p4DXfyp4O1fkByIA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.44",
"@vue/shared": "3.5.44"
@@ -960,6 +967,7 @@
"resolved": "https://registry.npmmirror.com/@vue/reactivity/-/reactivity-3.5.44.tgz",
"integrity": "sha512-u+QJdKeBBEADkPdevsL+6E12QlYVfBD8Zcw5qjDQKtamI6l14KyqazJMobhCKelhWN5zpyKUiEDoTyHE93cqWw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/shared": "3.5.44"
}
@@ -969,6 +977,7 @@
"resolved": "https://registry.npmmirror.com/@vue/runtime-core/-/runtime-core-3.5.44.tgz",
"integrity": "sha512-uEa/ndwjhrrhnOfb2p+sZy6zeoamJOISqaLSJGk/8R6nABT1ZldpzcJoPzKj+zHVomVBPcmQYyC2r4LtvDV6CQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.44",
"@vue/shared": "3.5.44"
@@ -979,6 +988,7 @@
"resolved": "https://registry.npmmirror.com/@vue/runtime-dom/-/runtime-dom-3.5.44.tgz",
"integrity": "sha512-3fc4ARcXVhVBaJ3ujWiNZJARD6pkyRcwG+ZYhMzjKtKUp7MAY0HLwr7r3Smep3Li6ZaWT6ewdmx8XqdaD5oNZg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/reactivity": "3.5.44",
"@vue/runtime-core": "3.5.44",
@@ -991,6 +1001,7 @@
"resolved": "https://registry.npmmirror.com/@vue/server-renderer/-/server-renderer-3.5.44.tgz",
"integrity": "sha512-R4S1UoH4h5Frrauv8Z5XE5TxV9oBiUSgWIC4TyVK1FK+RocRnOLwFA5Xcmo2011RlgJp+AbZCnw6afrhlgRuUQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-ssr": "3.5.44",
"@vue/runtime-dom": "3.5.44",
@@ -1001,7 +1012,8 @@
"version": "3.5.44",
"resolved": "https://registry.npmmirror.com/@vue/shared/-/shared-3.5.44.tgz",
"integrity": "sha512-H82XLH0DjmSOdbEwO15x3QTo1f5PWEtv237eLpYKc0mqLu+B8hnq16lFWmuBmNurkeiG3wr+oM1FhOll/YVFRg==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@whyour/qinglong-cli": {
"version": "0.1.2",
@@ -1119,6 +1131,7 @@
"resolved": "https://registry.npmmirror.com/aria-query/-/aria-query-5.3.1.tgz",
"integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -1204,6 +1217,7 @@
"resolved": "https://registry.npmmirror.com/axobject-query/-/axobject-query-4.1.0.tgz",
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
"license": "Apache-2.0",
"peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -1397,6 +1411,7 @@
"resolved": "https://registry.npmmirror.com/clsx/-/clsx-2.1.1.tgz",
"integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6"
}
@@ -1457,7 +1472,8 @@
"version": "3.2.3",
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/data-view-buffer": {
"version": "1.0.2",
@@ -1573,7 +1589,8 @@
"version": "5.9.4",
"resolved": "https://registry.npmmirror.com/devalue/-/devalue-5.9.4.tgz",
"integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/docx-preview": {
"version": "0.4.1",
@@ -1895,13 +1912,15 @@
"version": "1.2.2",
"resolved": "https://registry.npmmirror.com/esm-env/-/esm-env-1.2.2.tgz",
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/esrap": {
"version": "2.4.0",
"resolved": "https://registry.npmmirror.com/esrap/-/esrap-2.4.0.tgz",
"integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.4.15"
},
@@ -1918,7 +1937,8 @@
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-2.0.2.tgz",
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/exceljs": {
"version": "4.4.0",
@@ -2615,6 +2635,7 @@
"resolved": "https://registry.npmmirror.com/is-reference/-/is-reference-3.0.3.tgz",
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "^1.0.6"
}
@@ -2937,7 +2958,8 @@
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/locate-character/-/locate-character-3.0.0.tgz",
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/lodash.defaults": {
"version": "4.2.0",
@@ -3023,24 +3045,23 @@
"resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/mailparser": {
"version": "3.9.39",
"resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.9.39.tgz",
"integrity": "sha512-tFIEhwsNR4Xs5aq/8oBtd8aQZv42oLoDGWrne6rT/b3e0hN+o/k1KjaedWLh1NydVK35FiDaOTmGg9ZFhIsfYw==",
"version": "3.12.4",
"resolved": "https://registry.npmjs.org/mailparser/-/mailparser-3.12.4.tgz",
"integrity": "sha512-FdoMF+S89/AQaJHY7StwTfABPHZ8Vey+CDyUno5j+TO0jF0UxM+la4Pe9MeqKqBO4Y9ZMB2eomdyg5i+jzpfZw==",
"license": "MIT",
"dependencies": {
"@zone-eu/mailsplit": "5.4.21",
"encoding-japanese": "2.4.0",
"@zone-eu/mailsplit": "5.4.29",
"he": "1.2.0",
"html-to-text": "10.0.1",
"iconv-lite": "0.7.3",
"libmime": "5.4.8",
"libmime": "5.6.3",
"linkify-it": "5.0.2",
"nodemailer": "10.1.1",
"nodemailer": "10.2.1",
"punycode.js": "2.3.1",
"tlds": "1.261.0"
},
@@ -3048,6 +3069,53 @@
"node": ">=20.0.0"
}
},
"node_modules/mailparser/node_modules/@zone-eu/mailsplit": {
"version": "5.4.29",
"resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.29.tgz",
"integrity": "sha512-CCUNycmUjrV5M0wNf23waWAt9eOHczhjLbUQS7k0FNJvR0py9VSqHFt+tSl/D0+XI73VLG0U+PwYtq9R0zsm9Q==",
"license": "(MIT OR EUPL-1.1+)",
"dependencies": {
"libbase64": "1.4.1",
"libmime": "5.6.3",
"libqp": "3.0.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/mailparser/node_modules/libbase64": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.4.1.tgz",
"integrity": "sha512-Nyh3H90B3gRtrcxIe56Ayy7635J0jmh6AbxbQgQae8wrSPQMH5wFqJChiMTB13yKG512L3YspbA5DzumhFTITA==",
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/mailparser/node_modules/libmime": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/libmime/-/libmime-5.6.3.tgz",
"integrity": "sha512-cuTUW/Jybvh5O4/U9p61gyutHOjDtZyGQYuY99+bfnaFwqcDf2Nb+R6hMHY6DDen2H9wLKQSMpofWUgn2TI5JQ==",
"license": "MIT",
"dependencies": {
"encoding-japanese": "2.4.0",
"iconv-lite": "0.7.3",
"libbase64": "1.4.1",
"libqp": "3.0.1"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/mailparser/node_modules/libqp": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/libqp/-/libqp-3.0.1.tgz",
"integrity": "sha512-7QZxpPX25pga1WiMueduWxmrHMVBFrZPH6ZUaozGYa/H98JH6NVBSET3qVw+4NxzoraIW7rJ81YxSU9IalvCpg==",
"license": "MIT",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -3109,9 +3177,9 @@
}
},
"node_modules/nodemailer": {
"version": "10.1.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.1.tgz",
"integrity": "sha512-pbqZRoeYUO+1E8TJ/11WeY4D2EVujj1hsYjz3qff/vUFDtGnmi7p3iqzTFslYOfQ6PnjVcWxx/CIUSHCSrO/QA==",
"version": "10.2.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.1.tgz",
"integrity": "sha512-ZrDNsPFoDMwefNs7sJwrYiEJ/CG4ClJWDZv05iNJsEBWa8GRDry1QJHTJxsuTAY9eDDKjX4k+q3SxslXJOao7w==",
"license": "MIT-0",
"engines": {
"node": ">=20.0.0"
@@ -3352,7 +3420,6 @@
"resolved": "https://registry.npmmirror.com/preact/-/preact-10.29.8.tgz",
"integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==",
"license": "MIT",
"peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
@@ -3755,14 +3822,14 @@
"version": "0.28.0",
"resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.28.0.tgz",
"integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/selderee": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.12.0.tgz",
"integrity": "sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==",
"license": "MIT",
"peer": true,
"dependencies": {
"parseley": "~0.13.1"
},
@@ -3905,14 +3972,14 @@
}
},
"node_modules/smtp-server": {
"version": "3.19.22",
"resolved": "https://registry.npmjs.org/smtp-server/-/smtp-server-3.19.22.tgz",
"integrity": "sha512-tFAL2UmSPDvxSIpH809XcZ61Pri2uM/8/EmGO4ptf8fAsoOrHbCeyv5jWAVE21zKQk/OEzEQHgJYjfUQF8lFxw==",
"version": "3.21.1",
"resolved": "https://registry.npmjs.org/smtp-server/-/smtp-server-3.21.1.tgz",
"integrity": "sha512-gj95f6YhcL0uu3m3FvRnQ6LSotursugAuVjK5V4f0f2C/4OSVpn/+h28F4pPJFob/myli9V+F7/Hxx9DJVdwvg==",
"dev": true,
"license": "MIT-0",
"dependencies": {
"ipv6-normalize": "1.0.1",
"nodemailer": "10.1.1",
"nodemailer": "10.2.1",
"punycode.js": "2.3.1"
},
"engines": {
@@ -4327,12 +4394,16 @@
"license": "MIT"
},
"node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmmirror.com/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",
"integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/vue": {
@@ -4448,6 +4519,18 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/xlsx": {
"version": "0.20.3",
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",
"license": "Apache-2.0",
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/xmlchars": {
"version": "2.2.0",
"resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz",
@@ -4458,7 +4541,8 @@
"version": "1.1.5",
"resolved": "https://registry.npmmirror.com/zimmerframe/-/zimmerframe-1.1.5.tgz",
"integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/zip-stream": {
"version": "4.1.1",
@@ -4494,18 +4578,6 @@
"engines": {
"node": ">= 10"
}
},
"node_modules/xlsx": {
"version": "0.20.3",
"resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",
"license": "Apache-2.0",
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
}
}
}
+9 -4
View File
@@ -13,7 +13,7 @@
"service:stop": "node scripts/service.cjs stop",
"service:restart": "node scripts/service.cjs restart",
"test": "npm run test:business",
"test:business": "node --test --test-concurrency=1 tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
"test:business": "node --test --test-concurrency=1 tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs",
"test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\""
},
"engines": {
@@ -27,15 +27,20 @@
"exceljs": "4.4.0",
"imapflow": "2.4.3",
"jszip": "3.10.1",
"mailparser": "3.9.39",
"nodemailer": "10.1.1",
"mailparser": "3.12.4",
"nodemailer": "10.2.1",
"photoswipe": "5.4.4",
"playwright-core": "1.62.1",
"sanitize-html": "2.18.1",
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
"html-to-text": "10.0.1"
},
"overrides": {
"exceljs": {
"uuid": "11.1.1"
}
},
"devDependencies": {
"smtp-server": "3.19.22"
"smtp-server": "3.21.1"
}
}
+7 -4
View File
@@ -6,7 +6,7 @@ const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
const {matchesScope}=require('../order-rules/scopes.cjs');
const taskIdentity=require('../order-rules/task-identity.cjs');
const eligibility=require('../order-rules/restricted-test.cjs');
const {collectionBounds,inWindow}=require('../order-rules/window.cjs');
const {collectionBounds,inWindow,upcomingWindow}=require('../order-rules/window.cjs');
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
const clone=value=>structuredClone(value);
class OrderExecutionCoordinator{
@@ -234,7 +234,7 @@ class OrderExecutionCoordinator{
this.store.transaction(()=>require('../order-rules/scope-catalog.cjs').observe(this.store,rows));
if(trustedRows===undefined&&eligibility.state(this.store))eligibility.recordCurrentScan(this.store,{connectionId:connection.id,rows,startedAt:this.query.startedAt,finishedAt:this.now()});
let considered=0;const observed=new Set(),discovered=[];
const window=this.store.snapshot().window;
const window=upcomingWindow(new Date(this.query.startedAt),this.store.schedule(),this.store.calendar());
// Commit the entire discovery set before probes, captures, exceptions or archives yield.
this.store.transaction(()=>{
for(const raw of rows){
@@ -259,7 +259,7 @@ class OrderExecutionCoordinator{
// Pre-activation backlog requires explicit admission. Eligible missed-window work is
// retained below without recapturing, archiving, or widening frozen mail.
if(baseline&&received<Date.parse(baseline)&&!task&&!eligibility.isAdmitted(this.store,row))continue;
const historical=window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row);
const historical=window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row)&&!this.store.intakeWindow(row);
const frozen=historical&&this.store.all('batches').find(batch=>rules.some(rule=>rule.categoryId===batch.categoryId)&&batch.window&&inWindow(eligibleAt,batch.window));
if(historical&&!baseline&&!frozen)continue;
considered++;
@@ -268,6 +268,9 @@ class OrderExecutionCoordinator{
task={id,taskKey:taskIdentity.taskIdentity(row),version:0,connectionId:connection.id,owner:connection.owner||'',row:clone(row),categoryIds:[...new Set(rules.map(r=>r.categoryId))],status:'identified',step:'capture',createdAt:this.now()};
this.persist(task);
}
if(!task.intakeWindow&&window&&inWindow(eligibleAt,window)&&Date.parse(this.query.startedAt)<=Date.parse(window.end)+60000){
task.intakeWindow=clone(window);task.intakeStartedAt=this.query.startedAt;this.persist(task);
}
if(taskIdentity.legacyRevisionMissing(task,row)&&taskIdentity.equivalent(task,row)){
task.legacyRow=task.legacyRow||clone(task.row);task.row=clone(row);task.sourceRevisionMissing={observedAt:this.now(),legacyRevision:'0',reason:'旧归一化默认值未由来源证明;本次真实来源未报告业务修订。'};this.persist(task);
}
@@ -328,7 +331,7 @@ class OrderExecutionCoordinator{
this.reconcileArchive(task);
const order=task.orderId&&this.store.get('orders',task.orderId);
if(!needsRuntimeCheck(order))continue;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start))continue;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start)&&!this.store.intakeWindow(task.row))continue;
await this.checkArchivedRuntime(task,order,connection,principal);
}
if(input.automatic&&!this.store.settings().processingEnabled)throw Error('自动处理已暂停,待处理对账保留到恢复后继续。');
+5 -2
View File
@@ -34,13 +34,15 @@ class OrderRuleDispatcher{
return task;
}
async perform(now){
this.store.expireIntakes?.();
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。');
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
if(!schedule?.times?.length)return;
const signature=JSON.stringify([schedule,calendar]);
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
const cutoff=this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&now-Date.parse(cutoff)<=60000;
const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[];
const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff));
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
if(!canPrepare&&!queued)return;
try{await this.mail.exclusive(config.channelId,async()=>{
@@ -52,7 +54,8 @@ class OrderRuleDispatcher{
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue;
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
const grace=batch.intakeGrace?.cutoff===batch.cutoff&&Date.parse(batch.intakeGrace.expiresAt)===Date.parse(batch.cutoff)+1800000&&Date.parse(batch.createdAt)<=Date.parse(batch.intakeGrace.expiresAt)&&batch.orderIds?.every(id=>{const order=this.store.get('orders',id);return order&&this.store.intakeWindow(order.sample||order.event)?.end===batch.cutoff;});
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000&&!grace||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
});}catch(error){this.store.recordIssue?.('dispatch:'+String(cutoff),{component:'mail',error:error.message,cutoff});if(error.status!==409)throw error;}
// Keep the current slot during its collection allowance so repaired categories retry.
if(cutoff&&this.clock()-Date.parse(cutoff)>60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]};
+1 -1
View File
@@ -152,7 +152,7 @@ function eventInWindow(store,row,window){
}
return require('./window.cjs').inWindow(at,window);
}
function orderInWindow(store,order,window){return eventInWindow(store,order?.sample||order?.event,window);}
function orderInWindow(store,order,window){const row=order?.sample||order?.event;return store.intakeWindow?.(row)?.end===window.end||eventInWindow(store,row,window);}
function assertCurrentPresence(store,row){
const run=state(store),entry=(run?.currentBacklog||[]).find(item=>taskIdentity.sameTask(item.snapshot,row));if(!entry)return;
const scan=store.get('current-task-scans',entry.scanConnectionId),matches=scan?.rows.filter(observed=>taskIdentity.sameTask(observed,row))||[];
+51 -9
View File
@@ -139,6 +139,39 @@ class RuleStore{
const hasEnabledMatch=enabled.some(r=>matchesScope(r,sample));
return hasEnabledMatch?enabled:rules;
}
intakeWindow(sample,{includeExpired=false}={}){
const task=taskIdentity.lookup(this,'execution-tasks',sample);
if(!task||task.removedAt||task.revisionIgnored||task.supersededBy||task.conflict||!task.intakeWindow||!validDate(task.intakeStartedAt))return null;
if(sample?.connectionId!==undefined&&String(sample.connectionId)!==String(task.connectionId))return null;
if(['source','portalSource','instanceId','taskId','revision','processName','nodeName','receivedAt'].some(key=>String(task.row?.[key])!==String(sample?.[key])))return null;
let window;try{window=windowForCutoff(task.intakeWindow.end,this.schedule(),this.calendar());}catch{return null;}
if(task.intakeWindow.start!==window.start||task.intakeWindow.collectionEnd!==window.collectionEnd||!inWindow(eligibility.eventTime(this,sample),window))return null;
const started=Date.parse(task.intakeStartedAt),cutoff=Date.parse(window.end),now=+this.clock();
if(started>cutoff+60000||started< Date.parse(window.start)||started>now||(!includeExpired&&now>cutoff+1800000))return null;
return window;
}
pendingIntakeCutoffs(){
const now=+this.clock();
return [...new Set(this.all('execution-tasks').filter(task=>!['sent','ignored','unknown','sending'].includes(task.status)||task.step==='complete'&&this.pendingCompanion(task.orderId&&this.get('orders',task.orderId))).map(task=>this.intakeWindow(task.row)?.end).filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
}
pendingCompanion(order){
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
}
expireIntakes(){return this.transaction(()=>{
for(const order of this.all('orders')){
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
if(this.pendingCompanion(order)){
updateDelivery(order,'huizhou',{status:'blocked',error:'原处理时段超过30分钟,等待负责人核验。',missedWindow:window});order.updatedAt=this.now();this.put('orders',order);
this.recordIssue('missed:'+order.id+':huizhou',{component:'rules',notificationMode:'huizhou',error:delivery(order,'huizhou').error,window,orderIds:[order.id]});
}
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||order.batchId||order.missedWindow)continue;
order.status='blocked';order.error='原处理时段超过30分钟,等待负责人核验。';order.missedWindow=window;order.updatedAt=this.now();this.put('orders',order);
for(const task of this.all('execution-tasks').filter(task=>task.orderId===order.id&&!['unknown','sending','sent','ignored'].includes(task.status)))this.put('execution-tasks',{...task,status:'blocked',step:'missed_window',missedWindow:window,error:order.error,version:(task.version||0)+1,updatedAt:this.now()});
this.recordIssue('missed:'+order.id,{component:'rules',error:order.error,window,orderIds:[order.id]});
}
});}
ingest(sample,actor){return this.transaction(()=>{
require('./restricted-test.cjs').assertEvent(this,sample);
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
@@ -153,10 +186,11 @@ class RuleStore{
if(rule)require('./restricted-test.cjs').assertRule(this,rule);
const order={id,taskKey,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
order.notifications={huizhou:initialNotification(rule,order.event)};
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
const intake=this.intakeWindow(sample),window=intake||upcomingWindow(this.clock(),this.schedule(),this.calendar());
const eligibleAt=eligibility.eventTime(this,sample);
if(window&&validDate(eligibleAt)&&Date.parse(eligibleAt)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,sample)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&eligibility.eventInWindow(this,sample,b.window));
if(!intake&&this.intakeWindow(sample,{includeExpired:true})){order.status='blocked';order.error='原处理时段超过30分钟,保留采集证据,等待负责人核验。';}
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&(eligibility.eventInWindow(this,sample,b.window)||intake?.end===b.window.end));
if(frozen){order.status='blocked';order.blockedByBatchId=frozen.id;order.error='本接收时段的类别已冻结,新增订单须负责人核验,不能混入已冻结邮件。';this.put('orders',order);this.recordIssue('late:'+order.id,{component:'rules',error:order.error,batchId:frozen.id,orderIds:[order.id]});}
this.put('orders',order);this.audit(actor,'识别订单任务',id);return order;
});}
@@ -167,7 +201,7 @@ class RuleStore{
const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected);
if(!stale){
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
const window=this.intakeWindow(order.sample||order.event)||upcomingWindow(this.clock(),this.schedule(),this.calendar());
if(window&&Date.parse(eligibility.orderTime(this,order))<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event))fail('该订单已超出当前时段,不再自动归档或补发。',409);
}
if(!evidence||!validDate(evidence.archivedAt)||!Array.isArray(evidence.files)||!evidence.files.length||evidence.files.some(f=>!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
@@ -212,7 +246,7 @@ class RuleStore{
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null;
const relevant=this.all('execution-tasks').filter(t=>!window||eligibility.eventInWindow(this,t.row,window));
const relevant=this.all('execution-tasks').filter(t=>!t.removedAt&&(!window||eligibility.eventInWindow(this,t.row,window)));
const sources=new Set([...this.executionSources(),...relevant.filter(t=>!['sent','ignored'].includes(t.status)).map(t=>t.connectionId)]);
for(const id of sources){
if(!allowed(id))continue;
@@ -223,7 +257,7 @@ class RuleStore{
return blockers;
}
categoryIncomplete(categoryId,window){
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window)||this.intakeWindow(task.row)?.end===window.end)&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
}
batchIncomplete(batch){
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));
@@ -251,9 +285,11 @@ class RuleStore{
});
}
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
this.expireIntakes();
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
if(eligibility.state(this)){const current=upcomingWindow(this.clock(),this.schedule(),this.calendar());if(!current?.available||current.end!==window.end)return [];}
const resuming=this.pendingIntakeCutoffs().includes(window.end)&&+this.clock()>Date.parse(window.end)+60000;
if(eligibility.state(this)){const current=upcomingWindow(this.clock(),this.schedule(),this.calendar());if((!current?.available||current.end!==window.end)&&!resuming)return [];}
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
const blockers=this.discoveryBlockers(cutoff);
const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode);
@@ -263,11 +299,16 @@ class RuleStore{
const grouped=new Map(),batches=[];
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
const state=delivery(order,mode);
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||state.missedWindow||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
if(resuming&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||(!state.orderNos?.length&&!state.issues?.length)))continue;
const at=eligibility.orderTime(this,order);
if(validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});updateDelivery(order,mode,{status:'ignored',error:'早于本时段的历史订单,不补发。'});this.put('orders',order);continue;}
if(!eligibility.orderInWindow(this,order,window))continue;
if(validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){
const expired=this.intakeWindow(order.sample||order.event,{includeExpired:true});
this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});
updateDelivery(order,mode,{status:expired?'blocked':'ignored',error:expired?'原处理时段超过30分钟,等待负责人核验。':'早于本时段的历史订单,不补发。',...(expired?{missedWindow:expired}:{})});this.put('orders',order);continue;
}
if(!eligibility.orderInWindow(this,order,window)&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
const key=order.categoryId+':'+mode;if(!grouped.has(key))grouped.set(key,{mode,orders:[]});grouped.get(key).orders.push(order);
}
for(const {mode,orders} of grouped.values()){
@@ -288,6 +329,7 @@ class RuleStore{
const key=resultId(rule.categoryId,mode);
if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});this.put('orders',order);}continue;}
const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
if(resuming)batch.intakeGrace={cutoff:window.end,expiresAt:new Date(Date.parse(window.end)+1800000).toISOString()};
if(rule.testRunId)batch.testRunId=rule.testRunId;
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
if(mode==='normal')batch.huizhouPlanned=rule.huizhouEnabled===true&&orders.some(order=>!!order.notifications?.huizhou);
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
test('upgraded mail dependencies preserve Unicode order subject HTML footer and isolated envelope',async()=>{
const nodemailer=require('nodemailer'),{simpleParser}=require('mailparser');
const transport=nodemailer.createTransport({streamTransport:true,buffer:true,newline:'unix'});
try{
const subject='【海外订单通知书】315477、315437',text='大家好:\n订单号:315477\n订单号:315437\nBest Regards!\n隔离测试签名';
const result=await transport.sendMail({from:{address:'fixture@example.test',name:'隔离发件人'},to:['2639266652@qq.com'],cc:[],subject,text,html:'<p>大家好:</p><div>订单号:315477<br>订单号:315437</div><p>Best Regards!</p>',attachments:[],disableFileAccess:true,disableUrlAccess:true});
assert.deepEqual(result.envelope.to,['2639266652@qq.com']);const message=await simpleParser(result.message);
assert.equal(message.subject,subject);assert.equal(message.from.value[0].name,'隔离发件人');assert.equal(message.text,text);assert.match(message.html,/Best Regards!/);assert.equal(message.attachments.length,0);assert.equal(message.cc,undefined);
}finally{transport.close();}
});
test('ExcelJS UUID override writes extended conditional formatting and round-trips workbook values',async()=>{
const ExcelJS=require('exceljs'),JSZip=require('jszip'),{createRequire}=require('node:module');
const uuid=createRequire(require.resolve('exceljs'))('uuid');assert.throws(()=>uuid.v5('fixture',uuid.v5.DNS,Buffer.alloc(4)),RangeError);
const book=new ExcelJS.Workbook(),sheet=book.addWorksheet('分类规则');sheet.addRows([['适用流程','触发节点','数量'],['海外运营订单评审','订单专员(订单通知书)',200],['国内订单评审','订单通知书',20]]);
sheet.addConditionalFormatting({ref:'C2:C3',rules:[{type:'dataBar',cfvo:[{type:'min'},{type:'max'}],color:{argb:'FF638EC6'},gradient:false,border:true,negativeBarColorSameAsPositive:false}]});
const bytes=await book.xlsx.writeBuffer(),zip=await JSZip.loadAsync(bytes),xml=await zip.file('xl/worksheets/sheet1.xml').async('string');
assert.match(xml,/x14:conditionalFormattings/);assert.match(xml,/id="\{[0-9A-F-]{36}\}"/i);
const loaded=new ExcelJS.Workbook();await loaded.xlsx.load(bytes);assert.equal(loaded.getWorksheet('分类规则').getCell('A2').value,'海外运营订单评审');assert.equal(loaded.getWorksheet('分类规则').getCell('C2').value,200);
});
@@ -0,0 +1,15 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const cutoff='2026-10-26T09:00:00.000Z';
function fixture(removed=true){
const tasks=[{id:'old',removedAt:removed?'2026-10-26T05:58:00Z':undefined,status:'unknown',connectionId:'disabled-old',row:{receivedAt:'2026-10-26T05:00:00Z'}}];
return {tasks,all:k=>k==='execution-tasks'?tasks:[],get:(k,id)=>k==='execution-scans'&&id==='active'?{status:'complete',startedAt:cutoff}:null,executionSources:()=>['active'],schedule:()=>({times:['11:00','17:00'],weekends:false}),calendar:()=>[]};
}
test('removed unknown historical task no longer adds disabled source to fresh batch discovery',()=>{
const s=fixture(),before=structuredClone(s.tasks);assert.deepEqual(RuleStore.prototype.discoveryBlockers.call(s,cutoff),[]);assert.deepEqual(s.tasks,before);
});
test('retained live uncertain tasks and active incomplete sources still block discovery',()=>{
const s=fixture(false);assert.match(RuleStore.prototype.discoveryBlockers.call(s,cutoff).join(' '),/disabled-old/);
const active=fixture();active.get=()=>null;assert.match(RuleStore.prototype.discoveryBlockers.call(active,cutoff).join(' '),/active/);
});
+98
View File
@@ -0,0 +1,98 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs');
const cutoff='2026-10-26T03:00:00.000Z',principal={sessionId:'fixture',user:{username:'admin',role:'admin'}};
function fixture(t,{captureMs=0,archiveMs=0,startMs=0}={}){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'slow-cutoff-'));let now=new Date(Date.parse(cutoff)+startMs),archives=0,captures=0;
const store=new RuleStore(dir,{clock:()=>now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const base=activateReferenceMapping(store).sample,old=store.get('rules','bs-change').draft;
const rule=store.saveRule({...old,archiveDirectory:'\\\\fixture\\orders',to:['2639266652@qq.com'],cc:[],filenameDate:'receivedAt',bodyTemplateId:''},'fixture');store.put('rules',{...store.get('rules',rule.id),published:{...rule,status:'enabled'}});
const row={...base,connectionId:'c1',taskId:'slow',instanceId:'instance',receivedAt:'2026-10-26T02:00:00Z'};
const connection={id:'c1',owner:'admin',status:'connected'},workspace={snapshot:()=>({connections:[connection]}),getConnection:()=>connection};
const provider={scan:async()=>[row],capabilities:async()=>({liveTodo:true,pdfExport:true}),capture:async()=>{captures++;now=new Date(+now+captureMs);return {sample:row,snapshot:{processVersion:row.processVersion,fields:[]}};}};
const archive={supportsRecovery:true,capabilities:async()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{archives++;now=new Date(+now+archiveMs);return {archivedAt:now.toISOString(),files:[{name:'x.pdf',path:'C:\\fixture\\x.pdf',sha256:'a'.repeat(64),size:1,kind:'pdf'}]};}};
const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:()=>now,onException:async()=>{}});
return {dir,store,row,provider,archive,workspace,execution,clock:()=>now,setNow:value=>{now=new Date(value);},counts:()=>({captures,archives})};
}
for(const delays of [{captureMs:61001},{archiveMs:61001},{captureMs:30000,archiveMs:31001}])test(`original intake survives asynchronous cutoff crossing ${JSON.stringify(delays)}`,async t=>{
const f=fixture(t,delays);await f.execution.scan({connectionId:'c1',idempotencyKey:'scan'},principal);
assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.store.all('execution-tasks')[0].step,'complete');assert.equal(f.counts().archives,1);
assert.equal(f.store.prepare(cutoff,'fixture').length,1);
});
test('restart resumes original intake and dispatcher freezes within delivery grace',async t=>{
const f=fixture(t);f.provider.capture=async()=>{throw Error('transient');};await f.execution.scan({connectionId:'c1',idempotencyKey:'failed'},principal);
f.setNow(Date.parse(cutoff)+61001);f.provider.capture=async()=>({sample:f.row,snapshot:{processVersion:f.row.processVersion,fields:[]}});
const store=new RuleStore(f.dir,{clock:f.clock});try{
const resumed=new OrderExecutionCoordinator({...f.execution,store});await resumed.scan({connectionId:'c1',idempotencyKey:'restart'},principal);
assert.equal(store.all('orders')[0]?.status,'pending');
let sends=0;store.put('settings',{...store.get('settings','main'),enabled:true,channelId:'mail'});
const dispatcher=new OrderRuleDispatcher({store,clock:f.clock,settings:()=>({schedule:store.schedule()}),providersReady:()=>true,mail:{exclusive:async(_,fn)=>fn()}});
dispatcher.dispatch=async batch=>{sends++;assert.equal(batch.cutoff,cutoff);};await dispatcher.tick();assert.equal(sends,1);
}finally{store.close();}
});
test('newly observed old arrival after intake allowance cannot join original window',async t=>{
const f=fixture(t,{startMs:61001});await f.execution.scan({connectionId:'c1',idempotencyKey:'late'},principal);assert.equal(f.counts().archives,0);assert.equal(f.store.prepare(cutoff,'fixture').length,0);
});
for(const startMs of [60000,60001])test(`intake start allowance boundary ${startMs}ms`,async t=>{
const f=fixture(t,{startMs,captureMs:1});await f.execution.scan({connectionId:'c1',idempotencyKey:'edge'},principal);assert.equal(f.counts().archives,startMs===60000?1:0);
});
for(const captureMs of [1800000,1800001])test(`original intake completion grace boundary ${captureMs}ms`,async t=>{
const f=fixture(t,{captureMs});await f.execution.scan({connectionId:'c1',idempotencyKey:'grace'},principal);
const order=f.store.all('orders')[0];assert.equal(order.status,captureMs===1800000?'pending':'blocked');assert.equal(f.counts().archives,captureMs===1800000?1:0);
});
test('five minute arrival boundary still defers capture to the following window',async t=>{
const f=fixture(t);f.row.receivedAt='2026-10-26T02:55:00.000Z';await f.execution.scan({connectionId:'c1',idempotencyKey:'arrival'},principal);assert.equal(f.counts().captures,0);assert.equal(f.store.all('execution-tasks')[0].step,'waiting_window');
});
test('original frozen category remains immutable when a slow task finishes',async t=>{
const f=fixture(t,{captureMs:61001});const frozen={id:'frozen',categoryId:'bs-change',cutoff,window:require('../../src/modules/order-rules/window.cjs').windowForCutoff(cutoff,f.store.schedule()),status:'sent',orderIds:[],text:'original'};f.store.put('batches',frozen);
await f.execution.scan({connectionId:'c1',idempotencyKey:'frozen'},principal);assert.equal(f.store.all('orders')[0].status,'blocked');assert.equal(f.counts().archives,0);assert.deepEqual(f.store.get('batches','frozen'),frozen);
});
test('unknown archive outcome cannot be replayed by intake grace after restart',async t=>{
const f=fixture(t);f.archive.supportsRecovery=false;f.archive.archive=async()=>{throw Error('outcome uncertain');};await f.execution.scan({connectionId:'c1',idempotencyKey:'unknown'},principal);
f.setNow(Date.parse(cutoff)+61001);const resumed=new OrderExecutionCoordinator({...f.execution});await resumed.scan({connectionId:'c1',idempotencyKey:'again'},principal);
assert.equal(f.store.all('execution-tasks')[0].status,'unknown');assert.equal(f.store.prepare(cutoff,'fixture').length,0);
});
test('capture enrichment preserves original intake identity through grace',async t=>{
const f=fixture(t,{captureMs:61001}),capture=f.provider.capture;f.provider.capture=async()=>{const result=await capture();result.sample.extraCaptureEvidence='detail';return result;};
await f.execution.scan({connectionId:'c1',idempotencyKey:'enriched'},principal);assert.equal(f.store.all('orders')[0].status,'pending');
});
test('expired original intake remains blocked for review instead of becoming ignored history',async t=>{
const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'finished'},principal);f.setNow('2026-10-26T09:00:00Z');
f.store.prepare('2026-10-26T09:00:00Z','fixture');assert.equal(f.store.all('orders')[0].status,'blocked');assert.match(f.store.all('orders')[0].error,/30分钟/);
});
test('explicit backlog admission retains its accepted time only for the persisted original window',async t=>{
const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'accepted'},principal);
const row=f.store.all('orders')[0].sample,keys=['source','portalSource','taskId','instanceId','revision','processName','nodeName','processVersion','receivedAt'],snapshot=Object.fromEntries(keys.filter(k=>Object.hasOwn(row,k)).map(k=>[k,row[k]])),snapshotHash=require('node:crypto').createHash('sha256').update(JSON.stringify(Object.fromEntries(Object.keys(snapshot).sort().map(k=>[k,snapshot[k]])))).digest('hex');
f.store.put('restricted-test',{id:'main',value:{id:'run',rules:[],enabled:true,currentBacklog:[{snapshot,snapshotHash,testRunId:'run',admittedAt:'2026-10-26T02:00:00Z'}]}});f.setNow(Date.parse(cutoff)+61001);
const restricted=require('../../src/modules/order-rules/restricted-test.cjs'),window=require('../../src/modules/order-rules/window.cjs').windowForCutoff(cutoff,f.store.schedule());
assert.equal(restricted.orderInWindow(f.store,f.store.all('orders')[0],window),true);
f.setNow(Date.parse(cutoff)+1800001);assert.equal(restricted.orderInWindow(f.store,f.store.all('orders')[0],window),false);
});
test('slow source discovery preserves the window at scan start before its first asynchronous read',async t=>{
const f=fixture(t);f.provider.scan=async()=>{f.setNow(Date.parse(cutoff)+61001);return [f.row];};
await f.execution.scan({connectionId:'c1',idempotencyKey:'slow-discovery'},principal);assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.store.prepare(cutoff,'fixture').length,1);
});
async function companionFixture(t,outcome){
const f=fixture(t);await f.execution.scan({connectionId:'c1',idempotencyKey:'dual'},principal);
const order=f.store.all('orders')[0],record=f.store.get('rules','bs-change'),rule={...order.ruleSnapshot,huizhouEnabled:true,huizhouTemplateId:'hui'};
f.store.put('rules',{...record,published:rule});order.ruleSnapshot=rule;order.event.titleOrders=[{orderNo:'H-200',businessMode:'惠州数字',customer:'客户',text:'订单号:H-200业务模式:惠州数字客户简称:客户'}];order.notifications.huizhou={status:'pending',batchId:null,error:null,orderNos:['H-200'],issues:[]};f.store.put('orders',order);
f.store.templateResolver=(_,__,mode)=>{if(mode==='huizhou')throw Error('missing Hui template');return null;};
const batches=f.store.prepare(cutoff,'fixture');assert.equal(batches.length,1);const normal=batches[0];assert.equal(normal.huizhouPlanned,true);
f.store.beginSending(normal.id);f.store.finishSending(normal.id,outcome,'fixture');const task=f.store.all('execution-tasks')[0];f.store.put('execution-tasks',{...task,status:outcome,step:'complete'});
f.store.put('settings',{...f.store.get('settings','main'),enabled:true,channelId:'mail'});
const dispatcher=new OrderRuleDispatcher({store:f.store,clock:f.clock,settings:()=>({schedule:f.store.schedule()}),providersReady:()=>true,mail:{exclusive:async(_,fn)=>fn()}});dispatcher.dispatch=async()=>true;
f.store.templateResolver=(_,__,mode)=>mode==='huizhou'?{id:'hui',version:1,status:'active',notificationMode:'huizhou',subject:'惠州 {{订单号}}',text:'{{订单明细}}',html:'<div>{{订单明细}}</div>'}:null;
return {...f,normal:f.store.get('batches',normal.id),orderId:order.id,dispatcher};
}
for(const outcome of ['sent','unknown'])test(`original Hui companion repairs after normal ${outcome} without changing its frozen receipt`,async t=>{
const f=await companionFixture(t,outcome);f.setNow(Date.parse(cutoff)+61001);await f.dispatcher.tick();
const hui=f.store.all('batches').filter(batch=>batch.notificationMode==='huizhou');assert.equal(hui.length,1);assert.deepEqual(f.store.get('batches',f.normal.id),f.normal);assert.equal(f.store.get('orders',f.orderId).status,outcome);
f.store.beginSending(hui[0].id);f.store.finishSending(hui[0].id,'unknown','unknown fixture');await f.dispatcher.tick();assert.equal(f.store.all('batches').length,2);assert.equal(f.store.get('batches',hui[0].id).status,'unknown');
});
for(const outcome of ['sent','unknown'])test(`expired Hui companion blocks independently of normal ${outcome}`,async t=>{
const f=await companionFixture(t,outcome);f.setNow(Date.parse(cutoff)+1800001);await f.dispatcher.tick();
const order=f.store.get('orders',f.orderId);assert.equal(order.status,outcome);assert.equal(order.notifications.huizhou.status,'blocked');assert.match(order.notifications.huizhou.error,/30分钟/);assert.equal(order.notifications.huizhou.missedWindow.end,cutoff);assert.equal(order.missedWindow,undefined);assert.deepEqual(f.store.get('batches',f.normal.id),f.normal);
});