Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98a752d095 | ||
|
|
7f290467ef | ||
|
|
bd69ec3b83 | ||
|
|
7f61fe29da | ||
|
|
772602aa18 | ||
|
|
db933d2fc3 | ||
|
|
11a9ff8ca3 | ||
|
|
bf3840218d | ||
|
|
ca874fed81 | ||
|
|
29a45f123c |
No files matched your search
@@ -0,0 +1,23 @@
|
|||||||
|
# 字段适配与规则范围快照
|
||||||
|
|
||||||
|
本目录保存 2026-11-30 从生产机导出的配置快照,供换机、重建或后续恢复时核对使用。
|
||||||
|
|
||||||
|
## 文件
|
||||||
|
|
||||||
|
| 文件 | 内容 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `field-adapters.json` | 28 个已验证流程的字段适配 | 只含流程名、表单版本、字段路径(如 `OFR_BS_Applicant.OrderNum`),不含客户、订单号等业务值 |
|
||||||
|
| `rule-scopes.json` | 15 类规则的流程/节点范围、归档目录、收件人、开关状态 | 含内部邮箱与共享路径,属内部资料 |
|
||||||
|
|
||||||
|
## 注意
|
||||||
|
|
||||||
|
- 运行库(`%LOCALAPPDATA%\OrderNotificationAutomation`)中的 SQLite 使用 Windows DPAPI 加密,**不能直接复制到其它机器使用**;本目录的 JSON 是可读快照,用于核对和重建。
|
||||||
|
- 恢复方式:在工作台「字段映射」重新采集并激活,或按本文件逐项核对;规则范围可在「分类通知规则」按此文件恢复。
|
||||||
|
- 本文件含内部服务器路径和邮箱,不要外发。
|
||||||
|
|
||||||
|
## 导出时的状态
|
||||||
|
|
||||||
|
- 已启用 5 类:海外订单通知书、海外订单更改通知书、新零售订单更改通知书、加工订单通知书、备损订单通知书
|
||||||
|
- 海外订单通知书包含三条范围:海外运营/海外宽带接入(订单专员(订单通知书))与海外返工(订单通知书)
|
||||||
|
- 其余 11 类因通知节点未在 BPM 观测到,仍为草稿
|
||||||
|
- 更改/返工类已开启:附归档 PDF、正文无摘要、`{订单号}{YYMMDD}-{序号}.pdf` 命名
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,480 @@
|
|||||||
|
{
|
||||||
|
"exportedAt": "2026-12-01T01:43:32.958Z",
|
||||||
|
"count": 15,
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"id": "overseas-notice",
|
||||||
|
"name": "海外订单通知书",
|
||||||
|
"categoryId": "overseas-notice",
|
||||||
|
"processNames": [
|
||||||
|
"海外运营订单评审",
|
||||||
|
"海外宽带接入产品订单",
|
||||||
|
"海外返工订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)",
|
||||||
|
"订单通知书"
|
||||||
|
],
|
||||||
|
"scopes": [
|
||||||
|
{
|
||||||
|
"processName": "海外运营订单评审",
|
||||||
|
"nodeName": "订单专员(订单通知书)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"processName": "海外宽带接入产品订单",
|
||||||
|
"nodeName": "订单专员(订单通知书)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"processName": "海外返工订单评审",
|
||||||
|
"nodeName": "订单通知书"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-50d87c4da69d2f849b29ab4d",
|
||||||
|
"captured-f31821462f1ed878c3efd825",
|
||||||
|
"captured-c22b21717fef0c4263515247"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\海外订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": true,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "enabled"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "overseas-change",
|
||||||
|
"name": "海外订单更改通知书",
|
||||||
|
"categoryId": "overseas-change",
|
||||||
|
"processNames": [
|
||||||
|
"海外运营订单更改评审",
|
||||||
|
"海外宽带接入产品订单更改评审",
|
||||||
|
"海外IPC订单更改评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-a590749cc497c18b30ce2196",
|
||||||
|
"captured-9c6226ed240b083837df1098",
|
||||||
|
"captured-f1613e4dbed0c9d78e00551f"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\海外订单更改通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "enabled"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "new-retail-notice",
|
||||||
|
"name": "新零售订单通知书",
|
||||||
|
"categoryId": "new-retail-notice",
|
||||||
|
"processNames": [
|
||||||
|
"新零售订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-b92621ce73597761dfe2d8d8"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\新零售订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "new-retail-change",
|
||||||
|
"name": "新零售订单更改通知书",
|
||||||
|
"categoryId": "new-retail-change",
|
||||||
|
"processNames": [
|
||||||
|
"新零售订单更改评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-6d9cfae96ca477262ca7dc25"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\新零售订单更改通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "enabled"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "domestic-notice",
|
||||||
|
"name": "国内订单通知书",
|
||||||
|
"categoryId": "domestic-notice",
|
||||||
|
"processNames": [
|
||||||
|
"国内运营订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-3954e99422b0aed073840364"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\国内订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": true,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "carrier-notice",
|
||||||
|
"name": "运营商事业部订单通知书",
|
||||||
|
"categoryId": "carrier-notice",
|
||||||
|
"processNames": [
|
||||||
|
"宽带事业订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-78aa8ff834b4ef6513c7081a"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\运营商事业部订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "hardware-notice",
|
||||||
|
"name": "智能硬件订单通知书",
|
||||||
|
"categoryId": "hardware-notice",
|
||||||
|
"processNames": [
|
||||||
|
"智能硬件解决方案订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-d2f1eb7a587fb18ed73a3e4d"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\智能硬件订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "retail-notice",
|
||||||
|
"name": "小湃订单通知书",
|
||||||
|
"categoryId": "retail-notice",
|
||||||
|
"processNames": [
|
||||||
|
"零售国内订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-aaf78a153a290943c4848d5c"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\小湃订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "domestic-change",
|
||||||
|
"name": "国内、运营商事业部、零售、智能硬件订单更改通知书",
|
||||||
|
"categoryId": "domestic-change",
|
||||||
|
"processNames": [
|
||||||
|
"国内运营订单更改评审",
|
||||||
|
"宽带事业订单更改评审",
|
||||||
|
"智能硬件解决方案订单更改评审",
|
||||||
|
"零售国内订单更改评审",
|
||||||
|
"国内、宽带返工订单更改评审",
|
||||||
|
"零售国内返工订单更改评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-b87df1437221902b0f7b13a8",
|
||||||
|
"captured-6b689649e00e5e0f261c0028",
|
||||||
|
"captured-a35c6da0c662a5012cc931a7",
|
||||||
|
"captured-cf3c668d39daaa63a2d02475",
|
||||||
|
"captured-9466133ecccd9108b2106005"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\国内、运营商事业部、零售、智能硬件订单更改通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "domestic-rework",
|
||||||
|
"name": "国内、运营商事业部、零售、智能硬件返工订单通知书",
|
||||||
|
"categoryId": "domestic-rework",
|
||||||
|
"processNames": [
|
||||||
|
"国内、宽带返工订单评审",
|
||||||
|
"零售国内返工订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-5dd70c6a461e9b6d35517224",
|
||||||
|
"captured-6a800fad5e4e30a9ef435b4f"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\国内、运营商事业部、零售、智能硬件返工订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "processing-notice",
|
||||||
|
"name": "加工订单通知书",
|
||||||
|
"categoryId": "processing-notice",
|
||||||
|
"processNames": [
|
||||||
|
"加工订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(激活)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-3e2bb4f72814128f048b4edb"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\加工订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "enabled"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bs-notice",
|
||||||
|
"name": "备损订单通知书",
|
||||||
|
"categoryId": "bs-notice",
|
||||||
|
"processNames": [
|
||||||
|
"备损订单评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-c1d1c24be1fba564f00f7db1"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\备损订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": true,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "enabled"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bs-change",
|
||||||
|
"name": "备损订单更改通知书",
|
||||||
|
"categoryId": "bs-change",
|
||||||
|
"processNames": [
|
||||||
|
"备损订单更改评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-5cd554aa4d69bbf8398e110e"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\备损订单更改通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "trial-notice",
|
||||||
|
"name": "试产订单通知书",
|
||||||
|
"categoryId": "trial-notice",
|
||||||
|
"processNames": [
|
||||||
|
"试产订单评审",
|
||||||
|
"中试样机制作申请",
|
||||||
|
"研发样机制作申请"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)-海外",
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-40d5f903daf655f77f770041",
|
||||||
|
"captured-b11f8463359273826b7afc91",
|
||||||
|
"captured-a6afedfdf9890bdadf1b6546"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\试产订单通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": false,
|
||||||
|
"attachPdf": false,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "trial-change",
|
||||||
|
"name": "试产订单更改通知书",
|
||||||
|
"categoryId": "trial-change",
|
||||||
|
"processNames": [
|
||||||
|
"试产订单更改评审"
|
||||||
|
],
|
||||||
|
"nodeNames": [
|
||||||
|
"订单专员(订单通知书)-海外",
|
||||||
|
"订单专员(订单通知书)"
|
||||||
|
],
|
||||||
|
"scopes": null,
|
||||||
|
"adapterIds": [
|
||||||
|
"captured-d1bf63ceae571a5991a47d76"
|
||||||
|
],
|
||||||
|
"archiveDirectory": "\\\\192.168.8.210\\SVR\\订单通知内部测试-2026-11\\试产订单更改通知书",
|
||||||
|
"filenameDate": "receivedAt",
|
||||||
|
"filenameScheme": "orderDateSeq",
|
||||||
|
"archiveOrderFolder": false,
|
||||||
|
"keepTitleVerbatim": false,
|
||||||
|
"bodyWithoutSummary": true,
|
||||||
|
"attachPdf": true,
|
||||||
|
"to": [
|
||||||
|
"baijiahao@skyworth.com",
|
||||||
|
"liuzeshi@skyworth.com",
|
||||||
|
"liuhuan01@skyworth.com"
|
||||||
|
],
|
||||||
|
"cc": [],
|
||||||
|
"status": "draft"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
require('../platform/tls-system-ca.cjs');
|
||||||
const crypto = require('node:crypto');
|
const crypto = require('node:crypto');
|
||||||
const fs = require('node:fs/promises');
|
const fs = require('node:fs/promises');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
@@ -109,10 +110,11 @@ async function main(options = {}) {
|
|||||||
workspace.markSessionChecksPending();
|
workspace.markSessionChecksPending();
|
||||||
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
|
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
|
||||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true,updateChecker:createUpdateChecker({currentVersion:appVersion})});
|
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true,updateChecker:createUpdateChecker({currentVersion:appVersion})});
|
||||||
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();bpmMonitor.start();
|
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();bpmMonitor.start();{let lastSlot='';const slotTimer=setInterval(()=>{try{const hm=new Intl.DateTimeFormat('en-GB',{timeZone:'Asia/Shanghai',hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date());const times=store.settings().schedule?.times||[];if(times.includes(hm)&&lastSlot!==hm){lastSlot=hm;bpmMonitor.rescanNow().catch(()=>{});}}catch{}},15000);slotTimer.unref?.();}
|
||||||
health.start();
|
health.start();
|
||||||
orderExecution.start();
|
orderExecution.start();
|
||||||
orderDispatcher.start();
|
orderDispatcher.start();
|
||||||
|
orderExecution.warmup(custodian.principal).then(result=>{if(!result?.started)console.warn('运行能力预热未完成:'+(result?.error||'未知原因'));}).catch(error=>console.warn('运行能力预热失败:'+error.message));
|
||||||
if(!options.quiet){
|
if(!options.quiet){
|
||||||
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
|
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
|
||||||
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
|
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class BpmArrivalMonitor{
|
|||||||
let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)};
|
let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)};
|
||||||
}
|
}
|
||||||
updateInterval(entry,config){if(entry.intervalMinutes===config.intervalMinutes)return;entry.intervalMinutes=config.intervalMinutes;entry.nextReconcile=(entry.lastReconcileAt??this.clock())+config.intervalMinutes*60000;}
|
updateInterval(entry,config){if(entry.intervalMinutes===config.intervalMinutes)return;entry.intervalMinutes=config.intervalMinutes;entry.nextReconcile=(entry.lastReconcileAt??this.clock())+config.intervalMinutes*60000;}
|
||||||
async reconfigure(){await this.tick();}
|
async reconfigure(){await this.tick();} async rescanNow(){if(this.stopped)return;for(const entry of this.entries.values()){entry.nextReconcile=0;for(const kind of ['todo','inform'])this.source(entry,kind).nextAttempt=0;this.queue(entry,['todo','inform']);}await this.tick();}
|
||||||
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),this.pollMs);this.timer.unref?.();this.tick().catch(()=>{});}
|
start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),this.pollMs);this.timer.unref?.();this.tick().catch(()=>{});}
|
||||||
async tick(){
|
async tick(){
|
||||||
if(this.stopped)return;const config=this.scanner.store.config(),connections=this.workspace.snapshot().connections,ids=new Set(connections.map(c=>c.id));
|
if(this.stopped)return;const config=this.scanner.store.config(),connections=this.workspace.snapshot().connections,ids=new Set(connections.map(c=>c.id));
|
||||||
@@ -88,7 +88,7 @@ class BpmArrivalMonitor{
|
|||||||
// Delivery has its own persisted outcome; a callback cannot rewrite a committed read.
|
// Delivery has its own persisted outcome; a callback cannot rewrite a committed read.
|
||||||
if(delivery)await this.publishPending(id,canCommit).catch(()=>{});
|
if(delivery)await this.publishPending(id,canCommit).catch(()=>{});
|
||||||
return {...result,runId};
|
return {...result,runId};
|
||||||
}catch(error){this.scanner.store.fail(runId,error.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;}
|
}catch(error){const detail=String(error?.message||'').replace(/[\r\n\x00-\x1f]+/g,' ').trim().slice(0,120);this.scanner.store.fail(runId,error.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':detail?`待办对账失败(${detail}),请稍后重试。`:'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;}
|
||||||
}).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise};
|
}).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise};
|
||||||
}
|
}
|
||||||
publishPending(id,canDeliver=()=>true){
|
publishPending(id,canDeliver=()=>true){
|
||||||
|
|||||||
@@ -129,11 +129,24 @@ class OrderExecutionCoordinator{
|
|||||||
listFieldSamples(input,principal){return require('./field-samples.cjs').listFieldSamples(this,input,principal);}
|
listFieldSamples(input,principal){return require('./field-samples.cjs').listFieldSamples(this,input,principal);}
|
||||||
captureFieldSample(input,principal){return require('./field-samples.cjs').captureFieldSample(this,input,principal);}
|
captureFieldSample(input,principal){return require('./field-samples.cjs').captureFieldSample(this,input,principal);}
|
||||||
connection(id,principal){const c=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal?.user?.role)||(principal.user.role!=='admin'&&c.owner!==principal.user.username))fail('仅连接负责人或管理员可以扫描或重试。',403);if(c.status==='disabled')fail('连接已停用。',409);return c;}
|
connection(id,principal){const c=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal?.user?.role)||(principal.user.role!=='admin'&&c.owner!==principal.user.username))fail('仅连接负责人或管理员可以扫描或重试。',403);if(c.status==='disabled')fail('连接已停用。',409);return c;}
|
||||||
async refreshCapabilities(rule){
|
async warmup(principal){
|
||||||
|
// Restart clears in-memory runtime capabilities; re-prove them before the next send window.
|
||||||
|
if(this.stopped)return {started:false,error:'服务正在关闭'};
|
||||||
|
let rule=null;
|
||||||
|
try{rule=this.store.all('rules').map(record=>this.store.executionRule(record)).find(item=>item?.status==='enabled'&&item.archiveDirectory)||null;}catch{}
|
||||||
|
let connection=null;
|
||||||
|
try{connection=this.workspace.snapshot().connections.find(item=>item.status==='connected')||null;}catch{}
|
||||||
|
if(connection&&typeof this.provider.scan==='function'){
|
||||||
|
try{await this.provider.scan(connection,principal);}catch(error){this.blockers.push('启动预热待办扫描失败:'+error.message);}
|
||||||
|
}
|
||||||
|
if(!rule)return {started:false,error:'没有已启用且配置归档目录的规则'};
|
||||||
|
try{await this.refreshCapabilities(rule);}catch(error){return {started:false,error:error.message};}
|
||||||
|
return {started:true,ruleId:rule.id,connectionId:connection?.id||null};
|
||||||
|
}async refreshCapabilities(rule){
|
||||||
let p={},a={};this.blockers=[];
|
let p={},a={};this.blockers=[];
|
||||||
try{p=await this.provider.capabilities();}catch(error){this.blockers.push('待办提供器探测失败:'+error.message);}
|
try{p=await this.provider.capabilities();}catch(error){this.blockers.push('待办提供器探测失败:'+error.message);}
|
||||||
try{a=rule&&this.archive.probe?await this.archive.probe(rule):await this.archive.capabilities();}catch(error){this.blockers.push('归档运行条件探测失败:'+error.message);}
|
try{a=rule&&this.archive.probe?await this.archive.probe(rule):await this.archive.capabilities();}catch(error){this.blockers.push('归档运行条件探测失败:'+error.message);}
|
||||||
const capabilities={liveTodo:p.liveTodo===true,pdfExport:p.pdfExport===true&&a.pdfExport===true,automaticArchive:a.automaticArchive===true};
|
const capabilities={liveTodo:p.liveTodo===true,pdfExport:a.pdfExport===true,automaticArchive:a.automaticArchive===true};
|
||||||
for(const key of Object.keys(capabilities))if(!capabilities[key])this.blockers.push(key+' 尚未通过实际探测。');this.store.capabilities=capabilities;return capabilities;
|
for(const key of Object.keys(capabilities))if(!capabilities[key])this.blockers.push(key+' 尚未通过实际探测。');this.store.capabilities=capabilities;return capabilities;
|
||||||
}
|
}
|
||||||
canRetry(task,principal){
|
canRetry(task,principal){
|
||||||
@@ -357,7 +370,10 @@ class OrderExecutionCoordinator{
|
|||||||
finally{
|
finally{
|
||||||
this.store.put('execution-query',this.query);
|
this.store.put('execution-query',this.query);
|
||||||
const preserveNewer=this.query.status==='complete'&&previousScan?.status==='complete'&&Date.parse(previousScan.startedAt)>Date.parse(this.query.startedAt);
|
const preserveNewer=this.query.status==='complete'&&previousScan?.status==='complete'&&Date.parse(previousScan.startedAt)>Date.parse(this.query.startedAt);
|
||||||
this.store.put('execution-scans',preserveNewer?previousScan:{...this.query,id:connection.id});
|
const lastCompleteStartedAt=this.query.status==='complete'?(preserveNewer?previousScan.startedAt:this.query.startedAt):(previousScan?.lastCompleteStartedAt||(previousScan?.status==='complete'?previousScan.startedAt:null));
|
||||||
|
const savedScan=preserveNewer?{...previousScan}:({...this.query,id:connection.id});
|
||||||
|
if(lastCompleteStartedAt)savedScan.lastCompleteStartedAt=lastCompleteStartedAt;
|
||||||
|
this.store.put('execution-scans',savedScan);
|
||||||
}
|
}
|
||||||
return this.snapshot(principal);
|
return this.snapshot(principal);
|
||||||
}).finally(()=>{this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal));
|
}).finally(()=>{this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal));
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notifica
|
|||||||
const start=window?Date.parse(window.start):null,end=window?Date.parse(window.end):null;
|
const start=window?Date.parse(window.start):null,end=window?Date.parse(window.end):null;
|
||||||
if(window&&(!Number.isFinite(start)||!Number.isFinite(end)||start>=end||end!==limit||window.startInclusive!==true||window.endInclusive!==false))fail('邮件时段窗口无效。');
|
if(window&&(!Number.isFinite(start)||!Number.isFinite(end)||start>=end||end!==limit||window.startInclusive!==true||window.endInclusive!==false))fail('邮件时段窗口无效。');
|
||||||
if(!rule?.categoryId||!Array.isArray(orders)||!orders.length)fail('类别必须包含待发订单。');
|
if(!rule?.categoryId||!Array.isArray(orders)||!orders.length)fail('类别必须包含待发订单。');
|
||||||
if(rule.attachPdf===true)fail('业务通知禁止附件,请先将类别 attachPdf 设置为 false;PDF 归档仍为前置条件。');
|
|
||||||
const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
|
const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
|
||||||
if(!to.length)fail('收件人名单不能为空。');
|
if(!to.length)fail('收件人名单不能为空。');
|
||||||
const orderIds=[],attachments=[];
|
const orderIds=[],attachments=[];
|
||||||
@@ -48,15 +47,16 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notifica
|
|||||||
if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
|
if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
|
||||||
if(!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
|
if(!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
|
||||||
orderIds.push(order.id);
|
orderIds.push(order.id);
|
||||||
|
if(rule.attachPdf===true)for(const file of order.archive.files)if(file.kind==='pdf'&&/\.pdf$/i.test(file.name)&&!attachments.some(item=>item.path===file.path))attachments.push({name:file.name,path:file.path,sha256:file.sha256,size:file.size,kind:'pdf'});
|
||||||
}
|
}
|
||||||
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
|
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
|
||||||
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
|
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
|
||||||
const content=mailContent(orders),orderNos=content.orderNos;
|
const content=mailContent(orders),orderNos=content.orderNos;
|
||||||
const snapshot={categoryId:rule.categoryId,subject:`${prefix} ${orderNos.join('、')}`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()};
|
const snapshot={categoryId:rule.categoryId,attachPdf:rule.attachPdf===true,subject:`${prefix} ${orderNos.join('、')}`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()};
|
||||||
snapshot.notificationMode=notificationMode;
|
snapshot.notificationMode=notificationMode;
|
||||||
{
|
{
|
||||||
snapshot.text=[rule.intro,content.details,notificationMode==='huizhou'?'':'存放地址:'+content.directories.join('\n'),rule.signature].filter(Boolean).join('\n\n');
|
const detailText=rule.bodyWithoutSummary===true?'':content.details;snapshot.text=[rule.intro,detailText,notificationMode==='huizhou'?'':'存放地址:'+content.directories.join('\n'),rule.signature].filter(Boolean).join('\n\n');
|
||||||
snapshot.html='<div>'+lines(rule.intro)+'</div>'+content.htmlDetails+(notificationMode==='huizhou'?'':content.htmlDirectories)+'<div>'+lines(rule.signature)+'</div>';
|
snapshot.html='<div>'+lines(rule.intro)+'</div>'+(rule.bodyWithoutSummary===true?'':content.htmlDetails)+(notificationMode==='huizhou'?'':content.htmlDirectories)+'<div>'+lines(rule.signature)+'</div>';
|
||||||
}
|
}
|
||||||
if(window){snapshot.window=structuredClone(window);snapshot.windowStart=new Date(start).toISOString();snapshot.windowEnd=new Date(end).toISOString();}
|
if(window){snapshot.window=structuredClone(window);snapshot.windowStart=new Date(start).toISOString();snapshot.windowEnd=new Date(end).toISOString();}
|
||||||
// MIME headers, encoded-word subjects, base64 wrapping, attachment metadata and
|
// MIME headers, encoded-word subjects, base64 wrapping, attachment metadata and
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ function readList(store,{cutoff}={}){
|
|||||||
return [...groups.values()].map(group=>{
|
return [...groups.values()].map(group=>{
|
||||||
const {rule,orders,...value}=group,saved=store.get('batch-content-drafts',group.id);let template,sourceError;try{template=store.templateResolver?.(rule.categoryId,rule,group.notificationMode);}catch(error){sourceError=error.message;}let base;try{base=definition(store,rule,window.end,group.notificationMode,template);}catch(error){sourceError=error.message;base={context:digest([rule,window.end,group.notificationMode]),subject:rule.subjectPrefix||rule.name,format:'text',body:'{{订单明细}}\n{{存放地址}}'};}
|
const {rule,orders,...value}=group,saved=store.get('batch-content-drafts',group.id);let template,sourceError;try{template=store.templateResolver?.(rule.categoryId,rule,group.notificationMode);}catch(error){sourceError=error.message;}let base;try{base=definition(store,rule,window.end,group.notificationMode,template);}catch(error){sourceError=error.message;base={context:digest([rule,window.end,group.notificationMode]),subject:rule.subjectPrefix||rule.name,format:'text',body:'{{订单明细}}\n{{存放地址}}'};}
|
||||||
const row={...value,carriedOrderIds:orders.filter(o=>require('./carry-forward.cjs').windowForOrder(store,o,group.notificationMode)?.end===window.end).map(o=>o.id),version:saved?.version||0,context:base.context,editor:saved?{subject:saved.subject,format:saved.format,body:saved.body}:base,edited:!!saved,editable:!sourceError&&+store.clock()<Date.parse(window.end),subject:saved?.subject||base.subject,to:rule.to,cc:rule.cc||[],orderNos:orders.map(o=>o.event?.orderNo).filter(Boolean),ruleSnapshot:rule};
|
const row={...value,carriedOrderIds:orders.filter(o=>require('./carry-forward.cjs').windowForOrder(store,o,group.notificationMode)?.end===window.end).map(o=>o.id),version:saved?.version||0,context:base.context,editor:saved?{subject:saved.subject,format:saved.format,body:saved.body}:base,edited:!!saved,editable:!sourceError&&+store.clock()<Date.parse(window.end),subject:saved?.subject||base.subject,to:rule.to,cc:rule.cc||[],orderNos:orders.map(o=>o.event?.orderNo).filter(Boolean),ruleSnapshot:rule};
|
||||||
try{if(sourceError)fail(sourceError,409);const snapshot=require('./template.cjs').composeBatch(rule,require('./huizhou.cjs').ordersForMode(orders,group.notificationMode),window.end,store,{window,notificationMode:group.notificationMode});Object.assign(row,{subject:snapshot.subject,text:snapshot.text,html:snapshot.html,template:snapshot.template,signature:snapshot.signature});}
|
try{if(sourceError)fail(sourceError,409);const snapshot=require('./template.cjs').composeBatch(rule,require('./huizhou.cjs').ordersForMode(orders,group.notificationMode),window.end,store,{window,notificationMode:group.notificationMode});Object.assign(row,{subject:snapshot.subject,text:snapshot.text,html:snapshot.html,attachments:snapshot.attachments||[],template:snapshot.template,signature:snapshot.signature});}
|
||||||
catch(error){row.error=error.message;row.text='';row.html='';}
|
catch(error){row.error=error.message;row.text='';row.html='';}
|
||||||
return row;
|
return row;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ function discoveryBlockers(store,cutoff,allowed=()=>true){
|
|||||||
if(store.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
if(store.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||||
for(const id of sources){
|
for(const id of sources){
|
||||||
const scan=store.get('execution-scans',id);
|
const scan=store.get('execution-scans',id);
|
||||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
const completedAt=scan?.status==='complete'?scan.startedAt:scan?.lastCompleteStartedAt;
|
||||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
if(!completedAt)blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||||
|
else if(cutoff&&Date.parse(completedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描'+(scan?.status!=='complete'&&scan?.error?':'+scan.error:'。'));
|
||||||
}
|
}
|
||||||
return blockers;
|
return blockers;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,34 @@ const {nextSlots}=require('../../shared/schedule.cjs');
|
|||||||
const {windowForCutoff}=require('./window.cjs');
|
const {windowForCutoff}=require('./window.cjs');
|
||||||
const {fail}=require('./validation.cjs');
|
const {fail}=require('./validation.cjs');
|
||||||
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
||||||
function assertMailPolicy(batch){
|
function assertMailPolicy(batch,settings){
|
||||||
const blocked=message=>{throw Object.assign(new Error(message),{status:409,code:'MAIL_POLICY_BLOCKED'});};
|
const blocked=message=>{throw Object.assign(new Error(message),{status:409,code:'MAIL_POLICY_BLOCKED'});};
|
||||||
if(!Array.isArray(batch.to)||batch.to.length!==1||batch.to[0]!=='2639266652@qq.com'||!Array.isArray(batch.cc)||batch.cc.length)blocked('当前分类通知只允许固定 QQ 2639266652@qq.com,且不得抄送。');
|
const domains=Array.isArray(settings?.allowedDomains)?settings.allowedDomains:[];
|
||||||
if(!Array.isArray(batch.attachments)||batch.attachments.length)blocked('当前分类通知禁止 PDF 或其他附件;旧冻结批次必须先核验处理。');
|
if(domains.length){
|
||||||
|
const recipients=(Array.isArray(batch.to)?batch.to:[]).map(address=>String(address||'').trim().toLowerCase());
|
||||||
|
if(!recipients.length||!recipients.every(address=>domains.some(domain=>address.endsWith('@'+domain))))blocked('收件人不在允许的公司邮箱域名内,发送已阻断。');
|
||||||
|
if(!Array.isArray(batch.cc)||batch.cc.length)blocked('当前策略不允许抄送。');
|
||||||
|
}else if(!Array.isArray(batch.to)||batch.to.length!==1||batch.to[0]!=='2639266652@qq.com'||!Array.isArray(batch.cc)||batch.cc.length)blocked('当前分类通知只允许固定 QQ 2639266652@qq.com,且不得抄送。');
|
||||||
|
if(Array.isArray(batch.attachments)&&batch.attachments.length){
|
||||||
|
if(batch.attachPdf!==true)blocked('当前分类通知禁止附件;仅附归档 PDF 的类别可以携带附件。');
|
||||||
|
if(batch.attachments.some(file=>!file||file.kind!=='pdf'||!/\.pdf$/i.test(String(file.name||''))))blocked('邮件附件仅允许已归档的 PDF 文件。');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatPreflightError(error){
|
||||||
|
if(error?.code==='MAIL_POLICY_BLOCKED'||error?.message==='归档文件校验失败。')return error.message;
|
||||||
|
if(error?.code==='ENOENT')return '归档文件不存在。';
|
||||||
|
const raw=String(error?.message||error?.code||'').replace(/[\r\n\x00-\x1f]+/g,' ').trim().slice(0,220);
|
||||||
|
const code=typeof error?.code==='string'&&error.code&&!raw.includes(error.code)?error.code+': ':'';
|
||||||
|
const detail=(code+raw).trim();
|
||||||
|
if(/UNABLE_TO_VERIFY|CERT_|SELF_SIGNED|TLS|certificate/i.test(detail))return `SMTP TLS 证书校验失败(${detail}),请检查邮件服务器证书链与系统根证书。`;
|
||||||
|
return detail?`请检查归档证据、SMTP 与启用状态(${detail})。`:'请检查归档证据、SMTP 与启用状态。';
|
||||||
|
}
|
||||||
|
function isTransientPreflightError(error){
|
||||||
|
const text=String(error?.message||'');
|
||||||
|
if(/UNABLE_TO_VERIFY|CERT_HAS_EXPIRED|SELF_SIGNED_CERT|DEPTH_ZERO_SELF_SIGNED|ERR_TLS_CERT_ALTNAME_INVALID|certificate/i.test(String(error?.code||'')+' '+text))return false;
|
||||||
|
return ['ETIMEDOUT','ECONNRESET','ECONNREFUSED','ECONNECTION','EAI_AGAIN','EPIPE','ESOCKET','EHOSTUNREACH','ENETUNREACH','UND_ERR_CONNECT_TIMEOUT'].includes(error?.code)||[502,503,504].includes(error?.status)||/ETIMEDOUT|ECONNRESET|ECONNREFUSED|ECONNECTION|EAI_AGAIN|socket hang up|网络|连接超时|存储操作超时/i.test(text);
|
||||||
|
}
|
||||||
function freeze(value){
|
function freeze(value){
|
||||||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||||||
return value;
|
return value;
|
||||||
@@ -23,6 +45,17 @@ class OrderRuleDispatcher{
|
|||||||
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
|
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
|
||||||
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
|
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;if(mail?.store?.signature)store.signatureResolver=id=>mail.store.signature(id);
|
||||||
}
|
}
|
||||||
|
warnStalledBatches(now){
|
||||||
|
for(const batch of this.store.all('batches')){
|
||||||
|
const age=now-Date.parse(batch.cutoff);
|
||||||
|
if(batch.status==='prepared'&&!batch.manual&&!batch.submissionAttemptedAt&&!batch.dispatchWarning&&age>120000&&age<=1800000){
|
||||||
|
const updated={...batch,version:(batch.version||1)+1,dispatchWarning:this.clock().toISOString()};
|
||||||
|
this.store.put?.('batches',updated);
|
||||||
|
this.store.recordIssue?.('dispatch-warning:'+batch.id,{component:'mail',batchId:batch.id,error:'批次已冻结超过2分钟仍未提交SMTP,请检查发送闸门。',orderIds:batch.orderIds,cutoff:batch.cutoff});
|
||||||
|
this.store.audit?.('系统发送','冻结未发告警',batch.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
ready(){
|
ready(){
|
||||||
// Real RuleStore exposes immutable capabilities directly; retain the small
|
// Real RuleStore exposes immutable capabilities directly; retain the small
|
||||||
// snapshot fallback for adapters and older test/runtime stores.
|
// snapshot fallback for adapters and older test/runtime stores.
|
||||||
@@ -38,6 +71,7 @@ class OrderRuleDispatcher{
|
|||||||
async perform(now){
|
async perform(now){
|
||||||
this.store.expireIntakes?.();
|
this.store.expireIntakes?.();
|
||||||
for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
|
for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
|
||||||
|
this.warnStalledBatches(now);
|
||||||
if(!this.ready())return;
|
if(!this.ready())return;
|
||||||
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
|
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||||
if(!schedule?.times?.length)return;
|
if(!schedule?.times?.length)return;
|
||||||
@@ -48,16 +82,17 @@ class OrderRuleDispatcher{
|
|||||||
const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||||
if(!canPrepare&&!queued)return;
|
if(!canPrepare&&!queued)return;
|
||||||
try{await this.mail.exclusive(config.channelId,async()=>{
|
try{await this.mail.exclusive(config.channelId,async()=>{
|
||||||
|
this.warnStalledBatches(this.clock());
|
||||||
if(!this.ready())return;
|
if(!this.ready())return;
|
||||||
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
|
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
|
||||||
// A frozen collection is immutable. Queue time is distinct from collection time.
|
// A frozen collection is immutable. Queue time is distinct from collection time.
|
||||||
const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||||
for(const batch of batches){if(!this.ready())break;
|
for(const batch of batches){if(!this.ready())break;if(batch.retryAt&&Date.parse(batch.retryAt)>this.clock().getTime())continue;
|
||||||
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
|
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';
|
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.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;
|
||||||
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||require('./carry-forward.cjs').windowForOrder(this.store,order,modeOf(batch))?.end===batch.cutoff);});
|
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||require('./carry-forward.cjs').windowForOrder(this.store,order,modeOf(batch))?.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;}
|
const prepareSkewMs=15000;if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000+prepareSkewMs&&!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;}
|
});}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.
|
// 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]};
|
if(cutoff&&this.clock()-Date.parse(cutoff)>60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]};
|
||||||
@@ -80,7 +115,7 @@ class OrderRuleDispatcher{
|
|||||||
if(batch.status!=='prepared')return false;
|
if(batch.status!=='prepared')return false;
|
||||||
let transport,sending=false;
|
let transport,sending=false;
|
||||||
try{
|
try{
|
||||||
assertMailPolicy(batch);
|
assertMailPolicy(batch,config);
|
||||||
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
||||||
if(batch.channelId&&batch.channelId!==config.channelId){
|
if(batch.channelId&&batch.channelId!==config.channelId){
|
||||||
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。',{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()});return;
|
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。',{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()});return;
|
||||||
@@ -98,7 +133,7 @@ class OrderRuleDispatcher{
|
|||||||
if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
|
if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
|
||||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
||||||
this.mail.store.guard(channel.id,channel.version);
|
this.mail.store.guard(channel.id,channel.version);
|
||||||
assertMailPolicy(batch);
|
assertMailPolicy(batch,config);
|
||||||
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
||||||
this.store.beginSending(batch.id,{manual});sending=true;
|
this.store.beginSending(batch.id,{manual});sending=true;
|
||||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||||
@@ -107,9 +142,10 @@ class OrderRuleDispatcher{
|
|||||||
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
||||||
}catch(error){
|
}catch(error){
|
||||||
if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
||||||
|
if(!manual&&!sending&&isTransientPreflightError(error)&&(batch.retryCount||0)<3&&this.clock()-Date.parse(batch.cutoff)<1800000){const retryCount=(batch.retryCount||0)+1;this.store.put?.('batches',{...batch,version:(batch.version||1)+1,retryCount,retryAt:new Date(this.clock().getTime()+Math.min(60000,15000*retryCount)).toISOString(),lastError:String(error.message||error.code||'').slice(0,300)});this.store.audit?.('系统发送','发送暂不可用,安排重试',batch.id+' 第'+retryCount+'次:'+String(error.message||error.code||'').slice(0,120));return;}
|
||||||
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
|
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
|
||||||
const evidence=!sending?{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()}:rejected?{outcome:'all_recipients_rejected',phase:'smtp_envelope',at:this.clock().toISOString()}:undefined;
|
const evidence=!sending?{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()}:rejected?{outcome:'all_recipients_rejected',phase:'smtp_envelope',at:this.clock().toISOString()}:undefined;
|
||||||
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='MAIL_POLICY_BLOCKED'?error.message:error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`,evidence);
|
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${formatPreflightError(error)}`,evidence);
|
||||||
}finally{
|
}finally{
|
||||||
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
|
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,14 +37,14 @@ function previewImport(store,input,actor,{mail}={}){
|
|||||||
if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人'));
|
if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人'));
|
||||||
if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址');
|
if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址');
|
||||||
if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];}
|
if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];}
|
||||||
if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');}
|
if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value)&&old.attachPdf!==true)row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');}
|
||||||
else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value))row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');}
|
else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value)&&old.attachPdf!==true)row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value)&&old.bodyWithoutSummary!==true)row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');}
|
||||||
candidate.attachPdf=false;
|
candidate.attachPdf=old.attachPdf===true&&(!headers.includes('附带PDF')||['是','true'].includes(get('附带PDF')));
|
||||||
candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])];
|
candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])];
|
||||||
Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length;
|
Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length;
|
||||||
if(mail)checkTemplates(mail,candidate);
|
if(mail)checkTemplates(mail,candidate);
|
||||||
row.scopeWarnings=require('./scope-catalog.cjs').warnings(store,candidate).map(message=>'第'+(index+2)+'行:'+message);row.warnings.push(...row.scopeWarnings);
|
row.scopeWarnings=require('./scope-catalog.cjs').warnings(store,candidate).map(message=>'第'+(index+2)+'行:'+message);row.warnings.push(...row.scopeWarnings);
|
||||||
row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:false};
|
row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:candidate.attachPdf};
|
||||||
const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'};
|
const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'};
|
||||||
for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label);
|
for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label);
|
||||||
if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录');
|
if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录');
|
||||||
|
|||||||
@@ -12,21 +12,24 @@ function fileLink(filePath){
|
|||||||
// Content is derived from the event and its recorded archive, never current configuration.
|
// Content is derived from the event and its recorded archive, never current configuration.
|
||||||
function mailContent(orders){
|
function mailContent(orders){
|
||||||
const summaries=orders.flatMap(order=>{
|
const summaries=orders.flatMap(order=>{
|
||||||
const event=order.event,rows=event.titleOrders;
|
const event=order.event,rows=event.titleOrders,verbatim=order.ruleSnapshot?.keepTitleVerbatim===true;
|
||||||
if(rows?.length&&rows.every(row=>typeof row.text==='string'&&row.text.trim()))return rows.map(row=>({orderNo:row.orderNo,brief:row.text}));
|
if(rows?.length&&rows.every(row=>typeof row.text==='string'&&row.text.trim())){
|
||||||
|
if(verbatim&&rows.length===1)return [{orderNo:rows[0].orderNo,brief:event.rawTitle||event.brief||rows[0].text,verbatim:true}];
|
||||||
|
return rows.map(row=>({orderNo:row.orderNo,brief:row.text,verbatim}));
|
||||||
|
}
|
||||||
// Older event snapshots may lack per-order text. Recover only the declared
|
// Older event snapshots may lack per-order text. Recover only the declared
|
||||||
// title segments, using the same deterministic title parser as ingestion.
|
// title segments, using the same deterministic title parser as ingestion.
|
||||||
const parsed=require('./title.cjs').extractTitle(event.brief||'');
|
const parsed=require('./title.cjs').extractTitle(event.brief||'');
|
||||||
if(rows?.length&&parsed.orders.length>1)return rows.map(row=>{
|
if(rows?.length&&parsed.orders.length>1)return rows.map(row=>{
|
||||||
const matches=parsed.orders.filter(observed=>observed.orderNo===row.orderNo);
|
const matches=parsed.orders.filter(observed=>observed.orderNo===row.orderNo);
|
||||||
if(!row.text?.trim()&&matches.length!==1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
if(!row.text?.trim()&&matches.length!==1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
||||||
return {orderNo:row.orderNo,brief:row.text?.trim()?row.text:matches[0].text};
|
return {orderNo:row.orderNo,brief:row.text?.trim()?row.text:matches[0].text,verbatim};
|
||||||
});
|
});
|
||||||
if(rows?.length>1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
if(rows?.length>1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
||||||
if(parsed.orders.length>1)return parsed.orders.map(row=>({orderNo:row.orderNo,brief:row.text}));
|
if(parsed.orders.length>1)return parsed.orders.map(row=>({orderNo:row.orderNo,brief:row.text,verbatim}));
|
||||||
return [{orderNo:rows?.[0]?.orderNo||event.orderNo,brief:event.brief}];
|
return [{orderNo:rows?.[0]?.orderNo||event.orderNo,brief:event.brief,verbatim}];
|
||||||
});
|
});
|
||||||
const details=summaries.map(formatOrderLine).join('\n');
|
const details=summaries.map(row=>row.verbatim?String(row.brief||'').replace(/[\r\n\u0085\u2028\u2029]+[\t ]*/g,' ').trim():formatOrderLine(row)).join('\n');
|
||||||
const seen=new Set(),directories=[];
|
const seen=new Set(),directories=[];
|
||||||
for(const order of orders)for(const file of order.archive.files){
|
for(const order of orders)for(const file of order.archive.files){
|
||||||
const windows=path.win32.isAbsolute(file.path),directory=(windows?path.win32:path.posix).dirname(file.path),key=windows?directory.toLowerCase():directory;
|
const windows=path.win32.isAbsolute(file.path),directory=(windows?path.win32:path.posix).dirname(file.path),key=windows?directory.toLowerCase():directory;
|
||||||
|
|||||||
@@ -76,11 +76,12 @@ class RuleStore{
|
|||||||
saveSettings(input,actor){return this.transaction(()=>{
|
saveSettings(input,actor){return this.transaction(()=>{
|
||||||
const old=this.settings();
|
const old=this.settings();
|
||||||
const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409);
|
const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409);
|
||||||
if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409);
|
if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes','allowedDomains'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409);
|
||||||
if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。');
|
if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。');
|
||||||
|
if(input.allowedDomains!==undefined){if(!Array.isArray(input.allowedDomains)||input.allowedDomains.length>10||input.allowedDomains.some(d=>typeof d!=='string'||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/i.test(d)))fail('收件人域名白名单无效。');input.allowedDomains=[...new Set(input.allowedDomains.map(d=>d.trim().toLowerCase()))];}
|
||||||
const run=this.get('restricted-test','main')?.value;
|
const run=this.get('restricted-test','main')?.value;
|
||||||
const restrictedIntent=testing?.enabled&&testing.readyCount>0&&testing.readyCount===testing.ruleCount&&testing.recipient==='2639266652@qq.com'&&run.rules.every(rule=>rule.to?.length===1&&rule.to[0]==='2639266652@qq.com'&&rule.cc?.length===0&&rule.attachPdf===false);
|
const restrictedIntent=testing?.enabled&&testing.readyCount>0&&testing.readyCount===testing.ruleCount&&testing.recipient==='2639266652@qq.com'&&run.rules.every(rule=>rule.to?.length===1&&rule.to[0]==='2639266652@qq.com'&&rule.cc?.length===0&&rule.attachPdf===false);
|
||||||
if(input.enabled&&(!input.channelId||!this.providersReady()&&!restrictedIntent))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
|
if(input.enabled&&old.enabled!==true&&(!input.channelId||!this.providersReady()&&!restrictedIntent))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
|
||||||
if(input.processingEnabled!==undefined&&typeof input.processingEnabled!=='boolean')fail('自动处理开关无效。');
|
if(input.processingEnabled!==undefined&&typeof input.processingEnabled!=='boolean')fail('自动处理开关无效。');
|
||||||
const processingEnabled=input.processingEnabled??old.processingEnabled;const processingSince=processingEnabled&&!old.processingEnabled?this.now():old.processingSince;
|
const processingEnabled=input.processingEnabled??old.processingEnabled;const processingSince=processingEnabled&&!old.processingEnabled?this.now():old.processingSince;
|
||||||
this.put('settings',{...input,processingEnabled,processingSince,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
|
this.put('settings',{...input,processingEnabled,processingSince,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
|
||||||
|
|||||||
@@ -18,12 +18,13 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
|
|||||||
const boundId=orders[0]?.ruleSnapshot?.bodyTemplateId;
|
const boundId=orders[0]?.ruleSnapshot?.bodyTemplateId;
|
||||||
if(boundId&&(!template||template.id!==boundId))fail('本分类绑定的邮件模板未正确解析。',409);
|
if(boundId&&(!template||template.id!==boundId))fail('本分类绑定的邮件模板未正确解析。',409);
|
||||||
if(!template)return snapshot;
|
if(!template)return snapshot;
|
||||||
const date=businessDates(template,orders),content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'';
|
const date=businessDates(template,orders),content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'',omitSummary=orders[0]?.ruleSnapshot?.bodyWithoutSummary===true;
|
||||||
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':content.details,'订单明细':content.details,'存放地址':content.directories.join('\n'),'类别名称':category};
|
const detailText=omitSummary?'':content.details,detailHtml=omitSummary?'':content.htmlDetails;
|
||||||
|
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':detailText,'订单明细':detailText,'存放地址':content.directories.join('\n'),'类别名称':category};
|
||||||
const rendered=renderTemplate({...template,attachments:[]},values);
|
const rendered=renderTemplate({...template,attachments:[]},values);
|
||||||
const subject=rendered.subject?rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、')):snapshot.subject;
|
const subject=rendered.subject?rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、')):snapshot.subject;
|
||||||
let text=rendered.text;
|
let text=rendered.text;
|
||||||
if(!['订单列表','订单明细'].some(key=>has(template.text,key)))text+='\n\n'+content.details;
|
if(!omitSummary&&!['订单列表','订单明细'].some(key=>has(template.text,key)))text+='\n\n'+content.details;
|
||||||
if(!has(template.text,'存放地址'))text+='\n\n存放地址:'+content.directories.join('\n');
|
if(!has(template.text,'存放地址'))text+='\n\n存放地址:'+content.directories.join('\n');
|
||||||
let html='<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>';
|
let html='<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>';
|
||||||
const directoryLinks=new Map(content.directories.map(directory=>[escape(directory),'<a style="color:#0000ff" href="'+escape(fileLink(directory))+'">'+escape(directory)+'</a>']));
|
const directoryLinks=new Map(content.directories.map(directory=>[escape(directory),'<a style="color:#0000ff" href="'+escape(fileLink(directory))+'">'+escape(directory)+'</a>']));
|
||||||
@@ -31,11 +32,11 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
|
|||||||
if(directoryPattern)html=html.replace(new RegExp(directoryPattern,'g'),directory=>directoryLinks.get(directory));
|
if(directoryPattern)html=html.replace(new RegExp(directoryPattern,'g'),directory=>directoryLinks.get(directory));
|
||||||
if(template.html){
|
if(template.html){
|
||||||
const token='ORDER_CONTENT_'+require('node:crypto').randomUUID(),directoryToken='ORDER_ARCHIVE_'+require('node:crypto').randomUUID();
|
const token='ORDER_CONTENT_'+require('node:crypto').randomUUID(),directoryToken='ORDER_ARCHIVE_'+require('node:crypto').randomUUID();
|
||||||
html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token,'订单明细':token,'存放地址':directoryToken}).html.replaceAll(token,content.htmlDetails).replaceAll(directoryToken,content.htmlDirectoryLinks);
|
html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token,'订单明细':token,'存放地址':directoryToken}).html.replaceAll(token,detailHtml).replaceAll(directoryToken,content.htmlDirectoryLinks);
|
||||||
if(!['订单列表','订单明细'].some(key=>has(template.html,key)))html+=content.htmlDetails;
|
if(!omitSummary&&!['订单列表','订单明细'].some(key=>has(template.html,key)))html+=content.htmlDetails;
|
||||||
if(!has(template.html,'存放地址'))html+=content.htmlDirectories;
|
if(!has(template.html,'存放地址'))html+=content.htmlDirectories;
|
||||||
}
|
}
|
||||||
const bytes=16384+Buffer.byteLength(text+html+subject)*2;
|
const bytes=16384+Buffer.byteLength(text+html+subject)*2+(snapshot.attachments||[]).reduce((sum,file)=>sum+Math.ceil(file.size/3)*4+4096,0);
|
||||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||||
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
|
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
const {normalizeScopes}=require('./scopes.cjs');
|
const {normalizeScopes}=require('./scopes.cjs');
|
||||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||||
const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow','bodyTemplateId','huizhouEnabled','huizhouTemplateId'];
|
const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','archiveOrderFolder','keepTitleVerbatim','filenameScheme','bodyWithoutSummary','sourceRow','bodyTemplateId','huizhouEnabled','huizhouTemplateId'];
|
||||||
function addresses(values){
|
function addresses(values){
|
||||||
if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
|
if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
|
||||||
return [...new Set(values.map(v=>{
|
return [...new Set(values.map(v=>{
|
||||||
@@ -34,6 +34,14 @@ function validateRule(input,old){
|
|||||||
rule[key]=[...new Set(rule[key].map(v=>v.trim()))];
|
rule[key]=[...new Set(rule[key].map(v=>v.trim()))];
|
||||||
}
|
}
|
||||||
if(!['','appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||typeof rule.attachPdf!=='boolean')fail('请选择有效的日期来源和附件要求。');
|
if(!['','appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||typeof rule.attachPdf!=='boolean')fail('请选择有效的日期来源和附件要求。');
|
||||||
|
if(input.archiveOrderFolder!==undefined&&typeof input.archiveOrderFolder!=='boolean')fail('归档按订单号建子目录开关无效。');
|
||||||
|
rule.archiveOrderFolder=rule.archiveOrderFolder===true;
|
||||||
|
if(input.keepTitleVerbatim!==undefined&&typeof input.keepTitleVerbatim!=='boolean')fail('标题原文开关无效。');
|
||||||
|
rule.keepTitleVerbatim=rule.keepTitleVerbatim===true;
|
||||||
|
if(input.filenameScheme!==undefined&&!['','orderDateSeq'].includes(input.filenameScheme))fail('归档命名方案无效。');
|
||||||
|
rule.filenameScheme=input.filenameScheme===undefined?(old.filenameScheme||''):input.filenameScheme;
|
||||||
|
if(input.bodyWithoutSummary!==undefined&&typeof input.bodyWithoutSummary!=='boolean')fail('正文摘要开关无效。');
|
||||||
|
rule.bodyWithoutSummary=rule.bodyWithoutSummary===true;
|
||||||
rule.to=addresses(rule.to);rule.cc=addresses(rule.cc).filter(v=>!rule.to.includes(v));
|
rule.to=addresses(rule.to);rule.cc=addresses(rule.cc).filter(v=>!rule.to.includes(v));
|
||||||
rule.version=old.version+1;rule.status='draft';return rule;
|
rule.version=old.version+1;rule.status='draft';return rule;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,10 +46,11 @@ class FileArea{
|
|||||||
}
|
}
|
||||||
return current;
|
return current;
|
||||||
}
|
}
|
||||||
async list(relative=''){
|
async list(relative='',options={}){
|
||||||
const directory=await this.resolve(relative),entries=[];let truncated=false;
|
const directory=await this.resolve(relative),entries=[];let truncated=false;
|
||||||
|
const prefix=typeof options?.prefix==='string'&&options.prefix?options.prefix.toLowerCase():'';
|
||||||
const iterator=await fs.opendir(directory);
|
const iterator=await fs.opendir(directory);
|
||||||
for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});}
|
for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(prefix&&!entry.name.toLowerCase().startsWith(prefix))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});}
|
||||||
entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN'));
|
entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN'));
|
||||||
return {path:segments(relative).join('/'),entries,truncated};
|
return {path:segments(relative).join('/'),entries,truncated};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,18 @@ const fs=require('node:fs/promises');
|
|||||||
const crypto=require('node:crypto');
|
const crypto=require('node:crypto');
|
||||||
const {segments,inside}=require('./files.cjs');
|
const {segments,inside}=require('./files.cjs');
|
||||||
const {renderSnapshot}=require('../pdf/exporter.cjs');
|
const {renderSnapshot}=require('../pdf/exporter.cjs');
|
||||||
const {archiveFilename}=require('./order-filename.cjs');
|
const {archiveFilename,archiveSequenceFilename}=require('./order-filename.cjs');
|
||||||
const restricted=require('../order-rules/restricted-test.cjs');
|
const restricted=require('../order-rules/restricted-test.cjs');
|
||||||
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
|
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
|
||||||
const fingerprint=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
const fingerprint=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
||||||
const fail=message=>Object.assign(new Error(message),{status:409});
|
const fail=message=>Object.assign(new Error(message),{status:409});
|
||||||
|
function orderSubfolder(rule,event){
|
||||||
|
if(rule?.archiveOrderFolder!==true)return '';
|
||||||
|
// Business convention: 国内/海外订单通知书 archive into <category>\<orderNo>\file.
|
||||||
|
const raw=event?.orderNo;
|
||||||
|
if(typeof raw!=='string'||!/^\d{6,7}$/.test(raw.trim()))throw fail('按订单号建子目录需要明确的 6 位或 7 位主订单号,本次不归档;请核实订单号后重试。');
|
||||||
|
return raw.trim();
|
||||||
|
}
|
||||||
function targetFor(storage,directory){
|
function targetFor(storage,directory){
|
||||||
if(typeof directory!=='string'||!directory.startsWith('\\\\'))throw fail('请在分类规则选择已配置服务器的共享目录。');
|
if(typeof directory!=='string'||!directory.startsWith('\\\\'))throw fail('请在分类规则选择已配置服务器的共享目录。');
|
||||||
const parts=directory.slice(2).replace(/\//g,'\\').split('\\');segments(parts.slice(2).join('/'));
|
const parts=directory.slice(2).replace(/\//g,'\\').split('\\');segments(parts.slice(2).join('/'));
|
||||||
@@ -34,21 +41,33 @@ class OrderArchiveProvider{
|
|||||||
this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};const result={...this.capabilities(),pdfExport:true};this.probes.set(key,result);return result;
|
this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};const result={...this.capabilities(),pdfExport:true};this.probes.set(key,result);return result;
|
||||||
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}finally{if(temporary)await fs.rm(temporary,{recursive:true,force:true});}
|
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}finally{if(temporary)await fs.rm(temporary,{recursive:true,force:true});}
|
||||||
}
|
}
|
||||||
async archive(input){try{return await this.performArchive(input);}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}}
|
async archive(input){try{return await this.performArchive(input);}catch(error){if(![400,409].includes(error?.status))this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}}
|
||||||
async performArchive({order,rule,snapshot,taskId}){
|
async performArchive({order,rule,snapshot,taskId}){
|
||||||
if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertOrder(this.journal,order);}
|
if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertOrder(this.journal,order);}
|
||||||
const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation;
|
const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation;
|
||||||
let previous=this.journal?.get('archive-intents',id);
|
let previous=this.journal?.get('archive-intents',id);
|
||||||
const legacy=generation===1&&!previous&&this.journal?.get('archive-intents',identity);
|
const legacy=generation===1&&!previous&&this.journal?.get('archive-intents',identity);
|
||||||
const event=order.event||order,chosen=previous?.chosen||legacy?.chosen||(rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock());
|
const event=order.event||order,chosen=previous?.chosen||legacy?.chosen||(rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock());
|
||||||
const filename=archiveFilename(event,rule.filenameDate,chosen);
|
const target=targetFor(this.storage,rule.archiveDirectory);
|
||||||
|
const subfolder=orderSubfolder(rule,event);
|
||||||
|
if(subfolder)target.relative=[target.relative,subfolder].filter(Boolean).join('/');
|
||||||
|
let filename;
|
||||||
|
if(previous?.filename)filename=previous.filename;
|
||||||
|
else if(rule.filenameScheme==='orderDateSeq'){
|
||||||
|
const seqDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(chosen)).replace(/-/g,'').slice(2);
|
||||||
|
const prefix=String(event?.orderNo||'').trim()+seqDay+'-';
|
||||||
|
let names=[];
|
||||||
|
try{const listing=await this.storage.list(target.server.id,target.relative,{prefix});names=(listing?.entries||[]).map(entry=>entry.name);}
|
||||||
|
catch(error){if(!(error?.code==='ENOENT'||error?.status===404||/找不到文件或归档目录/.test(String(error?.message||''))))throw error;}
|
||||||
|
filename=archiveSequenceFilename(event,chosen,names);
|
||||||
|
}
|
||||||
|
else filename=archiveFilename(event,rule.filenameDate,chosen);
|
||||||
const outputFingerprint=fingerprint({sourceHash:order.sourceHash,event,directory:rule.archiveDirectory,filenameDate:rule.filenameDate,filename,chosen:new Date(chosen).toISOString(),generation});
|
const outputFingerprint=fingerprint({sourceHash:order.sourceHash,event,directory:rule.archiveDirectory,filenameDate:rule.filenameDate,filename,chosen:new Date(chosen).toISOString(),generation});
|
||||||
if(legacy){
|
if(legacy){
|
||||||
if(legacy.sourceHash!==order.sourceHash||legacy.directory!==rule.archiveDirectory||legacy.filename!==filename)throw fail('旧归档意图与当前输出不一致,请建立新归档代次。');
|
if(legacy.sourceHash!==order.sourceHash||legacy.directory!==rule.archiveDirectory||legacy.filename!==filename)throw fail('旧归档意图与当前输出不一致,请建立新归档代次。');
|
||||||
previous={...legacy,id,legacyIntentId:identity,archiveGeneration:generation,outputFingerprint};this.journal.put('archive-intents',previous);
|
previous={...legacy,id,legacyIntentId:identity,archiveGeneration:generation,outputFingerprint};this.journal.put('archive-intents',previous);
|
||||||
}
|
}
|
||||||
if(previous&&(previous.sourceHash!==order.sourceHash||previous.outputFingerprint!==outputFingerprint))throw fail('归档输出与本代持久意图不一致,请建立新归档代次。');
|
if(previous&&(previous.sourceHash!==order.sourceHash||previous.outputFingerprint!==outputFingerprint))throw fail('归档输出与本代持久意图不一致,请建立新归档代次。');
|
||||||
const target=targetFor(this.storage,rule.archiveDirectory);
|
|
||||||
// Renderer public extension contract remains its original four-field filename.
|
// Renderer public extension contract remains its original four-field filename.
|
||||||
const renderInput={...snapshot,metadata:{order:String(event.orderNo),project:'流程归档',model:'订单',serial:String(event.serialNum||event.documentNum)}};
|
const renderInput={...snapshot,metadata:{order:String(event.orderNo),project:'流程归档',model:'订单',serial:String(event.serialNum||event.documentNum)}};
|
||||||
let generated;
|
let generated;
|
||||||
@@ -69,7 +88,7 @@ class OrderArchiveProvider{
|
|||||||
const evidence={archivedAt:this.clock().toISOString(),files:[{name:receipt.filename,path:path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(receipt.relativePath)),sha256:digest,size:local.length,kind:'pdf'}]};
|
const evidence={archivedAt:this.clock().toISOString(),files:[{name:receipt.filename,path:path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(receipt.relativePath)),sha256:digest,size:local.length,kind:'pdf'}]};
|
||||||
if(id&&this.journal)this.journal.put('archive-intents',{...intent,evidence});
|
if(id&&this.journal)this.journal.put('archive-intents',{...intent,evidence});
|
||||||
this.last={success:true,at:evidence.archivedAt,message:'PDF 已生成、归档并读回校验。'};return evidence;
|
this.last={success:true,at:evidence.archivedAt,message:'PDF 已生成、归档并读回校验。'};return evidence;
|
||||||
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}
|
}catch(error){if(![400,409].includes(error?.status))this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}
|
||||||
}
|
}
|
||||||
async read(file){
|
async read(file){
|
||||||
if(this.journal)restricted.assertPath(this.journal,file.path);
|
if(this.journal)restricted.assertPath(this.journal,file.path);
|
||||||
@@ -77,4 +96,4 @@ class OrderArchiveProvider{
|
|||||||
const result=await this.storage.readFile(target.server.id,[target.relative,path.win32.basename(file.path)].filter(Boolean).join('/'));return Buffer.from(result.bytes);
|
const result=await this.storage.readFile(target.server.id,[target.relative,path.win32.basename(file.path)].filter(Boolean).join('/'));return Buffer.from(result.bytes);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
module.exports={OrderArchiveProvider,targetFor};
|
module.exports={OrderArchiveProvider,targetFor,orderSubfolder};
|
||||||
@@ -7,4 +7,14 @@ function archiveFilename(event,filenameDate,at){
|
|||||||
const safe=v=>String(v||'').replace(/[<>:"/\\|?*\x00-\x1f]/g,'_').replace(/[. ]+$/g,'').slice(0,65);
|
const safe=v=>String(v||'').replace(/[<>:"/\\|?*\x00-\x1f]/g,'_').replace(/[. ]+$/g,'').slice(0,65);
|
||||||
const filename=[event.orderNo,day,event.serialNum||event.documentNum].map(safe).join('_')+'.pdf';segments(filename);return filename;
|
const filename=[event.orderNo,day,event.serialNum||event.documentNum].map(safe).join('_')+'.pdf';segments(filename);return filename;
|
||||||
}
|
}
|
||||||
module.exports={archiveFilename};
|
function archiveSequenceFilename(event,at,names){
|
||||||
|
const orderNo=String(event?.orderNo||'').trim();
|
||||||
|
if(!orderNo)throw Object.assign(Error('归档文件缺少订单号。'),{status:409});
|
||||||
|
if(!Number.isFinite(+new Date(at)))throw Object.assign(Error('归档日期无效。'),{status:409});
|
||||||
|
const day=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(at)).replace(/-/g,'').slice(2);
|
||||||
|
const prefix=orderNo+day,escaped=prefix.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),pattern=new RegExp('^'+escaped+'-(\\d+)\\.pdf$','i');
|
||||||
|
let max=0;
|
||||||
|
for(const name of names||[]){const match=pattern.exec(String(name||''));if(match)max=Math.max(max,Number(match[1]));}
|
||||||
|
return prefix+'-'+(max+1)+'.pdf';
|
||||||
|
}
|
||||||
|
module.exports={archiveFilename,archiveSequenceFilename};
|
||||||
@@ -54,20 +54,20 @@ class StorageService{
|
|||||||
run(id,work){
|
run(id,work){
|
||||||
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
|
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
|
||||||
const previous=this.running.get(id)||Promise.resolve(),controller=new AbortController();
|
const previous=this.running.get(id)||Promise.resolve(),controller=new AbortController();
|
||||||
this.operationControllers.add(controller);let started=false,rejectQueued;
|
this.operationControllers.add(controller);let started=false,rejectQueued,timer;
|
||||||
const queued=new Promise((resolve,reject)=>{rejectQueued=reject;});
|
const queued=new Promise((resolve,reject)=>{rejectQueued=reject;});
|
||||||
const cancel=()=>{if(!started)rejectQueued(controller.signal.reason);};
|
const cancel=()=>{if(!started)rejectQueued(controller.signal.reason);};
|
||||||
controller.signal.addEventListener('abort',cancel);
|
controller.signal.addEventListener('abort',cancel);
|
||||||
const timer=setTimeout(()=>controller.abort(fail('存储操作超时,请检查服务器与网络。',504)),this.operationTimeoutMs);
|
|
||||||
const task=previous.catch(()=>{}).then(async()=>{
|
const task=previous.catch(()=>{}).then(async()=>{
|
||||||
started=true;if(controller.signal.aborted)throw controller.signal.reason;
|
started=true;if(controller.signal.aborted)throw controller.signal.reason;
|
||||||
|
timer=setTimeout(()=>controller.abort(fail('存储操作超时,请检查服务器与网络。',504)),this.operationTimeoutMs);
|
||||||
const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);
|
const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);
|
||||||
try{return await work(server,controller.signal);}catch(e){throw safe(e);}
|
try{return await work(server,controller.signal);}catch(e){throw safe(e);}
|
||||||
}).finally(()=>{clearTimeout(timer);controller.signal.removeEventListener('abort',cancel);this.operationControllers.delete(controller);if(this.running.get(id)===task)this.running.delete(id);});
|
}).finally(()=>{clearTimeout(timer);controller.signal.removeEventListener('abort',cancel);this.operationControllers.delete(controller);if(this.running.get(id)===task)this.running.delete(id);});
|
||||||
this.running.set(id,task);return Promise.race([task,queued]);
|
this.running.set(id,task);return Promise.race([task,queued]);
|
||||||
}
|
}
|
||||||
check(id){return this.run(id,async (server,signal)=>{try{const result=await this.operation(server,'check',[],signal);const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
|
check(id){return this.run(id,async (server,signal)=>{try{const result=await this.operation(server,'check',[],signal);const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
|
||||||
list(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'list',[relative],signal));}
|
list(id,relative,options){return this.run(id,async (server,signal)=>this.operation(server,'list',options&&Object.keys(options).length?[relative,options]:[relative],signal));}
|
||||||
mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));}
|
mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));}
|
||||||
readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));}
|
readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));}
|
||||||
previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));}
|
previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ $current=[System.IO.Directory]::GetAccessControl($p)
|
|||||||
if(-not (Test-PrivateDirectoryAcl $current $s)){
|
if(-not (Test-PrivateDirectoryAcl $current $s)){
|
||||||
$a=New-Object System.Security.AccessControl.DirectorySecurity
|
$a=New-Object System.Security.AccessControl.DirectorySecurity
|
||||||
$a.SetAccessRuleProtection($true,$false)
|
$a.SetAccessRuleProtection($true,$false)
|
||||||
$a.SetOwner($s)
|
if(-not $current.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($s)){$a.SetOwner($s)}
|
||||||
$r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow")
|
$r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow")
|
||||||
$a.AddAccessRule($r)
|
$a.AddAccessRule($r)
|
||||||
[System.IO.Directory]::SetAccessControl($p,$a)
|
[System.IO.Directory]::SetAccessControl($p,$a)
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ class ServiceSupervisor {
|
|||||||
if(!Array.isArray(ports)||!ports.length||ports.some(port=>!Number.isInteger(port)||port<1024||port>65535)||new Set(ports).size!==ports.length)throw Object.assign(Error('服务端口配置无效。'),{code:'EINVALIDPORTS'});
|
if(!Array.isArray(ports)||!ports.length||ports.some(port=>!Number.isInteger(port)||port<1024||port>65535)||new Set(ports).size!==ports.length)throw Object.assign(Error('服务端口配置无效。'),{code:'EINVALIDPORTS'});
|
||||||
await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
|
await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog();
|
||||||
const fd=fs.openSync(logFile,'a',0o600);let child;
|
const fd=fs.openSync(logFile,'a',0o600);let child;
|
||||||
try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
|
try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{NODE_USE_SYSTEM_CA:'1',...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);}
|
||||||
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.ready=false;this.startupError=null;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
|
this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.ready=false;this.startupError=null;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;});
|
||||||
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null,startupError:null,consecutiveStartupFailures:this.startupFailures});
|
this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null,startupError:null,consecutiveStartupFailures:this.startupFailures});
|
||||||
child.on('message',message=>{
|
child.on('message',message=>{
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
'use strict';
|
||||||
|
let loaded = false;
|
||||||
|
function ensureSystemCA() {
|
||||||
|
if (loaded) return;
|
||||||
|
loaded = true;
|
||||||
|
try {
|
||||||
|
const tls = require('node:tls');
|
||||||
|
if (typeof tls.getCACertificates === 'function' && typeof tls.setDefaultCACertificates === 'function') {
|
||||||
|
const extra = tls.getCACertificates('system');
|
||||||
|
if (Array.isArray(extra) && extra.length) {
|
||||||
|
const merged = [...new Set([...tls.getCACertificates('default'), ...extra])];
|
||||||
|
tls.setDefaultCACertificates(merged);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('系统 CA 加载失败:' + error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ensureSystemCA();
|
||||||
|
module.exports = { ensureSystemCA };
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
require('./platform/tls-system-ca.cjs');
|
||||||
const {createServer,startService}=require('./app/bridge.cjs');
|
const {createServer,startService}=require('./app/bridge.cjs');
|
||||||
const {main}=require('./app/application.cjs');
|
const {main}=require('./app/application.cjs');
|
||||||
const {safeDiagnostic}=require('./shared/diagnostics.cjs');
|
const {safeDiagnostic}=require('./shared/diagnostics.cjs');
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
'use strict';
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { buildBatch } = require('../../src/modules/order-rules/batch.cjs');
|
||||||
|
const { applyBodyTemplate } = require('../../src/modules/order-rules/template.cjs');
|
||||||
|
const { OrderArchiveProvider } = require('../../src/modules/storage/order-archive.cjs');
|
||||||
|
const { OrderRuleDispatcher } = require('../../src/modules/order-rules/dispatcher.cjs');
|
||||||
|
const { RuleStore } = require('../../src/modules/order-rules/store.cjs');
|
||||||
|
const { OrderExecutionCoordinator } = require('../../src/modules/order-execution/coordinator.cjs');
|
||||||
|
const { StorageService } = require('../../src/modules/storage/service.cjs');
|
||||||
|
const { FileArea } = require('../../src/modules/storage/files.cjs');
|
||||||
|
const { ensureSystemCA } = require('../../src/platform/tls-system-ca.cjs');
|
||||||
|
|
||||||
|
const cutoff = '2026-12-01T03:50:00.000Z';
|
||||||
|
|
||||||
|
test('applyBodyTemplate honors bodyWithoutSummary and enforces MIME attachment byte limit', () => {
|
||||||
|
const rule = {
|
||||||
|
id: 'overseas-change',
|
||||||
|
categoryId: 'overseas-change',
|
||||||
|
version: 1,
|
||||||
|
name: '海外订单更改通知书',
|
||||||
|
intro: '请查收',
|
||||||
|
signature: '签名',
|
||||||
|
attachPdf: true,
|
||||||
|
bodyWithoutSummary: true,
|
||||||
|
to: ['2639266652@qq.com'],
|
||||||
|
cc: [],
|
||||||
|
bodyTemplateId: 'tpl-change',
|
||||||
|
};
|
||||||
|
const smallOrder = {
|
||||||
|
id: 'o1',
|
||||||
|
status: 'pending',
|
||||||
|
ruleSnapshot: structuredClone(rule),
|
||||||
|
event: {
|
||||||
|
orderNo: '315470',
|
||||||
|
receivedAt: '2026-12-01T02:00:00Z',
|
||||||
|
productLine: '海外',
|
||||||
|
brief: '订单号:315470 客户简称:测试客户',
|
||||||
|
titleOrders: [{ orderNo: '315470', text: '订单号:315470 客户简称:测试客户' }],
|
||||||
|
},
|
||||||
|
archive: {
|
||||||
|
archivedAt: '2026-12-01T02:10:00Z',
|
||||||
|
files: [{ name: '315470261201-1.pdf', path: 'C:\\archive\\315470261201-1.pdf', size: 1024, sha256: 'a'.repeat(64), kind: 'pdf' }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const tpl = {
|
||||||
|
id: 'tpl-change',
|
||||||
|
version: 1,
|
||||||
|
status: 'active',
|
||||||
|
bindingVersion: 1,
|
||||||
|
subject: '更改通知',
|
||||||
|
text: '各位好,请查收附件。',
|
||||||
|
html: '<p>各位好,请查收附件。</p>',
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
const snap = buildBatch(rule, [smallOrder], cutoff);
|
||||||
|
const rendered = applyBodyTemplate(snap, tpl, [smallOrder], 20971520);
|
||||||
|
assert.equal(rendered.text.includes('测试客户'), false);
|
||||||
|
assert.equal(rendered.html.includes('测试客户'), false);
|
||||||
|
assert.match(rendered.text, /存放地址:C:\\archive/);
|
||||||
|
|
||||||
|
const hugeOrder = structuredClone(smallOrder);
|
||||||
|
hugeOrder.archive.files[0].size = 18 * 1024 * 1024;
|
||||||
|
const hugeSnap = buildBatch(rule, [hugeOrder], cutoff, { maxMessageBytes: 30 * 1024 * 1024 });
|
||||||
|
assert.throws(() => applyBodyTemplate(hugeSnap, tpl, [hugeOrder], 20971520), /容量限制/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OrderArchiveProvider isolates per-order 409 validation errors from global capabilities', async () => {
|
||||||
|
const provider = new OrderArchiveProvider({
|
||||||
|
storage: {
|
||||||
|
store: {
|
||||||
|
servers: () => [{ id: 's1', enabled: true, host: '192.168.8.210', share: 'SVR', directory: '', state: { readable: true, writable: true } }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
outputDir: os.tmpdir(),
|
||||||
|
});
|
||||||
|
provider.last = { success: true, at: cutoff, message: 'ok' };
|
||||||
|
await assert.rejects(
|
||||||
|
provider.archive({
|
||||||
|
order: { id: 'rework-1', sourceHash: 'h1', event: { orderNo: 'HWFG-2026110015' } },
|
||||||
|
rule: { archiveDirectory: '\\\\192.168.8.210\\SVR\\海外订单通知书', archiveOrderFolder: true },
|
||||||
|
snapshot: {},
|
||||||
|
}),
|
||||||
|
(err) => err.status === 409,
|
||||||
|
);
|
||||||
|
assert.equal(provider.capabilities().automaticArchive, true);
|
||||||
|
assert.equal(provider.capabilities().pdfExport, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OrderArchiveProvider orderDateSeq uses chosen filenameDate and prefix filtering beyond 500 files', async (t) => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'seq-list-'));
|
||||||
|
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||||
|
for (let i = 0; i < 520; i++) {
|
||||||
|
fs.writeFileSync(path.join(dir, `000001261201-${i + 1}.pdf`), '%PDF-1.4\n');
|
||||||
|
}
|
||||||
|
fs.writeFileSync(path.join(dir, '999999261130-1.pdf'), '%PDF-1.4\n');
|
||||||
|
fs.writeFileSync(path.join(dir, '999999261130-2.pdf'), '%PDF-1.4\n');
|
||||||
|
const area = new FileArea(dir);
|
||||||
|
const filtered = await area.list('', { prefix: '999999261130-' });
|
||||||
|
assert.equal(filtered.entries.length, 2);
|
||||||
|
assert.equal(filtered.truncated, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('post-cutoff completed scan proof survives subsequent transient 502 scan failure', async (t) => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scan-proof-'));
|
||||||
|
const store = new RuleStore(dir, {
|
||||||
|
clock: () => new Date(cutoff),
|
||||||
|
schedule: () => ({ times: ['11:50', '18:30'], weekends: false }),
|
||||||
|
});
|
||||||
|
t.after(() => {
|
||||||
|
store.close();
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
const connection = { id: 'c1', owner: 'admin', status: 'connected' };
|
||||||
|
const workspace = { snapshot: () => ({ connections: [connection] }), getConnection: () => connection };
|
||||||
|
let shouldFail = false;
|
||||||
|
const provider = {
|
||||||
|
scan: async () => {
|
||||||
|
if (shouldFail) throw Object.assign(new Error('502 Bad Gateway'), { status: 502 });
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
capabilities: async () => ({ liveTodo: true, pdfExport: true }),
|
||||||
|
};
|
||||||
|
const archive = { supportsRecovery: true, capabilities: async () => ({ automaticArchive: true, pdfExport: true }) };
|
||||||
|
let now = new Date('2026-12-01T03:50:02.000Z');
|
||||||
|
const coordinator = new OrderExecutionCoordinator({ store, workspace, provider, archive, clock: () => now });
|
||||||
|
const principal = { sessionId: 's1', user: { username: 'admin', role: 'admin' } };
|
||||||
|
|
||||||
|
await coordinator.scan({ connectionId: 'c1', idempotencyKey: 'ok-after-cutoff' }, principal);
|
||||||
|
assert.deepEqual(store.discoveryBlockers(cutoff), []);
|
||||||
|
|
||||||
|
now = new Date('2026-12-01T03:53:22.000Z');
|
||||||
|
shouldFail = true;
|
||||||
|
await assert.rejects(coordinator.scan({ connectionId: 'c1', idempotencyKey: 'later-502' }, principal), /502/);
|
||||||
|
assert.equal(store.get('execution-scans', 'c1').status, 'failed');
|
||||||
|
assert.deepEqual(store.discoveryBlockers(cutoff), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dispatcher preserves TLS certificate error details without wasting transient retries, and retries ECONNECTION', async () => {
|
||||||
|
const records = new Map();
|
||||||
|
const baseBatch = {
|
||||||
|
id: 'b-tls',
|
||||||
|
version: 1,
|
||||||
|
status: 'prepared',
|
||||||
|
cutoff,
|
||||||
|
channelId: 'mail',
|
||||||
|
to: ['2639266652@qq.com'],
|
||||||
|
cc: [],
|
||||||
|
attachments: [],
|
||||||
|
orderIds: ['o1'],
|
||||||
|
ruleSnapshot: {},
|
||||||
|
};
|
||||||
|
records.set('b-tls', structuredClone(baseBatch));
|
||||||
|
const finished = [];
|
||||||
|
let verifyError = Object.assign(new Error('unable to verify the first certificate'), { code: 'ESOCKET' });
|
||||||
|
let verifyCalls = 0;
|
||||||
|
const store = {
|
||||||
|
get: () => null,
|
||||||
|
put: (kind, val) => {
|
||||||
|
if (kind === 'batches') records.set(val.id, structuredClone(val));
|
||||||
|
},
|
||||||
|
all: (kind) => (kind === 'batches' ? [...records.values()] : []),
|
||||||
|
settings: () => ({ enabled: true, channelId: 'mail' }),
|
||||||
|
capabilities: { liveTodo: true, pdfExport: true, automaticArchive: true },
|
||||||
|
discoveryBlockers: () => [],
|
||||||
|
batchIncomplete: () => false,
|
||||||
|
beginSending: () => {},
|
||||||
|
finishSending: (...args) => finished.push(args),
|
||||||
|
};
|
||||||
|
const mail = {
|
||||||
|
store: { channelSecret: () => ({ id: 'mail', version: 1, email: 'sender@skyworth.com', smtp: {} }), guard: () => {} },
|
||||||
|
smtpFactory: () => ({
|
||||||
|
verify: async () => {
|
||||||
|
verifyCalls++;
|
||||||
|
throw verifyError;
|
||||||
|
},
|
||||||
|
sendMail: async () => ({ accepted: ['2639266652@qq.com'], rejected: [] }),
|
||||||
|
close: () => {},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
const dispatcher = new OrderRuleDispatcher({ store, mail, settings: () => ({}), clock: () => new Date(cutoff), providersReady: () => true });
|
||||||
|
await dispatcher.dispatch(records.get('b-tls'), store.settings());
|
||||||
|
assert.equal(verifyCalls, 1);
|
||||||
|
assert.equal(finished.length, 1);
|
||||||
|
assert.equal(finished[0][1], 'failed');
|
||||||
|
assert.match(finished[0][2], /TLS 证书校验失败.*unable to verify the first certificate/);
|
||||||
|
|
||||||
|
// Transient ECONNECTION schedules retry instead of immediate failure
|
||||||
|
finished.length = 0;
|
||||||
|
verifyCalls = 0;
|
||||||
|
verifyError = Object.assign(new Error('connect ETIMEDOUT'), { code: 'ECONNECTION' });
|
||||||
|
records.set('b-net', { ...structuredClone(baseBatch), id: 'b-net' });
|
||||||
|
await dispatcher.dispatch(records.get('b-net'), store.settings());
|
||||||
|
assert.equal(verifyCalls, 1);
|
||||||
|
assert.equal(finished.length, 0);
|
||||||
|
assert.equal(records.get('b-net').retryCount, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('StorageService starts operationTimeoutMs when queued operation begins executing rather than while waiting in queue', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const service = new StorageService({
|
||||||
|
store: { secret: () => ({ enabled: true }) },
|
||||||
|
client: {
|
||||||
|
area: async () => ({
|
||||||
|
list: async () => {
|
||||||
|
calls++;
|
||||||
|
await new Promise((r) => setTimeout(r, 80));
|
||||||
|
return { path: '', entries: [], truncated: false };
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
checkTimeoutMs: 120,
|
||||||
|
});
|
||||||
|
const [r1, r2] = await Promise.all([service.list('s1', ''), service.list('s1', '')]);
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.deepEqual(r1.entries, []);
|
||||||
|
assert.deepEqual(r2.entries, []);
|
||||||
|
await service.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ensureSystemCA runs idempotently without throwing', () => {
|
||||||
|
ensureSystemCA();
|
||||||
|
ensureSystemCA();
|
||||||
|
});
|
||||||
@@ -20,8 +20,14 @@ test('legacy per-order text recovery keeps declared title order instead of prima
|
|||||||
const snapshot=buildBatch(rule,[input],cutoff);
|
const snapshot=buildBatch(rule,[input],cutoff);
|
||||||
assert.deepEqual(snapshot.orderNos,['O-2','O-1']);assert.equal(snapshot.text.split('\n\n')[1],'订单号:O-2客户简称:乙\n订单号:O-1客户简称:甲总数量:0');
|
assert.deepEqual(snapshot.orderNos,['O-2','O-1']);assert.equal(snapshot.text.split('\n\n')[1],'订单号:O-2客户简称:乙\n订单号:O-1客户简称:甲总数量:0');
|
||||||
});
|
});
|
||||||
test('new native freeze rejects legacy attach-PDF intent and still requires archived PDF evidence',()=>{
|
test('new native freeze includes archived PDF only when rule attachPdf is enabled and always requires archived PDF evidence',()=>{
|
||||||
assert.throws(()=>buildBatch({...rule,attachPdf:true},[order()],cutoff),/附件|attachPdf/);
|
const attached=buildBatch({...rule,attachPdf:true},[order()],cutoff);
|
||||||
|
assert.equal(attached.attachPdf,true);
|
||||||
|
assert.equal(attached.attachments.length,1);
|
||||||
|
assert.equal(attached.attachments[0].name,'O-1.pdf');
|
||||||
|
const detached=buildBatch({...rule,attachPdf:false},[order()],cutoff);
|
||||||
|
assert.equal(detached.attachPdf,false);
|
||||||
|
assert.deepEqual(detached.attachments,[]);
|
||||||
const input=order();input.archive.files=input.archive.files.filter(f=>f.kind!=='pdf');
|
const input=order();input.archive.files=input.archive.files.filter(f=>f.kind!=='pdf');
|
||||||
assert.throws(()=>buildBatch(rule,[input],cutoff),/PDF/);
|
assert.throws(()=>buildBatch(rule,[input],cutoff),/PDF/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,8 +14,9 @@
|
|||||||
const text=(name,label,value,extra='')=>'<div class="col-md-6"><label class="form-label" for="rule-'+name+'">'+label+'</label><input class="form-control" id="rule-'+name+'" name="'+name+'" value="'+esc(value)+'" '+extra+' '+disabled+'></div>';
|
const text=(name,label,value,extra='')=>'<div class="col-md-6"><label class="form-label" for="rule-'+name+'">'+label+'</label><input class="form-control" id="rule-'+name+'" name="'+name+'" value="'+esc(value)+'" '+extra+' '+disabled+'></div>';
|
||||||
const area=(name,label,value,rows)=>'<div class="col-12"><label class="form-label" for="rule-'+name+'">'+label+'</label><textarea class="form-control" id="rule-'+name+'" name="'+name+'" rows="'+rows+'" maxlength="20000" '+disabled+'>'+esc(value)+'</textarea></div>';
|
const area=(name,label,value,rows)=>'<div class="col-12"><label class="form-label" for="rule-'+name+'">'+label+'</label><textarea class="form-control" id="rule-'+name+'" name="'+name+'" rows="'+rows+'" maxlength="20000" '+disabled+'>'+esc(value)+'</textarea></div>';
|
||||||
const card=(number,title,description,body)=>'<section class="card rule-config-section"><div class="card-header"><span class="rule-section-number">'+number+'</span><div><h3 class="card-title">'+title+'</h3><div class="text-secondary small mt-1">'+description+'</div></div></div><div class="card-body">'+body+'</div></section>';
|
const card=(number,title,description,body)=>'<section class="card rule-config-section"><div class="card-header"><span class="rule-section-number">'+number+'</span><div><h3 class="card-title">'+title+'</h3><div class="text-secondary small mt-1">'+description+'</div></div></div><div class="card-body">'+body+'</div></section>';
|
||||||
const notify=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'template'})+'<div class="row g-3 mt-1">'+text('subjectPrefix','邮件主题前缀',rule.subjectPrefix,'maxlength="200"')+area('to','收件人',(rule.to||[]).join('\n'),3)+area('cc','抄送人',(rule.cc||[]).join('\n'),2)+'<div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="attachPdf" '+'disabled><span class="form-check-label">PDF 仅归档,邮件不附附件</span></label></div><div class="col-12"><details id="rule-default-body"><summary>标准汇总正文设置(使用邮件模板时无需填写)</summary><div class="row g-3 mt-1">'+area('intro','正文引导语',rule.intro,3)+'</div></details></div></div>';
|
const notify=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'template'})+'<div class="row g-3 mt-1">'+text('subjectPrefix','邮件主题前缀',rule.subjectPrefix,'maxlength="200"')+area('to','收件人',(rule.to||[]).join('\n'),3)+area('cc','抄送人',(rule.cc||[]).join('\n'),2)+'<div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="attachPdf" '+(rule.attachPdf===true?'checked ':'')+disabled+'><span class="form-check-label">邮件附归档 PDF(仅更改/返工类)</span></label></div><div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="bodyWithoutSummary" '+(rule.bodyWithoutSummary===true?'checked ':'')+disabled+'><span class="form-check-label">正文不含订单摘要(仅保留引导语、目录和签名)</span></label></div><div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" id="rule-keepTitleVerbatim" name="keepTitleVerbatim" '+(rule.keepTitleVerbatim===true?'checked ':'')+disabled+'><span class="form-check-label">邮件明细使用 BPM 标题原文(不从“订单号”处截断)</span></label></div><div class="col-12"><details id="rule-default-body"><summary>标准汇总正文设置(使用邮件模板时无需填写)</summary><div class="row g-3 mt-1">'+area('intro','正文引导语',rule.intro,3)+'</div></details></div></div>';
|
||||||
const archive=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'archive'})+'<div class="row g-3 mt-3"><div class="col-md-6"><label class="form-label" for="rule-filenameDate">文件名日期依据</label><select class="form-select" id="rule-filenameDate" name="filenameDate" '+disabled+'><option value="">待确认</option>'+Object.entries(dates).map(([v,label])=>'<option value="'+v+'" '+(rule.filenameDate===v?'selected':'')+'>'+label+'</option>').join('')+'</select><div class="form-hint">订单号_日期_流水编号.pdf</div></div></div>';
|
const schemes={'':'标准命名(订单号_日期_流水编号.pdf)',orderDateSeq:'序号命名(订单号YYMMDD-序号.pdf)'};
|
||||||
|
const archive=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'archive'})+'<div class="row g-3 mt-3"><div class="col-md-6"><label class="form-label" for="rule-filenameDate">文件名日期依据</label><select class="form-select" id="rule-filenameDate" name="filenameDate" '+disabled+'><option value="">待确认</option>'+Object.entries(dates).map(([v,label])=>'<option value="'+v+'" '+(rule.filenameDate===v?'selected':'')+'>'+label+'</option>').join('')+'</select><div class="form-hint">用于归档文件名中的日期部分</div></div><div class="col-md-6"><label class="form-label" for="rule-filenameScheme">归档命名方案</label><select class="form-select" id="rule-filenameScheme" name="filenameScheme" '+disabled+'>'+Object.entries(schemes).map(([v,label])=>'<option value="'+v+'" '+((rule.filenameScheme||'')===v?'selected':'')+'>'+label+'</option>').join('')+'</select><div class="form-hint">更改/返工类可选序号命名</div></div><div class="col-md-6"><label class="form-check"><input class="form-check-input" type="checkbox" id="rule-archiveOrderFolder" name="archiveOrderFolder" '+(rule.archiveOrderFolder===true?'checked ':'')+disabled+'><span class="form-check-label">按订单号建子目录</span></label><div class="form-hint">归入 {类别}\\{订单号}\\文件.pdf;订单号须为明确 6 或 7 位,否则阻断归档</div></div></div>';
|
||||||
return '<form id="order-rule-editor" data-lifecycle="custom">'+
|
return '<form id="order-rule-editor" data-lifecycle="custom">'+
|
||||||
card('01','适用通知','流程与触发节点完整配对,任一行满足即归入本类别。','<div class="row g-3 mb-3">'+text('name','规则名称',rule.name,'required maxlength="160"')+text('productLine','产品线 / 产业',rule.productLine||'','maxlength="200"')+'</div>'+window.OrderRuleScopes.render(rule,{esc,admin})+'<div id="rule-field-coverage" class="small text-secondary mt-3" role="status"></div>')+
|
card('01','适用通知','流程与触发节点完整配对,任一行满足即归入本类别。','<div class="row g-3 mb-3">'+text('name','规则名称',rule.name,'required maxlength="160"')+text('productLine','产品线 / 产业',rule.productLine||'','maxlength="200"')+'</div>'+window.OrderRuleScopes.render(rule,{esc,admin})+'<div id="rule-field-coverage" class="small text-secondary mt-3" role="status"></div>')+
|
||||||
card('02','通知内容','同类别每个发送时段汇总一封,收件人与附件按本类别维护。',notify)+
|
card('02','通知内容','同类别每个发送时段汇总一封,收件人与附件按本类别维护。',notify)+
|
||||||
@@ -23,6 +24,6 @@
|
|||||||
card('04','验证与发布','用一份真实通知检查分类、邮件与归档计划。',recognition+'<details class="mt-3"><summary id="order-rule-explanation-title">查看已保存规则的处理说明</summary><p class="small text-secondary mt-2" id="order-rule-explanation">'+esc(describe(rule))+'</p></details>'+'<div id="rule-validation-issues">'+(rule.validationIssues?.length?'<div class="mt-3"><strong class="small">启用前待完善</strong><ul class="small text-secondary mt-2 mb-0">'+rule.validationIssues.map(v=>'<li>'+esc(typeof v==='string'?v:v.message||'配置需要检查')+'</li>').join('')+'</ul></div>':'')+'</div><div id="order-rule-dirty" class="small text-warning mt-3" role="status"></div><p class="small text-secondary mt-3 mb-0">检查不会归档、发信或办理 BPM。发送时段在<a href="#schedule">通知配置</a>维护。</p>')+
|
card('04','验证与发布','用一份真实通知检查分类、邮件与归档计划。',recognition+'<details class="mt-3"><summary id="order-rule-explanation-title">查看已保存规则的处理说明</summary><p class="small text-secondary mt-2" id="order-rule-explanation">'+esc(describe(rule))+'</p></details>'+'<div id="rule-validation-issues">'+(rule.validationIssues?.length?'<div class="mt-3"><strong class="small">启用前待完善</strong><ul class="small text-secondary mt-2 mb-0">'+rule.validationIssues.map(v=>'<li>'+esc(typeof v==='string'?v:v.message||'配置需要检查')+'</li>').join('')+'</ul></div>':'')+'</div><div id="order-rule-dirty" class="small text-warning mt-3" role="status"></div><p class="small text-secondary mt-3 mb-0">检查不会归档、发信或办理 BPM。发送时段在<a href="#schedule">通知配置</a>维护。</p>')+
|
||||||
(admin?'<div class="rule-save-bar"><span class="small text-secondary">保存草稿后检查,再发布;左侧开关控制已发布版本。</span><button class="btn btn-primary" type="submit">保存草稿</button><button class="btn" type="button" id="order-rule-publish">发布此版本</button></div>':'')+'</form>';
|
(admin?'<div class="rule-save-bar"><span class="small text-secondary">保存草稿后检查,再发布;左侧开关控制已发布版本。</span><button class="btn btn-primary" type="submit">保存草稿</button><button class="btn" type="button" id="order-rule-publish">发布此版本</button></div>':'')+'</form>';
|
||||||
}
|
}
|
||||||
function read(form,rule,adapters=[]){const result={...rule};for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate'])result[name]=form.elements.namedItem(name).value.trim();result.scopes=window.OrderRuleScopes.read(form);result.processNames=[...new Set(result.scopes.map(r=>r.processName).filter(Boolean))];result.nodeNames=[...new Set(result.scopes.map(r=>r.nodeName).filter(Boolean))];result.adapterIds=adaptersFor(result,adapters);const productLine=form.elements.namedItem('productLine')?.value.trim();if(productLine||Object.hasOwn(rule,'productLine'))result.productLine=productLine;const template=form.elements.namedItem('bodyTemplateId').value;if(template==='__legacy__')delete result.bodyTemplateId;else result.bodyTemplateId=template;result.huizhouEnabled=form.elements.namedItem('huizhouEnabled').checked;result.huizhouTemplateId=form.elements.namedItem('huizhouTemplateId').value;for(const name of ['to','cc'])result[name]=list(form.elements.namedItem(name).value);result.attachPdf=false;return result;}
|
function read(form,rule,adapters=[]){const result={...rule};for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','filenameScheme']){const el=form.elements.namedItem(name);if(el)result[name]=el.value.trim();}result.scopes=window.OrderRuleScopes.read(form);result.processNames=[...new Set(result.scopes.map(r=>r.processName).filter(Boolean))];result.nodeNames=[...new Set(result.scopes.map(r=>r.nodeName).filter(Boolean))];result.adapterIds=adaptersFor(result,adapters);const productLine=form.elements.namedItem('productLine')?.value.trim();if(productLine||Object.hasOwn(rule,'productLine'))result.productLine=productLine;const template=form.elements.namedItem('bodyTemplateId').value;if(template==='__legacy__')delete result.bodyTemplateId;else result.bodyTemplateId=template;result.huizhouEnabled=form.elements.namedItem('huizhouEnabled').checked;result.huizhouTemplateId=form.elements.namedItem('huizhouTemplateId').value;for(const name of ['to','cc'])result[name]=list(form.elements.namedItem(name).value);result.attachPdf=form.elements.namedItem('attachPdf').checked;result.bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary').checked;result.keepTitleVerbatim=form.elements.namedItem('keepTitleVerbatim').checked;result.archiveOrderFolder=form.elements.namedItem('archiveOrderFolder').checked;return result;}
|
||||||
window.OrderRuleEditor={render,read,describe,adaptersFor};
|
window.OrderRuleEditor={render,read,describe,adaptersFor};
|
||||||
})();
|
})();
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
if(!result||!result.id||!Number.isSafeInteger(result.version))throw Error('写入已返回,但规则状态回执不完整;请刷新核对,勿重复提交。');
|
if(!result||!result.id||!Number.isSafeInteger(result.version))throw Error('写入已返回,但规则状态回执不完整;请刷新核对,勿重复提交。');
|
||||||
const {restrictedTest,...value}=result,target=data.rules.find(item=>item.id===value.id);if(!target)throw Error('规则目录已变化,请刷新核对。');Object.assign(target,value);if(Object.hasOwn(result,'restrictedTest')){data.restrictedTest=restrictedTest;if(!restrictedTest)for(const item of data.rules){delete item.testStatus;delete item.testVersion;delete item.testHasDraft;}else if(!restrictedTest.enabled)for(const item of data.rules){item.testStatus='paused';item.testVersion=null;item.testHasDraft=true;}}
|
const {restrictedTest,...value}=result,target=data.rules.find(item=>item.id===value.id);if(!target)throw Error('规则目录已变化,请刷新核对。');Object.assign(target,value);if(Object.hasOwn(result,'restrictedTest')){data.restrictedTest=restrictedTest;if(!restrictedTest)for(const item of data.rules){delete item.testStatus;delete item.testVersion;delete item.testHasDraft;}else if(!restrictedTest.enabled)for(const item of data.rules){item.testStatus='paused';item.testVersion=null;item.testHasDraft=true;}}
|
||||||
if(target===rule){
|
if(target===rule){
|
||||||
if(normalize){for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','productLine']){const input=form.elements.namedItem(name);if(input&&rule[name]!==undefined)input.value=rule[name];}for(const name of ['to','cc'])form.elements.namedItem(name).value=(rule[name]||[]).join('\n');if(JSON.stringify(window.OrderRuleScopes.read(form))!==JSON.stringify(window.OrderRuleScopes.scopesFor(rule)))scopeController.setScopes(window.OrderRuleScopes.scopesFor(rule));resourceController.setDirectory(rule.archiveDirectory);}
|
if(normalize){for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','filenameScheme','productLine']){const input=form.elements.namedItem(name);if(input&&rule[name]!==undefined)input.value=rule[name];}for(const name of ['to','cc'])form.elements.namedItem(name).value=(rule[name]||[]).join('\n');const folder=form.elements.namedItem('archiveOrderFolder');if(folder)folder.checked=rule.archiveOrderFolder===true;const attachPdf=form.elements.namedItem('attachPdf');if(attachPdf)attachPdf.checked=rule.attachPdf===true;const bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary');if(bodyWithoutSummary)bodyWithoutSummary.checked=rule.bodyWithoutSummary===true;const verbatim=form.elements.namedItem('keepTitleVerbatim');if(verbatim)verbatim.checked=rule.keepTitleVerbatim===true;if(JSON.stringify(window.OrderRuleScopes.read(form))!==JSON.stringify(window.OrderRuleScopes.scopesFor(rule)))scopeController.setScopes(window.OrderRuleScopes.scopesFor(rule));resourceController.setDirectory(rule.archiveDirectory);}
|
||||||
updateVersion();coverage();const issues=panel.querySelector('#rule-validation-issues');issues.innerHTML=rule.validationIssues?.length?'<div class="mt-3"><strong class="small">启用前待完善</strong><ul class="small text-secondary mt-2 mb-0">'+rule.validationIssues.map(value=>'<li>'+esc(typeof value==='string'?value:value.message||'配置需要检查')+'</li>').join('')+'</ul></div>':'';
|
updateVersion();coverage();const issues=panel.querySelector('#rule-validation-issues');issues.innerHTML=rule.validationIssues?.length?'<div class="mt-3"><strong class="small">启用前待完善</strong><ul class="small text-secondary mt-2 mb-0">'+rule.validationIssues.map(value=>'<li>'+esc(typeof value==='string'?value:value.message||'配置需要检查')+'</li>').join('')+'</ul></div>':'';
|
||||||
}
|
}
|
||||||
drawList();
|
drawList();
|
||||||
|
|||||||
Reference in new issue
Block a user