feat: add category order rules and read-only sent mail history
This commit is contained in:
1 parent
388805a8a6
commit
efa982a8a1
41 files changed
+1828
-28
No files matched your search
@@ -0,0 +1,57 @@
|
||||
# 分类通知规则首版
|
||||
|
||||
入口:侧栏“分类通知规则”。六个页签为工作台、通知规则、待发批次、订单记录、发送记录、设置。
|
||||
|
||||
## 收单范围
|
||||
|
||||
按节点收到时间(不是流程发起时间)和北京时间计算,包含起点、不包含终点。
|
||||
|
||||
| 批次 | 以11:00和17:00为例 |
|
||||
| --- | --- |
|
||||
| 正常工作日上午 | 当天00:00至11:00 |
|
||||
| 正常工作日下午 | 当天11:00至17:00 |
|
||||
| 周一上午 | 上个工作日最后截止时点至周一11:00,通常为周五17:00开始 |
|
||||
|
||||
业务日历决定实际工作日。更早历史不归档、不补发,过期未发送批次取消。历史发送结果不明保留人工核验,不自动重发。具体发送时间在“发送计划”维护。
|
||||
|
||||
每个有效类别在一个时段内汇总为一封邮件,普通通知和更改分开,不按产品线误分类。缺必需PDF或归档证据会阻塞本类别;不会静默漏掉本时段订单。超过邮箱容量限制时阻塞整类并提示。
|
||||
|
||||
## 配置和对应关系
|
||||
|
||||
Excel15个类别已建立。选择类别后维护适用流程、节点、字段适配器、归档共享路径、文件名日期来源、主题、正文引导语、签名及主送/抄送名单。
|
||||
|
||||
Excel只有归档分类目录名,完整服务器共享路径与“日期”具体来源仍需业务确认。不会凭目录名猜服务器地址。
|
||||
|
||||
保存产生草稿,原发布版本继续服务已有任务。字段对应面板显示中文业务字段、xdatabind来源及样本值。高级选项可替换真实业务样本;校验展示命中原因、缺失字段和多重规则冲突。预置演示样本仅帮助理解,不能作为发布依据。
|
||||
|
||||
发布要求当前草稿经过真实结构样本校验、所有适用流程具备已核验字段适配、业务配置完整且无启用规则冲突。当前只核对了备损更改v1.4和海外返工更改v1.1表单结构,其余需补充适配。若只验证一个流程,可明确缩小适用流程范围。
|
||||
|
||||
未入批次的任务可由管理员填写依据后重新核对,应用当前规则并清除旧归档准备结果。已发送或已固定批次不会被规则修改覆盖。
|
||||
|
||||
## 标题生成邮件正文
|
||||
|
||||
标题按每个“订单号:”拆成独立段落,只保留订单号、机芯号、产品型号、客户简称、总数量、订单类别,去除客户等级、毛利、订单类型和业务模式。中文冒号、换行和`<br>`可识别;第二段`HA`订单不会遗漏,也不会只凭`HA`前缀推断工厂。原始标题保留在加密事件中以便追溯。
|
||||
|
||||
在规则的样本试运行面板粘贴“BPM 原始标题”,可对照原文与正文结果。真实接入使用样本的`title`字段;旧`brief`包含订单号标签时同样执行提取,未提供标题的现有更改摘要继续兼容。显式标题中没有订单段落或有空订单号时校验阻塞,不能静默丢掉订单。
|
||||
|
||||
标题的业务模式或客户简称出现“惠州”时只标注额外通知待核实。工厂额外邮件的主送、抄送、附件及触发条件尚需历史已发送邮件佐证,不自动生成第二封。
|
||||
|
||||
## 只读核对历史邮件
|
||||
|
||||
本机规则预览的“邮箱管理”提供只读历史入口。管理员可添加仅含IMAP配置的邮箱,授权码在本机表单输入并加密保存,不需要SMTP配置。保存不会连接邮箱;点击“连接并列出已发送文件夹”后再按日期和主题查询。
|
||||
|
||||
一次最多查询31天,显示最近20封(服务端上限50封);逐封打开正文、主送/抄送和附件名称。读取使用只读文件夹与UID,不标已读、不删除、不移动、不更新模板收信游标。正文以转义文本显示,不加载远程图片;正文截断和10MB容量限制明确提示。文件夹UID有效期变化时必须重新查询。
|
||||
|
||||
需要邮箱开通IMAP,且历史邮件已同步至服务器。仅有SMTP授权码或仅保存在Foxmail本地的已发送邮件无法通过此入口读取。真实邮箱尚未配置,当前已验证的是本地接口和模拟服务器流程,不代表已读取真实历史邮件。
|
||||
|
||||
## 接入边界
|
||||
|
||||
首版已实现本地规则维护、精确匹配、字段追踪、状态和版本存储、按时段类别组批、受控SMTP调度和异常核验。
|
||||
|
||||
实时待办、自动PDF导出和归档执行器尚未完成联调,页面明确显示“待联调”,默认暂停且禁止启用生产发送。现有待阅扫描不会冒充待办接入。BPM的提交/结束始终由人工办理。
|
||||
|
||||
## 独立预览
|
||||
|
||||
在项目目录运行 `node scripts/rules-preview.cjs`,访问本机18786端口并点击“进入演示空间”。该空间与正式数据隔离,不访问BPM、不保存业务文件、不发邮件。
|
||||
|
||||
可用 `--seed-file` 指定本机从Excel读取的15类名单JSON,私密名单只写入本地加密库,不进入代码仓库;`--state-dir`和`--port`可指定独立目录和端口。导入只初始化尚不存在的类别,不覆盖已有编辑。此预览的邮箱接口只允许IMAP历史查询,拒绝模板收信、SMTP检查和测试发信,不启动定时收信服务。
|
||||
@@ -0,0 +1,44 @@
|
||||
# Order Rules Implementation Plan
|
||||
|
||||
> **For agentic workers:** Use subagent-driven-development for independent domain and Web tasks; integrate and review in this session.
|
||||
|
||||
**Goal:** Create a usable first Web version of Excel category rules, explicit field mapping, deterministic preview and stateful order/batch records.
|
||||
|
||||
**Architecture:** Isolated order-rules module consumes verified form adapters and reusable mailbox/calendar infrastructure. Local encrypted storage holds business data; capabilities block unverified external execution.
|
||||
|
||||
**Tech Stack:** Node >=22.13, CommonJS, node:sqlite, existing BpmVault, Tabler/vanilla JS, node:test.
|
||||
|
||||
**Spec:** docs/superpowers/specs/2026-10-19-order-rules-design.md
|
||||
|
||||
## Global Constraints
|
||||
|
||||
15 Excel categories; one mail per category per slot; manual BPM handling; no private recipient lists committed; no live sends during construction; default paused; unverified production providers explicit; modules separated.
|
||||
|
||||
### Task 1: Catalog and field adapters
|
||||
- [x] Read Excel locally, preserve raw business intent, import private values only into encrypted local store.
|
||||
- [x] Write failing matching tests: target node exactness, zero quantity, no unsupported adapter, multiple matches.
|
||||
- [x] Implement catalog.cjs and matching.cjs per spec, then run tests.
|
||||
|
||||
### Task 2: State and version persistence
|
||||
- [x] Write state tests for duplicate events, conflicting drafts, transition legality, blocked category, cutoff and full aggregation, recovery.
|
||||
- [x] Implement store.cjs, state.cjs and batch.cjs with encrypted persistent evidence/snapshots.
|
||||
- [x] Add API, application lifecycle integration and HTTP role/origin tests.
|
||||
|
||||
### Task 3: Web editor and workbench
|
||||
- [x] Implement focused view/editor/preview modules under web/modules/order-rules.
|
||||
- [x] Add scripts/assets/nav and isolated preview runtime with first-run catalog.
|
||||
- [x] Exercise save/reload, readable execution summary, field trace, paused state and unsupported capability feedback.
|
||||
|
||||
### Task 4: Integration and review
|
||||
- [x] Integrate scheduled dispatch gate with existing mail service; keep provider limitations explicit and no arbitrary archive attestations.
|
||||
- [x] Run targeted domain/state/HTTP checks, complete npm test and browser workflow.
|
||||
- [x] Review spec and code for false readiness, privacy leakage, retry/duplicate errors; fix findings and document verified scope.
|
||||
|
||||
### Task 5: Confirmed title extraction and read-only historical evidence
|
||||
- [x] User example red/green regression: retain both ordinary and HA order paragraphs, remove metadata, preserve raw title; Chinese colons/zero quantity and missing order checks.
|
||||
- [x] Expose title input and original/result comparison with Huizhou evidence marked pending, without automatic extra email.
|
||||
- [x] Add IMAP-only local configuration and bounded sent-folder history search/detail with admin/origin gates, no SMTP, no seen/flag/cursor changes, no remote content loading.
|
||||
- [x] Verify service/API/preview/browser paths with simulated mailbox and no external SMTP/BPM calls.
|
||||
- [x] Finish combined full regression and live preview check; document pending real mailbox evidence.
|
||||
|
||||
Validation: combined full regression 282 tests, 281 passed, 0 failed, 1 expected skip (official ZCode CLI not configured). Local browser verified exact two-order title extraction and empty IMAP-only configuration form. Real mailbox history and production BPM/PDF/archive providers remain pending integration.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Excel 分类通知规则与执行状态
|
||||
|
||||
用户已批准聊天中六部分 Web 设计及状态机、字段对应关系、真实样本试运行、规则版本管理,2026-10-19 指示创建首版。
|
||||
|
||||
## 业务约束
|
||||
|
||||
- Excel `订单通知书邮件发送信息.xls` 的15类是分类依据,同一业务时段内同类汇总一封;通知与更改不混合,不能按产品线决定类别。
|
||||
- BPM 节点由人工办理。程序不得提交、结束或更改流程。
|
||||
- 自动发送默认暂停。现有待阅扫描不冒充待办接入,DOM 字段证据不冒充实时 API 验证。首版提供真实样本校验与接入接口,未验证适配器不能启用生产规则。
|
||||
- 修改生成草稿;发布须校验字段适配、名单、目录、命名日期和样本。历史任务固定原规则,规则版本变化不产生新事件。
|
||||
- 订单状态:identified、preparing、archived、pending、batched、sent;失败为blocked;发送不确定为unknown。批次状态:prepared、sending、sent、failed、unknown、cancelled。状态由动作控制,不能任意置成功。
|
||||
- 去重键为connectionId/source/instanceId/taskId/revision;订单号不是唯一键。数量为零合法。多条规则命中阻塞,不模糊匹配。
|
||||
- 用户补充并确认:正常工作日首封只取当天00:00到首个发送时点,第二封取首个时点到第二时点;周一首封从上个工作日最后时点起算,例如周五17:00到周一11:00。采用北京时间 [start,end),11点整归下午,边界不重复。业务日历休息/暂停间隔按上个实际工作日计算。
|
||||
- 以节点接收时间receivedAt归入时段,ingestedAt记录采集时间。更早历史不归档、不补发,过期未发批次取消,结果不明的历史批次仅保留人工核验。新发现但属于已关闭时段的记录不滚入后续邮件。无50/200条静默截断,邮件大小超限阻塞整类。
|
||||
- 手工整理只能在已配置发送时点的60秒执行宽限内操作,页面预览不可提前固定邮件。缺必需文件阻塞本类别,不影响其他类别;错过本时段不在下时段补发。
|
||||
- SMTP 已接受不等于最终送达;进入发送后异常或部分接受均为unknown,核实后才重试。重启sending恢复unknown。
|
||||
|
||||
## 模块与接口
|
||||
|
||||
新增 src/modules/order-rules,独立加密 SQLite,复用现有鉴权、审计、邮件和日历。不替换旧通知数据。web/modules/order-rules 下拆分页面渲染与编辑器。
|
||||
|
||||
Domain exports from catalog.cjs: `seedRules()` -> array of rule objects; `adapters` -> array `{id,label,processName,processVersion,verified,fields,sample}`. No embedded private recipient lists in repository; Excel private recipients/archive addresses imported locally to encrypted store via optional local file.
|
||||
|
||||
Rule object: `{id,version,status:'draft'|'enabled'|'paused',name,categoryId,processNames:[],nodeNames:[],adapterIds:[],archiveDirectory,filenameDate:'appDate'|'receivedAt'|'archiveDate'|'',subjectPrefix,intro,signature,to:[],cc:[],attachPdf:boolean,sourceRow:number}`. Adapter fields maps standard keys to xdatabind; sample `{connectionId,source:'todo',instanceId,taskId,revision,processName,processVersion,nodeName,receivedAt,serialNum,title?,brief,fields:{[xdatabind]:value}}`.
|
||||
|
||||
Domain exports from matching.cjs: `previewMatch(rules,adapters,sample)` -> `{valid,ruleId,categoryId,event,checks:[{label,ok,detail}],issues:[],explanation,fieldTrace:[{key,label,path,value}],candidates:[]}`. Normalized event has identity above plus orderNo/appDate/customer/productLine/quantity/brief, no hidden network calls. `describeRule(rule)` Chinese execution summary. Validation is deterministic, no AI and no eval. Adapter verified means sample field structure verified only; service independently gates production availability.
|
||||
|
||||
Store exports RuleStore(dir,{clock?}), methods snapshot()->`{rules,adapters,orders,batches,settings,audit,capabilities}`; saveRule(input,actor), publish(id,{version},actor), pause(id,{version},actor), preview(sample), ingest(sample,actor), recordArchive(id,evidence,actor), retryArchive(id,note,actor), prepare(cutoff,actor), beginSending(id), finishSending(id,status,message), resolve(id,{resolution,note},actor), settings(), saveSettings(input,actor), close(). Rule draft update input uses optimistic version. snapshot rules include publishedVersion and draft dirty flag as applicable. settings `{version,enabled:false,channelId:'',maxMessageBytes:20971520}`. capabilities clearly report liveTodo:false,pdfExport:false,automaticArchive:false initially.
|
||||
|
||||
recordArchive requires server-created evidence `{files:[{name,path,sha256,size,kind:'pdf'|'notice'}],archivedAt}` verified by archive executor; HTTP never permits clients to assert archive success. No live archive provider => ingest allowed only as blocked task, not sendable. Preview samples never create orders. prepare freezes exact rule/mail/recipient and per-order evidence snapshots and creates one batch/category; blocked/mixed rule versions prevent that category from sending. View only automatic disabled until providers verified. Batch contains id/categoryId/status/subject/text/html/to/cc/orderIds/orderNos/attachments/cutoff/createdAt/error. No data URLs or remote arbitrary URLs accepted.
|
||||
|
||||
API prefix `/api/order-rules`: GET root snapshot, POST `/rules` save draft (admin); POST `/rules/:id/publish`, `/pause` (admin); POST `/preview` `{sample}` (operator/admin); POST `/events` `{sample}` (operator/admin); POST `/settings` (admin); POST `/prepare` `{cutoff}` (admin); POST `/batches/:id/resolve` (admin). Preserve origin/session checks; audit mutations. No external-send endpoint in first UI; scheduled dispatch gated by capabilities/settings.
|
||||
|
||||
Web entry `#order-rules`, tab views workbench/rules/pending/orders/history/settings. GET above. UI Chinese, real empty states, no fabricated successful tasks; from sample JSON advanced import -> readable field trace. Rule editor normal business fields not JSON paths. Field panel shows verified sample and limitations. Existing integrations remain available separately. Preview/test runtime uses isolated loopback data and no SMTP/BPM.
|
||||
|
||||
## 2026-10-19 标题与历史邮件纠正
|
||||
|
||||
新增`title.cjs`确定性提取:按订单号分段,保留订单号、机芯号、产品型号、客户简称、总数量、订单类别。客户等级、毛利、订单类型、业务模式不进入正文。原始标题、逐段订单号和惠州线索保存于加密事件;惠州线索仅待核实,不推断HA前缀,不触发额外发信。显式标题无订单段落或订单号为空时阻塞。旧brief已包含订单号标签时同样提取,现有无标题更改摘要兼容。
|
||||
|
||||
新增`mail/history.cjs`与`web/modules/mail/history.js`,复用加密MailStore与MailService连接互斥。只读账号仅保存IMAP,不能发信、收取模板或验证SMTP。历史查询为管理员同源POST `/api/mail/channels/:id/history`,支持folders/search/message,服务器已发送文件夹只读锁、UID有效期、31天范围、50封上限、10MB源邮件限制;只返回纯文本及附件元信息,HTML不执行、图片不加载,不更改游标和邮件标记。隔离规则预览启用historyOnly接口门控且不启动MailService定时器。邮箱未配置时真实历史判断保持未完成,待本机配置后只读核对通知要求。
|
||||
|
||||
## Verification
|
||||
|
||||
Behavior tests: exact matching and aliases, missing adapter, zero quantity, collisions, >200 aggregate, cutoff/new arrivals, duplicate revision, illegal transitions, missing PDF, rule version race, persist/reopen/recover, role/origin checks, no production side effects in preview. UI browser exercise edit/save/reload/sample trace/pending/records. Run complete npm test before completion.
|
||||
+10
-4
@@ -6,8 +6,11 @@ const path=require('node:path');
|
||||
const {Store}=require('../src/modules/dashboard/store.cjs');
|
||||
const {WorkspaceStore}=require('../src/modules/workspace/store.cjs');
|
||||
const {createDashboard}=require('../src/app/dashboard.cjs');
|
||||
const {RuleStore}=require('../src/modules/order-rules/store.cjs');
|
||||
const {MailStore}=require('../src/modules/mail/store.cjs');
|
||||
const {MailService}=require('../src/modules/mail/service.cjs');
|
||||
|
||||
async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776}={}) {
|
||||
async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776,ruleSeedOverrides=[],mailHistory=false}={}) {
|
||||
fs.mkdirSync(stateDir,{recursive:true});
|
||||
const store=new Store(path.join(stateDir,'accounts'));
|
||||
if(!store.users().length) {
|
||||
@@ -17,7 +20,10 @@ async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.h
|
||||
const admin=store.users().find(user=>user.role==='admin');
|
||||
if(!admin)throw Error('演示空间缺少管理员,请检查独立演示数据目录。');
|
||||
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
|
||||
const orderRules=new RuleStore(path.join(stateDir,'order-rules'),{seedOverrides:ruleSeedOverrides,schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides});
|
||||
let mailStore,mail;
|
||||
try {
|
||||
if(mailHistory){mailStore=new MailStore(path.join(stateDir,'mail-history'));mail=new MailService({store:mailStore});mail.historyOnly=true;}
|
||||
const snapshot=workspace.snapshot(store.users());
|
||||
if(!snapshot.exceptions.length) {
|
||||
for(const item of [
|
||||
@@ -27,11 +33,11 @@ async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.h
|
||||
])workspace.createException(item,admin,store.users());
|
||||
}
|
||||
if(!snapshot.connections.length)workspace.createConnection({name:'演示 BPM 连接',owner:admin.username},admin,store.users());
|
||||
const server=createDashboard({store,workspace,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
|
||||
const server=createDashboard({store,workspace,orderRules,mail,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
|
||||
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});
|
||||
let closed=false;
|
||||
return {server,store,workspace,async close(){if(closed)return;closed=true;await new Promise(resolve=>server.close(resolve));workspace.close();}};
|
||||
} catch(error) { workspace.close();throw error; }
|
||||
return {server,store,workspace,orderRules,mail,async close(){if(closed)return;closed=true;await mail?.stop();await new Promise(resolve=>server.close(resolve));workspace.close();orderRules.close();mailStore?.close();}};
|
||||
} catch(error) { await mail?.stop();workspace.close();orderRules.close();mailStore?.close();throw error; }
|
||||
}
|
||||
|
||||
if(require.main===module)startPreview().then(runtime=>{
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
// Isolated local rule configuration. Never loads production sessions or SMTP.
|
||||
const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
|
||||
const {startPreview}=require('./preview.cjs');
|
||||
async function main(){
|
||||
const args=process.argv.slice(2),options={};
|
||||
for(let i=0;i<args.length;i+=2){if(!['--seed-file','--state-dir','--port'].includes(args[i])||!args[i+1])throw Error('支持参数:--seed-file 文件 --state-dir 目录 --port 端口');options[args[i]]=args[i+1];}
|
||||
const port=Number(options['--port']||18786);if(!Number.isInteger(port)||port<1024||port>65535)throw Error('预览端口无效。');
|
||||
let ruleSeedOverrides=[];
|
||||
if(options['--seed-file']){
|
||||
const filename=path.resolve(options['--seed-file']);if(fs.statSync(filename).size>1024*1024)throw Error('导入文件过大。');
|
||||
const rows=JSON.parse(fs.readFileSync(filename,'utf8'));if(!Array.isArray(rows)||rows.length!==15)throw Error('导入文件必须包含15个类别。');
|
||||
ruleSeedOverrides=rows.map(({id,to,cc,archiveDirectory})=>({id,to,cc,archiveDirectory}));
|
||||
}
|
||||
const stateDir=path.resolve(options['--state-dir']||path.join(process.env.LOCALAPPDATA||os.homedir(),'OrderNotificationAutomation','rules-preview'));
|
||||
const fresh=!fs.existsSync(path.join(stateDir,'accounts','state.sqlite'));
|
||||
const runtime=await startPreview({stateDir,port,ruleSeedOverrides,mailHistory:true});
|
||||
if(fresh){const settings=runtime.store.settings();runtime.store.saveSettings({schedule:{...settings.schedule,times:['11:00','17:00']}},settings.version,'规则预览初始化');}
|
||||
console.log(`分类通知规则:http://127.0.0.1:${port}/#order-rules\n独立配置空间;BPM、自动归档和邮件发送均未连接。`);
|
||||
const stop=()=>runtime.close().then(()=>process.exit(0));process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
||||
return runtime;
|
||||
}
|
||||
if(require.main===module)main().catch(error=>{console.error('规则预览启动失败:'+error.message);process.exitCode=1;});
|
||||
module.exports={main};
|
||||
+10
-5
@@ -21,6 +21,8 @@ const { StorageStore } = require('../modules/storage/store.cjs');
|
||||
const { StorageService } = require('../modules/storage/service.cjs');
|
||||
const { NotificationStore } = require('../modules/notifications/store.cjs');
|
||||
const { NotificationService } = require('../modules/notifications/service.cjs');
|
||||
const { RuleStore } = require('../modules/order-rules/store.cjs');
|
||||
const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs');
|
||||
|
||||
async function closeServer(server){
|
||||
if(!server)return;
|
||||
@@ -51,7 +53,7 @@ async function main(options = {}) {
|
||||
if(errors.length)throw new AggregateError(errors,'关闭服务时部分资源清理失败。');
|
||||
})();
|
||||
let server,dashboard,store,workspace,bpmSessions,custodian;
|
||||
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health;
|
||||
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,orderRules,orderDispatcher,assistantStore,assistant,health;
|
||||
try {
|
||||
const tokenPath = path.join(stateDir,'pairing.key');
|
||||
let token;
|
||||
@@ -69,9 +71,9 @@ async function main(options = {}) {
|
||||
workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
|
||||
// Register conditional closures before constructing later resources; partial startup follows the same path.
|
||||
cleanup.push(()=>closeServer(server));
|
||||
cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown());
|
||||
cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown());
|
||||
cleanup.push(()=>closeServer(dashboard),()=>workspace.close());
|
||||
cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>assistantStore?.close());
|
||||
cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close());
|
||||
bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
|
||||
custodian=new BpmCustodian({workspace,manager:bpmSessions});
|
||||
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
|
||||
@@ -79,21 +81,24 @@ async function main(options = {}) {
|
||||
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
|
||||
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
|
||||
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notificationStore.recover();notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
|
||||
orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides});
|
||||
orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
|
||||
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
|
||||
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail});
|
||||
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
|
||||
workspace.markSessionChecksPending();
|
||||
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,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,orderRules,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
|
||||
health.start();
|
||||
orderDispatcher.start();
|
||||
if(!options.quiet){
|
||||
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
|
||||
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
|
||||
console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`);
|
||||
if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`);
|
||||
}
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop};
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,assistant,health,stop};
|
||||
}catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
|
||||
}
|
||||
module.exports={main};
|
||||
@@ -8,6 +8,7 @@ function createAssets(){
|
||||
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
|
||||
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
|
||||
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
|
||||
'/mail-history.js':{path:path.join(webRoot,'modules/mail/history.js'),type:'text/javascript'},
|
||||
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
|
||||
'/storage.js':{path:path.join(webRoot,'modules/storage/view.js'),type:'text/javascript'},
|
||||
'/storage-preview.html':{path:path.join(webRoot,'modules/storage/preview.html'),type:'text/html',preview:true},
|
||||
@@ -15,6 +16,9 @@ function createAssets(){
|
||||
'/storage-preview-office.js':{path:path.join(webRoot,'modules/storage/preview-office.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-host.js':{path:path.join(webRoot,'modules/storage/preview-host.js'),type:'text/javascript'},
|
||||
'/storage-preview.css':{path:path.join(webRoot,'modules/storage/preview.css'),type:'text/css',preview:true},
|
||||
'/order-rules-editor.js':{path:path.join(webRoot,'modules/order-rules/editor.js'),type:'text/javascript'},
|
||||
'/order-rules-preview.js':{path:path.join(webRoot,'modules/order-rules/preview.js'),type:'text/javascript'},
|
||||
'/order-rules.js':{path:path.join(webRoot,'modules/order-rules/view.js'),type:'text/javascript'},
|
||||
'/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'},
|
||||
'/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'},
|
||||
'/health.js':{path:path.join(webRoot,'modules/health/view.js'),type:'text/javascript'},
|
||||
|
||||
@@ -6,13 +6,14 @@ const {mailApi}=require('../modules/mail/api.cjs');
|
||||
const {bpmScanApi}=require('../modules/bpm/scan-api.cjs');
|
||||
const {storageApi}=require('../modules/storage/api.cjs');
|
||||
const {notificationApi}=require('../modules/notifications/api.cjs');
|
||||
const {orderRuleApi}=require('../modules/order-rules/api.cjs');
|
||||
const {assistantApi}=require('../modules/assistant/api.cjs');
|
||||
const {respondToPing}=require('../platform/service/ping.cjs');
|
||||
const {createAssets,PREVIEW_CSP}=require('./assets.cjs');
|
||||
const {createAuth}=require('../modules/dashboard/auth.cjs');
|
||||
const {prepareRequest,readBody}=require('./request.cjs');
|
||||
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy=false}) {
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,orderRules,assistant,health,watchdog,trustedProxy=false}) {
|
||||
const auth=createAuth({store,previewUserId,bpmSessions});
|
||||
let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;}
|
||||
const server=http.createServer(async(request,response)=>{
|
||||
@@ -37,6 +38,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
|
||||
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
|
||||
if(await orderRuleApi({orderRules,mail,workspace,user,route,method:request.method,body,reply}))return;
|
||||
if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return;
|
||||
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
|
||||
if(await dashboardApi({store,outputDir,workspace,mail,scanner,storage,user,route,request,response,body,reply,fail}))return;
|
||||
|
||||
@@ -4,13 +4,19 @@ const fail=(message,status)=>{throw Object.assign(new Error(message),{status});}
|
||||
async function mailApi({mail,workspace,user,route,method,body,request,response,reply,trustedProxy}){
|
||||
if(!route.startsWith('/api/mail'))return false;if(!mail)fail('邮件服务暂不可用。',503);const store=mail.store;
|
||||
if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403);
|
||||
if(route==='/api/mail'&&method==='GET'){reply(200,{channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
|
||||
if(route==='/api/mail'&&method==='GET'){reply(200,{historyOnly:mail.historyOnly===true,channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
|
||||
const audit=(action,detail)=>workspace?.record(user,action,detail);
|
||||
if(route==='/api/mail/channels'&&method==='POST'){
|
||||
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403);
|
||||
if(mail.historyOnly&&body?.readOnly!==true)fail('此空间只允许配置只读 IMAP 邮箱。',409);
|
||||
if(body?.id&&mail.busy(body.id))fail('此邮箱正在执行操作,请稍后保存。',409);const saved=store.saveChannel(body);audit('mail.channel.save',saved.name);reply(body.id?200:201,saved);return true;
|
||||
}
|
||||
let match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
|
||||
let match=/^\/api\/mail\/channels\/([\w-]+)\/history$/.exec(route);
|
||||
if(match&&method==='POST'){
|
||||
const result=await mail.history(match[1],body);audit('mail.history.read',store.publicChannel(match[1]).name+' · '+String(body.action));reply(200,result);return true;
|
||||
}
|
||||
if(mail.historyOnly&&method==='POST')fail('此空间仅允许查询历史邮件,不能发信或收取模板。',409);
|
||||
match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
|
||||
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
|
||||
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
|
||||
if(match){const [,id,action,index]=match;const template=store.template(id);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
const {simpleParser}=require('mailparser');
|
||||
const {MAX_MAIL}=require('./parser.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const sent=folder=>folder.specialUse==='\\Sent'||/^(?:sent|sent items|sent messages|已发送|已发送邮件)$/iu.test(folder.name||folder.path.split(folder.delimiter||'/').at(-1));
|
||||
const addresses=values=>(values||[]).slice(0,100).map(({name,address})=>({name:name||'',address:address||''}));
|
||||
function date(value){
|
||||
if(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value))fail('请选择有效的查询日期。');
|
||||
const result=new Date(value+'T00:00:00Z');if(!Number.isFinite(+result)||result.toISOString().slice(0,10)!==value)fail('查询日期无效。');return result;
|
||||
}
|
||||
async function readHistory(client,input={}){
|
||||
if(!['folders','search','message'].includes(input.action))fail('请选择只读邮件查询操作。');
|
||||
let query,limit;
|
||||
if(input.action==='search'){
|
||||
const since=date(input.since),before=date(input.before),span=before-since;
|
||||
if(span<=0||span>31*86400000)fail('每次查询最多31天,结束日期不包含当天。');
|
||||
limit=input.limit??20;if(!Number.isInteger(limit)||limit<1||limit>50)fail('每次最多显示50封邮件。');
|
||||
if(input.subject!==undefined&&(typeof input.subject!=='string'||input.subject.length>100||/[\x00-\x1f]/.test(input.subject)))fail('主题关键词无效。');
|
||||
query={sentSince:since,sentBefore:before,...(input.subject?.trim()?{subject:input.subject.trim()}: {})};
|
||||
}
|
||||
const folders=(await client.list()).filter(f=>sent(f)&&!f.flags?.has('\\Noselect')).map(f=>({path:f.path,name:f.name||f.path}));
|
||||
if(input.action==='folders')return {folders};
|
||||
if(!folders.some(f=>f.path===input.folder))fail('请选择服务器上的已发送文件夹。');
|
||||
const lock=await client.getMailboxLock(input.folder,{readOnly:true});
|
||||
try{
|
||||
const uidValidity=String(client.mailbox.uidValidity);
|
||||
if(input.action==='search'){
|
||||
const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
|
||||
for(const uid of uids.slice(0,limit)){
|
||||
const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
|
||||
messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
|
||||
}
|
||||
return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
|
||||
}
|
||||
if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
|
||||
if(input.uidValidity!==uidValidity)fail('邮件文件夹已变化,请重新查询后打开。',409);
|
||||
const info=await client.fetchOne(input.uid,{size:true},{uid:true});if(!info)fail('邮件已移除。',404);
|
||||
if(!Number.isSafeInteger(info.size)||info.size>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
|
||||
const source=await client.fetchOne(input.uid,{source:true},{uid:true});if(!source?.source)fail('邮件已移除。',404);
|
||||
if(source.source.length>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
|
||||
const parsed=await simpleParser(source.source,{skipHtmlToText:false,skipTextToHtml:true,skipImageLinks:true});
|
||||
const text=parsed.text||'';
|
||||
return {folder:input.folder,uid:input.uid,uidValidity,messageId:parsed.messageId||'',subject:parsed.subject||'',date:parsed.date?.toISOString()||null,from:addresses(parsed.from?.value),to:addresses(parsed.to?.value),cc:addresses(parsed.cc?.value),text:text.slice(0,100000),truncated:text.length>100000,attachments:parsed.attachments.map(a=>({filename:a.filename||'',size:a.size,contentType:a.contentType}))};
|
||||
}finally{lock.release();}
|
||||
}
|
||||
module.exports={readHistory};
|
||||
@@ -7,8 +7,13 @@ class MailService{
|
||||
busy(id){return this.running.has(id);}
|
||||
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
|
||||
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
|
||||
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
|
||||
history(id,input){return this.exclusive(id,async()=>{
|
||||
const config=this.store.channelSecret(id);
|
||||
try{const result=await this.withImap(config.imap,client=>require('./history.cjs').readHistory(client,input));this.store.guard(id,config.version);return result;}
|
||||
catch(error){if([400,404,409,413].includes(error.status))throw error;fail(safeError(error,'IMAP'));}
|
||||
});}
|
||||
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
|
||||
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
|
||||
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
|
||||
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
|
||||
@@ -22,7 +27,7 @@ class MailService{
|
||||
}finally{lock.release();}});
|
||||
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
|
||||
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id),t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
|
||||
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
|
||||
}
|
||||
|
||||
@@ -29,14 +29,15 @@ class MailStore{
|
||||
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
|
||||
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
|
||||
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
|
||||
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
|
||||
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
|
||||
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
|
||||
saveChannel(input){return this.transaction(()=>{
|
||||
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
|
||||
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
|
||||
if(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100)fail('请填写模板发件人名单,并选择是否启用收信。');
|
||||
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind].password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
|
||||
const saved={name:text(input.name,'邮箱名称',80),email:address,smtp:endpoint('smtp'),imap:endpoint('imap'),senders:[...new Set(input.senders.map(email))],enabled:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
|
||||
const readOnly=input.readOnly===true;
|
||||
if(!readOnly&&(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100))fail('请填写模板发件人名单,并选择是否启用收信。');
|
||||
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind]?.password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
|
||||
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
|
||||
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
|
||||
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
|
||||
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
|
||||
|
||||
@@ -25,7 +25,7 @@ class NotificationService{
|
||||
if(this.stopped)break;
|
||||
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
|
||||
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
|
||||
try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.beginSending(batch);sending=true;
|
||||
try{if(channel.readOnly)throw Error('只读邮箱不能发送邮件。');transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.beginSending(batch);sending=true;
|
||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
|
||||
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 连接检查失败,请查看通知队列的重试状态。');}finally{transport?.close?.();}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
const {fail}=require('./validation.cjs');
|
||||
async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply}){
|
||||
if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
|
||||
if(!orderRules)fail('分类通知规则服务未启动。',503);
|
||||
if(route==='/api/order-rules'&&method==='GET'){reply(200,orderRules.snapshot());return true;}
|
||||
if(method!=='POST')fail('没有找到此规则操作。',404);
|
||||
if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
|
||||
const actor=user.username;
|
||||
if(route==='/api/order-rules/preview'||route==='/api/order-rules/events'){
|
||||
if(!body||Object.keys(body).some(k=>k!=='sample')||!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');
|
||||
const preview=route.endsWith('/preview');reply(preview?200:201,preview?orderRules.preview(body.sample):orderRules.ingest(body.sample,actor));
|
||||
if(!preview)workspace?.record(user,'识别分类通知订单','来源任务 '+String(body.sample.taskId));return true;
|
||||
}
|
||||
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
|
||||
let result;
|
||||
if(route==='/api/order-rules/rules')result=orderRules.saveRule(body,actor);
|
||||
else if(route==='/api/order-rules/settings'){
|
||||
if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
|
||||
result=orderRules.saveSettings(body,actor);
|
||||
}else if(route==='/api/order-rules/prepare'){
|
||||
if(!body||Object.keys(body).some(k=>k!=='cutoff'))fail('请提供发送截止时间。');
|
||||
const window=orderRules.snapshot().window;
|
||||
if(!window?.available||Date.parse(body.cutoff)!==Date.parse(window.end))fail('仅能在配置的发送时点整理本时段订单;更早历史不补发。',409);
|
||||
result=orderRules.prepare(body.cutoff,actor,window);
|
||||
}else{
|
||||
const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause)$/.exec(route);
|
||||
const batch=/^\/api\/order-rules\/batches\/([\w-]+)\/resolve$/.exec(route);
|
||||
const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
|
||||
if(rule){if(!body||Object.keys(body).some(k=>k!=='version'))fail('请提供当前草稿版本。');result=orderRules[rule[2]](rule[1],body,actor);}
|
||||
else if(batch){if(!body||Object.keys(body).some(k=>!['resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor);}
|
||||
else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
|
||||
else fail('没有找到此规则操作。',404);
|
||||
}
|
||||
workspace?.record(user,'维护分类通知规则',route.slice('/api/order-rules'.length));reply(200,result);return true;
|
||||
}
|
||||
module.exports={orderRuleApi};
|
||||
@@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
|
||||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const lines=value=>escape(value).replace(/\r?\n/g,'<br>');
|
||||
|
||||
function recipients(values,label){
|
||||
if(!Array.isArray(values))fail(`${label}邮箱名单无效。`);
|
||||
const result=[];
|
||||
for(const value of values){
|
||||
if(typeof value!=='string'||/[\r\n\x00-\x1f\x7f]/.test(value))fail(`${label}邮箱地址无效。`);
|
||||
const address=value.trim().toLowerCase();
|
||||
const parts=address.split('@'),local=parts[0],domain=parts[1];
|
||||
if(parts.length!==2||address.length>254||!local||local.length>64||!domain||!domain.includes('.')||!/^[-a-z0-9!#$%&'*+/=?^_`{|}~.]+$/i.test(local)||local.startsWith('.')||local.endsWith('.')||local.includes('..')||domain.split('.').some(p=>!p||p.length>63||! /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(p)))fail(`${label}邮箱地址无效。`);
|
||||
if(!result.includes(address))result.push(address);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function fileLink(filePath){
|
||||
if(filePath.startsWith('\\\\'))return 'file://'+filePath.slice(2).split('\\').map(encodeURIComponent).join('/');
|
||||
if(/^[a-z]:[\\/]/i.test(filePath))return 'file:///'+filePath.replace(/\\/g,'/').split('/').map((p,i)=>i===0?p:encodeURIComponent(p)).join('/');
|
||||
return 'file://'+filePath.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
function validFile(file){
|
||||
return file&&typeof file.name==='string'&&file.name.length>0&&!/[\r\n\x00-\x1f]/.test(file.name)&&typeof file.path==='string'&&!/[\r\n\x00-\x1f]/.test(file.path)&&(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))&&!/^[a-z]+:\/\//i.test(file.path)&&/^[a-f\d]{64}$/i.test(file.sha256)&&Number.isSafeInteger(file.size)&&file.size>=0&&['pdf','notice'].includes(file.kind);
|
||||
}
|
||||
|
||||
function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){
|
||||
const limit=Date.parse(cutoff);
|
||||
if(!Number.isFinite(limit)||!Number.isSafeInteger(maxMessageBytes)||maxMessageBytes<1)fail('截止时间或邮件大小设置无效。');
|
||||
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(!rule?.categoryId||!Array.isArray(orders)||!orders.length)fail('类别必须包含待发订单。');
|
||||
const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
|
||||
if(!to.length)fail('收件人名单不能为空。');
|
||||
const orderIds=[],orderNos=[],attachments=[],plain=[],html=[];
|
||||
for(const order of orders){
|
||||
if(!order?.id||orderIds.includes(order.id))fail('订单标识无效或重复。');
|
||||
if(order.ruleSnapshot?.categoryId!==rule.categoryId)fail('同一批次不能混合类别。');
|
||||
if(order.ruleSnapshot.id!==rule.id||order.ruleSnapshot.version!==rule.version)fail('同一类别包含不同规则版本,请核实后处理。');
|
||||
if(order.status&&order.status!=='pending')fail('此类别包含未准备完成的订单。');
|
||||
const received=Date.parse(order.event?.receivedAt);
|
||||
if(window&&(!Number.isFinite(received)||received<start||received>=end))fail('订单接收时间不属于本批时段窗口。');
|
||||
if(!Number.isFinite(received)||received>limit)fail('订单接收时间超出本批截止范围。');
|
||||
const number=order.event?.orderNo;
|
||||
if(typeof number!=='string'||!number.trim()||/[\r\n\x00-\x1f]/.test(number))fail('订单号无效。');
|
||||
if(!order.archive||!Number.isFinite(Date.parse(order.archive.archivedAt))||!Array.isArray(order.archive.files)||!order.archive.files.length)fail(`订单 ${number} 缺少归档证据,本类别已阻塞。`);
|
||||
if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
|
||||
if(rule.attachPdf&&!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
|
||||
orderIds.push(order.id);orderNos.push(number);
|
||||
const files=order.archive.files;
|
||||
attachments.push(...files.filter(file=>file.kind!=='pdf'||rule.attachPdf).map(file=>({...file})));
|
||||
plain.push(`${number}\n${String(order.event.brief??'')}\n${files.map(file=>file.path).join('\n')}`);
|
||||
html.push(`<li><strong>${escape(number)}</strong><br><span style="color:#0000ff">${lines(order.event.brief)}</span><br>${files.map(file=>`<a style="color:#0000ff" href="${escape(fileLink(file.path))}">${escape(file.path)}</a>`).join('<br>')}</li>`);
|
||||
}
|
||||
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
|
||||
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
|
||||
const snapshot={categoryId:rule.categoryId,subject:`${prefix} ${orderNos.join('、')}`,text:[rule.intro||'',...plain,rule.signature||''].filter(Boolean).join('\n\n'),html:`<div>${lines(rule.intro)}</div><ul>${html.join('')}</ul><div>${lines(rule.signature)}</div>`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).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
|
||||
// boundary overhead are intentionally overestimated rather than truncating.
|
||||
const encodedBytes=size=>Math.ceil(Math.ceil(size/3)*4/76)*78;
|
||||
let bytes=16384+encodedBytes(Buffer.byteLength(snapshot.subject+snapshot.text+snapshot.html,'utf8'))+Buffer.byteLength([...to,...cc].join(','))*4;
|
||||
for(const file of attachments)bytes+=encodedBytes(file.size)+4096+Buffer.byteLength(file.name,'utf8')*4;
|
||||
if(bytes>maxMessageBytes)fail(`本类别邮件大小超过容量限制(估计 ${bytes} 字节)。`);
|
||||
return snapshot;
|
||||
}
|
||||
module.exports={buildBatch};
|
||||
@@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
// Public business classification only. Recipient and archive values belong in
|
||||
// the encrypted local store and are deliberately absent from this catalog.
|
||||
const rows = [
|
||||
['overseas-notice', '海外订单通知书', ['海外运营订单评审', '海外宽带接入产品订单', '海外IPC订单评审', '海外返工订单评审']],
|
||||
['overseas-change', '海外订单更改通知书', ['海外运营订单更改评审', '海外宽带接入产品订单更改评审', '海外IPC订单更改评审', '海外返工订单更改评审']],
|
||||
['new-retail-notice', '新零售订单通知书', ['新零售订单评审']],
|
||||
['new-retail-change', '新零售订单更改通知书', ['新零售订单更改评审']],
|
||||
['domestic-notice', '国内订单通知书', ['国内运营订单评审']],
|
||||
['carrier-notice', '运营商事业部订单通知书', ['宽带事业订单评审']],
|
||||
['hardware-notice', '智能硬件订单通知书', ['智能硬件解决方案订单评审']],
|
||||
['retail-notice', '小湃订单通知书', ['零售国内订单评审']],
|
||||
['domestic-change', '国内、运营商事业部、零售、智能硬件订单更改通知书', ['国内运营订单更改评审', '宽带事业订单更改评审', '智能硬件解决方案订单更改评审', '零售国内订单更改评审', '国内、宽带返工订单更改评审', '零售国内返工订单更改评审']],
|
||||
['domestic-rework', '国内、运营商事业部、零售、智能硬件返工订单通知书', ['国内、宽带返工订单评审', '零售国内返工订单评审']],
|
||||
['processing-notice', '加工订单通知书', ['加工订单评审']],
|
||||
['bs-notice', '备损订单通知书', ['备损订单评审']],
|
||||
['bs-change', '备损订单更改通知书', ['备损订单更改评审']],
|
||||
['trial-notice', '试产订单通知书', ['试产订单评审', '中试样机制作申请', '研发样机制作申请']],
|
||||
['trial-change', '试产订单更改通知书', ['试产订单更改评审']],
|
||||
];
|
||||
|
||||
function seedRules() {
|
||||
return rows.map(([id, name, processNames], index) => ({
|
||||
id, version: 1, status: 'paused', name, categoryId: id,
|
||||
processNames: [...processNames],
|
||||
nodeNames: id === 'processing-notice' ? ['订单专员(激活)']
|
||||
: id.startsWith('trial-') ? ['订单专员(订单通知书)-海外', '订单专员(订单通知书)']
|
||||
: id === 'overseas-change' ? ['订单专员(订单通知书)', '订单更改通知书']
|
||||
: ['订单专员(订单通知书)'],
|
||||
adapterIds: ['bs-change', 'overseas-change'].includes(id) ? [id] : [],
|
||||
archiveDirectory: '', filenameDate: '', subjectPrefix: `【${name}】`,
|
||||
intro: `大家好:\n以下为${name},请查收!`, signature: '', to: [], cc: [],
|
||||
attachPdf: id.endsWith('-change'), sourceRow: index + 2,
|
||||
}));
|
||||
}
|
||||
|
||||
const adapters = [
|
||||
{
|
||||
id: 'bs-change', label: '备损订单更改评审 v1.4(字段样本已核对)',
|
||||
processName: '备损订单更改评审', processVersion: '1.4', verified: true,
|
||||
verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
|
||||
fields: {
|
||||
orderNo: 'OFR_BS_Applicant.OrderNum', appDate: 'OFR_BS_Applicant.AppDate',
|
||||
customer: 'OFR_BS_BInfo.CustomerName', productLine: 'OFR_BS_Applicant.ProductLine',
|
||||
changeReason: 'OFR_BS_Applicant.ChangeReason', changeContent: 'OFR_BS_Applicant.OrderChangeContent',
|
||||
},
|
||||
sample: {
|
||||
demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-BS-INSTANCE',
|
||||
taskId: 'DEMO-BS-TASK', revision: 0, processName: '备损订单更改评审', processVersion: '1.4',
|
||||
nodeName: '订单专员(订单通知书)', receivedAt: '2026-10-19T09:00:00+08:00',
|
||||
serialNum: 'DEMO-SERIAL-001', brief: '演示数据:备损订单更改,非真实业务记录。',
|
||||
fields: {
|
||||
'OFR_BS_Applicant.OrderNum': 'DEMO-BS-001', 'OFR_BS_Applicant.AppDate': '2026-10-19',
|
||||
'OFR_BS_BInfo.CustomerName': '演示客户', 'OFR_BS_Applicant.ProductLine': '演示产品线',
|
||||
'OFR_BS_Applicant.ChangeReason': '演示更改原因', 'OFR_BS_Applicant.OrderChangeContent': '演示更改内容',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'overseas-change', label: '海外返工订单更改评审 v1.1(字段样本已核对)',
|
||||
processName: '海外返工订单更改评审', processVersion: '1.1', verified: true,
|
||||
verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
|
||||
fields: {
|
||||
orderNo: 'OFR_HWLS_Applicant.OrderNum', appDate: 'OFR_HWLS_Applicant.AppDate',
|
||||
customer: 'OFR_HWLS_BInfo.CustomerName', quantity: 'OFR_HWLS_BInfo.TotalAmount',
|
||||
changeReason: 'OFR_HWLS_Applicant.ChangeReason', changeContent: 'OFR_HWLS_Applicant.OrderChangeContent',
|
||||
},
|
||||
sample: {
|
||||
demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-OVERSEAS-INSTANCE',
|
||||
taskId: 'DEMO-OVERSEAS-TASK', revision: 0, processName: '海外返工订单更改评审', processVersion: '1.1',
|
||||
nodeName: '订单更改通知书', receivedAt: '2026-10-19T09:01:00+08:00',
|
||||
serialNum: 'DEMO-SERIAL-002', brief: '演示数据:海外返工订单更改,非真实业务记录。',
|
||||
fields: {
|
||||
'OFR_HWLS_Applicant.OrderNum': 'DEMO-OVERSEAS-001', 'OFR_HWLS_Applicant.AppDate': '2026-10-19',
|
||||
'OFR_HWLS_BInfo.CustomerName': '演示客户', 'OFR_HWLS_BInfo.TotalAmount': 0,
|
||||
'OFR_HWLS_Applicant.ChangeReason': '演示更改原因', 'OFR_HWLS_Applicant.OrderChangeContent': '演示更改内容',
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = { seedRules, adapters };
|
||||
@@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
|
||||
function sameWindow(batch,cutoff,window){
|
||||
return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false;
|
||||
}
|
||||
|
||||
function freeze(value){
|
||||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||||
return value;
|
||||
}
|
||||
|
||||
class OrderRuleDispatcher{
|
||||
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false}){
|
||||
this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
|
||||
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
|
||||
}
|
||||
ready(){
|
||||
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
|
||||
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
|
||||
}
|
||||
tick(now=this.clock()){
|
||||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||||
const task=this.perform(new Date(now));this.running=task;
|
||||
task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});
|
||||
return task;
|
||||
}
|
||||
async perform(now){
|
||||
if(!this.ready())return;
|
||||
const config=freeze(structuredClone(this.store.settings()));
|
||||
const schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||
if(!schedule?.times?.length)return;
|
||||
const signature=JSON.stringify([schedule,calendar]);
|
||||
if(!this.schedule||this.schedule.signature!==signature){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
|
||||
if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return;
|
||||
const cutoff=this.schedule.next;
|
||||
if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
|
||||
if(!this.ready())return;
|
||||
try{
|
||||
await this.mail.exclusive(config.channelId,async()=>{
|
||||
if(!this.ready())return;
|
||||
// A busy mailbox cannot consume the slot or reserve any orders. Recovery
|
||||
// applies only to this exact business window, never to earlier history.
|
||||
const window=windowForCutoff(cutoff,schedule,calendar);
|
||||
const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window));
|
||||
const batches=[...new Map([...existing,...fresh].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()];
|
||||
let interrupted=false;
|
||||
for(const batch of batches){
|
||||
if(!this.ready()){interrupted=true;break;}
|
||||
if(batch.status!=='prepared')continue;
|
||||
await this.dispatch(batch,config);
|
||||
}
|
||||
if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};
|
||||
});
|
||||
}catch(error){if(error.status!==409)throw error;}
|
||||
}
|
||||
async attachments(batch,config){
|
||||
const result=[];let total=0;
|
||||
for(const file of batch.attachments||[]){
|
||||
if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。');
|
||||
total+=file.size;
|
||||
if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。');
|
||||
const stat=await fs.stat(file.path);
|
||||
if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');
|
||||
const content=await fs.readFile(file.path);
|
||||
if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。');
|
||||
result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async dispatch(batch,config){
|
||||
let transport,sending=false;
|
||||
try{
|
||||
if(batch.channelId&&batch.channelId!==config.channelId){
|
||||
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
|
||||
}
|
||||
const attachments=await this.attachments(batch,config);
|
||||
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
|
||||
const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
|
||||
if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
|
||||
transport=this.mail.smtpFactory(channel.smtp);
|
||||
this.mail.clients?.add(transport);
|
||||
await transport.verify();
|
||||
if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
|
||||
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
|
||||
this.mail.store.guard(channel.id,channel.version);
|
||||
this.store.beginSending(batch.id);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 accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
|
||||
const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
||||
}catch(error){
|
||||
this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
|
||||
}finally{
|
||||
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
|
||||
}
|
||||
}
|
||||
start(){
|
||||
if(this.timer||this.stopped)return;
|
||||
this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
|
||||
}
|
||||
async stop(){
|
||||
this.stopped=true;clearInterval(this.timer);this.timer=null;
|
||||
if(this.running)await this.running.catch(()=>{});
|
||||
}
|
||||
}
|
||||
module.exports={OrderRuleDispatcher};
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
const {extractTitle}=require('./title.cjs');
|
||||
|
||||
const labels = {
|
||||
orderNo: '订单号', appDate: '申请日期', customer: '客户', productLine: '产品线',
|
||||
quantity: '数量', brief: '摘要', changeReason: '更改原因', changeContent: '更改内容', totalAmount: '总金额',
|
||||
};
|
||||
const present = value => value !== undefined && value !== null && (typeof value !== 'string' || value.trim() !== '');
|
||||
const scalar = value => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
|
||||
const nonblank = value => typeof value === 'string' && value.trim().length > 0;
|
||||
function validAppDate(value){
|
||||
if(!nonblank(value)||!/^\d{4}-\d{2}-\d{2}(?:$|[ T])/.test(value))return false;
|
||||
const day=value.slice(0,10),date=new Date(day+'T00:00:00Z');
|
||||
if(!Number.isFinite(+date)||date.toISOString().slice(0,10)!==day)return false;
|
||||
return value.length===10||Number.isFinite(Date.parse(value.replace(' ','T')));
|
||||
}
|
||||
|
||||
function previewMatch(rules, adapters, input) {
|
||||
const sample = input && typeof input === 'object' ? input : {};
|
||||
const checks = [], issues = [];
|
||||
const check = (label, ok, detail) => {
|
||||
checks.push({ label, ok: !!ok, detail });
|
||||
if (!ok) issues.push(detail);
|
||||
};
|
||||
for (const key of ['connectionId', 'instanceId', 'taskId']) {
|
||||
check('事件身份', scalar(sample[key]) && present(sample[key]), `${key}:${present(sample[key]) ? String(sample[key]) : '缺失'}`);
|
||||
}
|
||||
check('事件来源', sample.source === 'todo', 'source 必须为 todo(待办)');
|
||||
check('事件修订', scalar(sample.revision) && present(sample.revision), `revision:${present(sample.revision) ? String(sample.revision) : '缺失'}`);
|
||||
check('接收时间', nonblank(sample.receivedAt) && /T.*(?:Z|[+-]\d{2}:\d{2})$/.test(sample.receivedAt) && Number.isFinite(Date.parse(sample.receivedAt)), 'receivedAt 必须是带时区的有效时间');
|
||||
for (const key of ['processName', 'processVersion', 'nodeName']) {
|
||||
check('流程信息', nonblank(sample[key]), `${key}:${nonblank(sample[key]) ? sample[key] : '缺失'}`);
|
||||
}
|
||||
const matches = (Array.isArray(rules) ? rules : []).filter(rule =>
|
||||
Array.isArray(rule.processNames) && rule.processNames.includes(sample.processName)
|
||||
&& Array.isArray(rule.nodeNames) && rule.nodeNames.includes(sample.nodeName));
|
||||
check('分类命中', matches.length === 1, matches.length === 1 ? `唯一命中:${matches[0].name}` : matches.length ? `同时命中 ${matches.length} 条规则,须消除冲突` : '没有流程名称和节点名称均精确匹配的规则');
|
||||
const rule = matches.length === 1 ? matches[0] : null;
|
||||
const available = rule ? (Array.isArray(adapters) ? adapters : []).filter(adapter =>
|
||||
rule.adapterIds?.includes(adapter.id) && adapter.processName === sample.processName
|
||||
&& adapter.processVersion === sample.processVersion && adapter.verified === true) : [];
|
||||
const adapter = available.length === 1 ? available[0] : null;
|
||||
check('字段适配', available.length === 1, adapter ? `字段适配 ${adapter.id}:仅表单结构已核对,不代表实时接口可用` : '没有唯一、已核对且流程版本一致的字段适配器');
|
||||
|
||||
const raw = sample.fields && typeof sample.fields === 'object' && !Array.isArray(sample.fields) ? sample.fields : {};
|
||||
const event = {};
|
||||
for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'processName', 'processVersion', 'nodeName', 'receivedAt', 'serialNum', 'demo']) {
|
||||
if (Object.hasOwn(sample, key)) event[key] = sample[key];
|
||||
}
|
||||
event.documentNum = sample.serialNum ?? '';
|
||||
event.ruleId = rule?.id ?? null;
|
||||
event.ruleVersion = rule?.version ?? null;
|
||||
event.categoryId = rule?.categoryId ?? null;
|
||||
event.adapterId = adapter?.id ?? null;
|
||||
const fieldTrace = [];
|
||||
const mappings = adapter?.fields ?? {};
|
||||
const titleSource=Object.hasOwn(sample,'title')?'title':typeof sample.brief==='string'&&/订单号\s*[::]/u.test(sample.brief)?'brief':null;
|
||||
const extracted=titleSource?extractTitle(sample[titleSource]):null;
|
||||
if(extracted){
|
||||
event.rawTitle=extracted.rawTitle;event.titleOrders=extracted.orders;event.factoryHints=extracted.factoryHints;
|
||||
check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州线索仅供核实,不触发额外发送`);
|
||||
}
|
||||
for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), 'brief'])) {
|
||||
const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:'brief' : mappings[key] || '';
|
||||
const value = key === 'brief' ? extracted?extracted.brief:sample.brief : path && Object.hasOwn(raw, path) ? raw[path] : null;
|
||||
event[key] = value ?? null;
|
||||
fieldTrace.push({ key, label: labels[key] || key, path, value: value ?? null });
|
||||
}
|
||||
for (const key of ['orderNo', 'brief']) {
|
||||
check(labels[key], nonblank(event[key]), `${key} ${nonblank(event[key]) ? '已取得' : '缺失或不是文本'}`);
|
||||
}
|
||||
check('流水编号',nonblank(sample.serialNum),'流水编号 serialNum 必须有值,用于文件命名和追溯');
|
||||
if(rule?.filenameDate==='appDate')check('申请日期',validAppDate(event.appDate),'文件名使用申请日期,样本必须包含有效的申请日期');
|
||||
if (present(event.quantity)) {
|
||||
const numeric = typeof event.quantity === 'number' ? event.quantity : typeof event.quantity === 'string' && event.quantity.trim() ? Number(event.quantity) : NaN;
|
||||
check('数量', Number.isFinite(numeric) && numeric >= 0, 'quantity 必须为非负数,零数量合法');
|
||||
if (Number.isFinite(numeric)) event.quantity = numeric;
|
||||
} else check('数量', true, 'quantity 未提供;不猜测未核对的数量字段');
|
||||
|
||||
return {
|
||||
valid: issues.length === 0, ruleId: rule?.id ?? null, categoryId: rule?.categoryId ?? null,
|
||||
event, checks, issues, fieldTrace, candidates: matches.map(item => item.id),
|
||||
explanation: rule ? describeRule(rule) : '按照流程名称和通知节点精确分类;未命中或多条命中时阻塞。',
|
||||
};
|
||||
}
|
||||
|
||||
function describeRule(rule) {
|
||||
const date = { appDate: '申请日期', receivedAt: '接收日期', archiveDate: '归档日期' }[rule.filenameDate] || '待选择的日期';
|
||||
return `${rule.name}:流程“${(rule.processNames || []).join('、')}”到达节点“${(rule.nodeNames || []).join('、')}”时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。正常工作日首封只取当天零点到首个时点,第二封取两个时点之间;周一首封从上个工作日最后时点起算。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`;
|
||||
}
|
||||
|
||||
module.exports = { previewMatch, describeRule };
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
// Actions describe completed, evidence-backed steps; callers must never accept a
|
||||
// target state from an HTTP request as authority to bypass these transitions.
|
||||
const transitions={
|
||||
order:{
|
||||
identified:{prepare:'preparing',block:'blocked'},
|
||||
preparing:{archive:'archived',block:'blocked'},
|
||||
archived:{queue:'pending',block:'blocked'},
|
||||
pending:{batch:'batched',block:'blocked'},
|
||||
batched:{sent:'sent',unknown:'unknown',block:'blocked',retry:'pending'},
|
||||
blocked:{retry:'preparing'},
|
||||
unknown:{resolve_sent:'sent',retry:'pending'},
|
||||
sent:{}
|
||||
},
|
||||
batch:{
|
||||
prepared:{send:'sending',fail:'failed',cancel:'cancelled'},
|
||||
sending:{sent:'sent',unknown:'unknown'},
|
||||
unknown:{resolve_sent:'sent',retry:'cancelled'},
|
||||
failed:{},sent:{},cancelled:{}
|
||||
}
|
||||
};
|
||||
function transition(kind,from,action){
|
||||
const group=Object.hasOwn(transitions,kind)?transitions[kind]:null;
|
||||
const actions=group&&Object.hasOwn(group,from)?group[from]:null;
|
||||
if(!actions||!Object.hasOwn(actions,action))throw Object.assign(new Error(`不允许的状态操作:${kind}/${from}/${action}`),{status:409,statusCode:409});
|
||||
return actions[action];
|
||||
}
|
||||
module.exports={transition};
|
||||
@@ -0,0 +1,193 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');
|
||||
const {seedRules,adapters}=require('./catalog.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
|
||||
const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
|
||||
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
|
||||
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.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 digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
||||
const copy=value=>structuredClone(value);
|
||||
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
|
||||
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
|
||||
class RuleStore{
|
||||
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[]}={}){
|
||||
this.clock=clock;this.schedule=schedule;this.calendar=calendar;this.capabilities={...BASE_CAPABILITIES,...capabilities};
|
||||
try{
|
||||
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
|
||||
this.db=new DatabaseSync(path.join(dir,'rules.sqlite'));
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS records(kind TEXT NOT NULL,id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(kind,id));`);
|
||||
this.transaction(()=>{
|
||||
if(!this.get('settings','main'))this.put('settings',{id:'main',version:1,enabled:false,channelId:'',maxMessageBytes:20971520});
|
||||
for(const rule of seedRules())if(!this.get('rules',rule.id)){
|
||||
const override=seedOverrides.find(r=>r.id===rule.id);
|
||||
const draft=override?validateRule({...rule,...override},rule):rule;
|
||||
this.put('rules',{id:rule.id,draft:{...draft,status:'draft'},published:null,trialVersion:null,trialDemo:null});
|
||||
}
|
||||
for(const batch of this.all('batches')){
|
||||
if(batch.status==='sending'){
|
||||
batch.status='unknown';batch.error='服务重启,发信结果待人工核实。';this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,'unknown',batch.error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
|
||||
}
|
||||
now(){return this.clock().toISOString();}
|
||||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
|
||||
get(kind,id){const row=this.db.prepare('SELECT payload FROM records WHERE kind=? AND id=?').get(kind,id);return row?this.vault.decode(kind+':'+id,row.payload):null;}
|
||||
all(kind){return this.db.prepare('SELECT id,payload FROM records WHERE kind=? ORDER BY rowid').all(kind).map(r=>this.vault.decode(kind+':'+r.id,r.payload));}
|
||||
put(kind,value){this.db.prepare('INSERT INTO records VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET payload=excluded.payload').run(kind,value.id,this.vault.encode(kind+':'+value.id,value));return value;}
|
||||
audit(actor,action,detail){this.put('audit',{id:crypto.randomUUID(),at:this.now(),actor:String(actor||'系统'),action,detail});}
|
||||
settings(){const {id,...settings}=this.get('settings','main');return settings;}
|
||||
saveSettings(input,actor){return this.transaction(()=>{
|
||||
const old=this.settings();
|
||||
if(!input||Object.keys(input).some(k=>!['version','enabled','channelId','maxMessageBytes'].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(input.enabled&&(!Object.values(this.capabilities).every(Boolean)||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
|
||||
this.put('settings',{...input,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
|
||||
});}
|
||||
snapshot(){
|
||||
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
|
||||
return {rules,adapters:copy(adapters),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
|
||||
}
|
||||
saveRule(input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404);
|
||||
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.draft),at:this.now(),actor});
|
||||
record.draft=validateRule(input,record.draft);record.trialVersion=null;record.trialDemo=null;this.put('rules',record);
|
||||
this.audit(actor,'保存规则草稿',record.id+' v'+record.draft.version);return {...record.draft,explanation:describeRule(record.draft)};
|
||||
});}
|
||||
preview(sample){
|
||||
const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),adapters,sample);
|
||||
if(result.valid&&result.ruleId){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
|
||||
return result;
|
||||
}
|
||||
publish(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
|
||||
const issues=publicationIssues(record.draft,adapters);
|
||||
if(record.trialVersion!==record.draft.version)issues.push('请先用真实结构样本试运行当前草稿');
|
||||
if(record.trialDemo!==false)issues.push('演示样本仅用于理解字段,发布前请校验真实业务样本');
|
||||
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&r.published.processNames.some(p=>record.draft.processNames.includes(p))&&r.published.nodeNames.some(n=>record.draft.nodeNames.includes(n)));
|
||||
if(overlaps.length)issues.push('与已启用规则存在流程和节点冲突:'+overlaps.map(r=>r.draft.name).join('、'));
|
||||
if(issues.length)fail(issues.join(';'),409);
|
||||
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};this.put('rules',record);
|
||||
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
|
||||
return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
pause(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
|
||||
if(record.published)record.published.status='paused';this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
matchingPublications(sample){
|
||||
const rules=this.all('rules').filter(r=>r.published).map(r=>r.published);
|
||||
const enabled=rules.filter(r=>r.status==='enabled');
|
||||
const hasEnabledMatch=enabled.some(r=>r.processNames.includes(sample.processName)&&r.nodeNames.includes(sample.nodeName));
|
||||
return hasEnabledMatch?enabled:rules;
|
||||
}
|
||||
ingest(sample,actor){return this.transaction(()=>{
|
||||
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
|
||||
if(!sample||['connectionId','source','instanceId','taskId','revision'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250))fail('缺少来源、流程实例、任务及业务修订标识。');
|
||||
sample=copy(sample);for(const key of ['connectionId','source','instanceId','taskId','revision'])sample[key]=String(sample[key]).trim();
|
||||
const id=digest(['BPM',sample.connectionId,sample.source,sample.instanceId,sample.taskId,sample.revision]);
|
||||
const sourceHash=digest(sample),old=this.get('orders',id);
|
||||
if(old){if(old.sourceHash!==sourceHash)fail('相同任务和业务修订的内容已变化,请核实来源版本。',409);return old;}
|
||||
const active=this.matchingPublications(sample);
|
||||
const result=previewMatch(active,adapters,sample),rule=active.find(r=>r.id===result.ruleId);
|
||||
const ready=Object.values(this.capabilities).every(Boolean),enabled=rule?.status==='enabled';
|
||||
const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt)<Date.parse(window.start)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
|
||||
this.put('orders',order);this.audit(actor,'识别订单任务',id);return order;
|
||||
});}
|
||||
recordArchive(id,evidence,actor){return this.transaction(()=>{
|
||||
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
|
||||
const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
|
||||
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&Date.parse(order.event.receivedAt)<Date.parse(window.start))fail('该订单已超出当前时段,不再自动归档或补发。',409);
|
||||
if(!evidence||!validDate(evidence.archivedAt)||!Array.isArray(evidence.files)||!evidence.files.length||evidence.files.some(f=>!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
|
||||
if(order.status==='identified')order.status=transition('order',order.status,'prepare');
|
||||
order.status=transition('order',order.status,'archive');order.archive=copy(evidence);
|
||||
if(order.ruleSnapshot.attachPdf&&!evidence.files.some(f=>f.kind==='pdf')){order.status='blocked';order.error='缺少本类别要求的电子流 PDF。';}
|
||||
else {order.status=transition('order',order.status,'queue');order.error=null;}
|
||||
order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'记录执行器归档结果',id);return order;
|
||||
});}
|
||||
retryArchive(id,note,actor){return this.transaction(()=>{
|
||||
if(typeof note!=='string'||note.trim().length<5||note.length>2000)fail('请填写至少5字修复依据。');
|
||||
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
|
||||
const order=this.get('orders',id);if(!order||!order.ruleSnapshot||order.status!=='blocked')fail('当前任务不能重试归档。',409);
|
||||
order.status=transition('order',order.status,'retry');order.error=null;order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'重试归档',id+':'+note.trim());return order;
|
||||
});}
|
||||
recheck(id,input,actor){return this.transaction(()=>{
|
||||
if(typeof input?.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字的重新识别依据。');
|
||||
const order=this.get('orders',id);
|
||||
if(!order||order.batchId||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
|
||||
const published=this.matchingPublications(order.sample);
|
||||
const result=previewMatch(published,adapters,order.sample),rule=published.find(r=>r.id===result.ruleId);
|
||||
if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
|
||||
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
|
||||
order.archive=null;order.status=Object.values(this.capabilities).every(Boolean)?'identified':'blocked';
|
||||
order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
|
||||
this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
|
||||
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
|
||||
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
|
||||
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
|
||||
for(const batch of this.all('batches'))if(batch.status==='prepared'&&Date.parse(batch.cutoff)<Date.parse(cutoff)){
|
||||
batch.status=transition('batch',batch.status,'cancel');batch.error='已错过原发送时段,历史订单不补发。';this.put('batches',batch);this.updateBatchOrders(batch,'ignored',batch.error);
|
||||
}
|
||||
const grouped=new Map(),batches=[];
|
||||
for(const order of this.all('orders')){
|
||||
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId)continue;
|
||||
const at=order.event.receivedAt||order.sample.receivedAt;
|
||||
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)){order.status='ignored';order.error='早于本时段的历史订单,不补发。';this.put('orders',order);continue;}
|
||||
if(!inWindow(at,window))continue;
|
||||
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
|
||||
}
|
||||
for(const orders of grouped.values()){
|
||||
const rule=orders[0].ruleSnapshot;if(!rule)continue;
|
||||
if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!['failed','cancelled'].includes(b.status)))continue;
|
||||
const published=this.get('rules',rule.id)?.published;
|
||||
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
|
||||
if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
|
||||
let snapshot;
|
||||
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});}catch(cause){error=cause.message;}
|
||||
if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;}
|
||||
const batch={...snapshot,id:crypto.randomUUID(),status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
|
||||
this.put('batches',batch);
|
||||
for(const order of orders){order.status=transition('order',order.status,'batch');order.batchId=batch.id;order.error=null;order.updatedAt=this.now();this.put('orders',order);}
|
||||
this.audit(actor,'固定分类邮件批次',batch.id+' '+orders.length+'单');batches.push(batch);
|
||||
}
|
||||
return batches;
|
||||
});}
|
||||
updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}}
|
||||
beginSending(id){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
|
||||
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
|
||||
if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
|
||||
batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
|
||||
});}
|
||||
finishSending(id,status,message=null){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
|
||||
batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,status==='failed'?'pending':status,message);
|
||||
if(status==='failed')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}}
|
||||
this.audit('系统发送','更新批次结果',id+' '+status);return batch;
|
||||
});}
|
||||
resolve(id,input,actor){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
|
||||
batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
|
||||
if(input.resolution==='retry')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}}
|
||||
this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
|
||||
});}
|
||||
close(){this.db.close();this.vault.destroy();}
|
||||
}
|
||||
module.exports={RuleStore};
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
|
||||
// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
|
||||
const retained=new Set(['订单号','机芯号','产品型号','客户简称','总数量','订单类别']);
|
||||
function extractTitle(title){
|
||||
const raw=typeof title==='string'?title:'';
|
||||
const text=raw.replace(/<br\s*\/?\s*>/gi,'\n').replace(/ | | /gi,' ');
|
||||
const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
|
||||
const orders=[],factoryHints=[],issues=[];let current=null;
|
||||
for(let i=0;i<matches.length;i++){
|
||||
const match=matches[i],label=match[1],value=text.slice(match.index+match[0].length,matches[i+1]?.index??text.length).trim();
|
||||
if(['业务模式','客户简称'].includes(label)&&value.includes('惠州'))factoryHints.push({source:label,value,status:'待核实额外通知'});
|
||||
if(label==='订单号'){
|
||||
current={orderNo:value,text:''};orders.push(current);
|
||||
if(!value)issues.push('标题中的订单号为空,不能遗漏该订单段落');
|
||||
}
|
||||
if(current&&retained.has(label))current.text+=`${label}:${value}`;
|
||||
}
|
||||
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
|
||||
return {rawTitle:raw,orders,brief:orders.map(order=>order.text).join('\n'),factoryHints,issues};
|
||||
}
|
||||
module.exports={extractTitle};
|
||||
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
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'];
|
||||
function addresses(values){
|
||||
if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
|
||||
return [...new Set(values.map(v=>{
|
||||
if(typeof v!=='string'||v.length>254||! /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(v.trim()))fail('请检查邮箱地址:'+String(v).slice(0,80));
|
||||
return v.trim().toLowerCase();
|
||||
}))];
|
||||
}
|
||||
function validateRule(input,old){
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))fail('规则格式无效。');
|
||||
if(!old||input.id!==old.id||input.categoryId!==old.categoryId)fail('规则类别标识不能修改。');
|
||||
if(input.version!==old.version)fail('规则已被其他人修改,请刷新后重试。',409);
|
||||
const rule=Object.fromEntries(fields.map(k=>[k,input[k]??old[k]]));
|
||||
for(const key of ['name','subjectPrefix','archiveDirectory','intro','signature']){
|
||||
if(typeof rule[key]!=='string'||rule[key].length>(['intro','signature'].includes(key)?4000:1200)||(/[\x00]/.test(rule[key])))fail('规则文本格式无效。');
|
||||
rule[key]=rule[key].trim();
|
||||
}
|
||||
if(!rule.name||/[\r\n]/.test(rule.subjectPrefix)||/[\x00-\x1f]/.test(rule.archiveDirectory))fail('请填写规则名称,主题和目录不能换行。');
|
||||
for(const key of ['processNames','nodeNames','adapterIds']){
|
||||
if(!Array.isArray(rule[key])||rule[key].length>100||rule[key].some(v=>typeof v!=='string'||!v.trim()||v.length>250||/[\x00-\x1f]/.test(v)))fail('流程、节点或字段适配配置无效。');
|
||||
rule[key]=[...new Set(rule[key].map(v=>v.trim()))];
|
||||
}
|
||||
if(!['','appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||typeof rule.attachPdf!=='boolean')fail('请选择有效的日期来源和附件要求。');
|
||||
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;
|
||||
}
|
||||
function publicationIssues(rule,adapters){
|
||||
const issues=[];
|
||||
if(!rule.processNames.length||!rule.nodeNames.length)issues.push('请选择适用流程和到达节点');
|
||||
if(!rule.subjectPrefix)issues.push('请填写邮件主题前缀');
|
||||
if(!rule.archiveDirectory||!/^\\\\[^\\]+\\[^\\]+/.test(rule.archiveDirectory)||/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(rule.archiveDirectory))issues.push('请选择完整服务器共享归档目录');
|
||||
if(!rule.filenameDate)issues.push('请选择文件名日期来源');
|
||||
if(!rule.to.length)issues.push('请配置收件人');
|
||||
for(const process of rule.processNames){
|
||||
if(!adapters.some(a=>a.verified&&a.processName===process&&rule.adapterIds.includes(a.id)))issues.push('流程字段适配待核验:'+process);
|
||||
}
|
||||
if(rule.adapterIds.some(id=>!adapters.some(a=>a.id===id)))issues.push('包含不存在的字段适配器');
|
||||
return issues;
|
||||
}
|
||||
module.exports={fail,validateRule,publicationIssues};
|
||||
@@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
|
||||
const invalid=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
const DAY=86400000,OFFSET=8*3600000;
|
||||
const dayOf=date=>new Date(+date+OFFSET).toISOString().slice(0,10);
|
||||
const at=(day,time)=>new Date(day+'T'+time+':00+08:00').toISOString();
|
||||
function timesOf(schedule){
|
||||
if(!Array.isArray(schedule?.times)||schedule.times.length!==2||schedule.times.some(t=>typeof t!=='string'||! /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(t))||schedule.times[0]===schedule.times[1])invalid('请配置两个不同的发送时间。');
|
||||
return [...schedule.times].sort();
|
||||
}
|
||||
function windowForCutoff(cutoff,schedule,overrides=[]){
|
||||
if(typeof cutoff!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(cutoff)||!Number.isFinite(Date.parse(cutoff)))invalid('发送截止时间必须包含时区。');
|
||||
const date=new Date(cutoff),day=dayOf(date),times=timesOf(schedule),end=date.toISOString();
|
||||
if(!dayPolicy(day,schedule,overrides).send)invalid('该日期未安排发送。');
|
||||
const index=times.findIndex(time=>at(day,time)===end);if(index<0)invalid('截止时间必须与已配置的发送时点一致。');
|
||||
let start=index?at(day,times[index-1]):at(day,'00:00');
|
||||
if(index===0){
|
||||
const prior=dayOf(new Date(+date-DAY));
|
||||
const monday=new Date(day+'T00:00:00Z').getUTCDay()===1;
|
||||
if(monday||!dayPolicy(prior,schedule,overrides).send){
|
||||
let found=false;
|
||||
for(let back=1;back<=370;back++){
|
||||
const previous=dayOf(new Date(+date-back*DAY));
|
||||
if(dayPolicy(previous,schedule,overrides).send){start=at(previous,times.at(-1));found=true;break;}
|
||||
}
|
||||
if(!found)invalid('找不到上个工作日的发送截止时间,请检查业务日历。');
|
||||
}
|
||||
}
|
||||
const fmt=value=>new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date(value));
|
||||
return {start,end,label:fmt(start)+' 至 '+fmt(end)+'(北京时间,含起点、不含终点)',startInclusive:true,endInclusive:false};
|
||||
}
|
||||
function upcomingWindow(now,schedule,overrides=[]){
|
||||
const times=timesOf(schedule),day=dayOf(now);
|
||||
const due=times.map(t=>at(day,t)).find(t=>+now-Date.parse(t)>=0&&+now-Date.parse(t)<=60000);
|
||||
const cutoff=due&&dayPolicy(day,schedule,overrides).send?due:nextSlots(schedule,now,1,overrides)[0];
|
||||
if(!cutoff)return null;
|
||||
return {...windowForCutoff(cutoff,schedule,overrides),available:Boolean(due&&cutoff===due)};
|
||||
}
|
||||
function inWindow(receivedAt,window){const value=Date.parse(receivedAt);return Number.isFinite(value)&&value>=Date.parse(window.start)&&value<Date.parse(window.end);}
|
||||
module.exports={windowForCutoff,upcomingWindow,inWindow};
|
||||
@@ -33,3 +33,15 @@ test('isolated preview signs in locally with fictional workspace data and surviv
|
||||
runtime=await startPreview({stateDir:dir,port:0});
|
||||
assert.deepEqual(runtime.workspace.snapshot(runtime.store.users()).exceptions.map(item=>item.id),ids);
|
||||
});
|
||||
|
||||
test('rule preview can configure IMAP history without enabling polling or SMTP',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-preview-'));
|
||||
const runtime=await startPreview({stateDir:dir,port:0,mailHistory:true});
|
||||
t.after(async()=>{await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+runtime.server.address().port;
|
||||
const login=await fetch(base+'/api/preview-login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:'{}'});
|
||||
const cookie=login.headers.get('set-cookie').split(';')[0];
|
||||
const result=await fetch(base+'/api/mail',{headers:{Cookie:cookie}});
|
||||
assert.equal(result.status,200);assert.equal((await result.json()).historyOnly,true);
|
||||
assert.equal(runtime.mail.timer,undefined);assert.equal(runtime.mail.startTimer,undefined);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {startPreview}=require('../../scripts/preview.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
test('history UI saves IMAP-only credentials locally, explicitly queries sent mail and displays escaped evidence',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-ui-'));const runtime=await startPreview({stateDir:dir,port:0,mailHistory:true});let browser;
|
||||
t.after(async()=>{await browser?.close();await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
let connects=0;
|
||||
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nSubject: Test notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n<img src="https://tracker.example.test/pixel"> Huizhou evidence');
|
||||
runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
|
||||
browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();const requests=[];page.on('request',r=>requests.push(r.url()));
|
||||
await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#mail');await page.getByRole('button',{name:'进入演示空间',exact:true}).click();
|
||||
await page.getByRole('button',{name:'添加只读邮箱',exact:true}).click({timeout:5000});
|
||||
for(const [label,value]of [['邮箱名称','历史核对'],['邮箱地址','orders@example.test'],['IMAP 服务器','imap.example.test'],['IMAP 登录账号','orders@example.test'],['IMAP 授权码','History-123']])await page.getByLabel(label,{exact:true}).fill(value);
|
||||
await page.getByRole('button',{name:'保存只读邮箱',exact:true}).click();await page.getByText('只读邮箱已保存。',{exact:true}).waitFor();assert.equal(connects,0);
|
||||
await page.getByRole('button',{name:'连接并列出已发送文件夹',exact:true}).click();await page.getByLabel('已发送文件夹',{exact:true}).selectOption('Sent');
|
||||
await page.getByRole('button',{name:'查询已发送邮件',exact:true}).click();await page.getByRole('button',{name:'查看邮件',exact:true}).click();
|
||||
await page.getByText('<img src="https://tracker.example.test/pixel"> Huizhou evidence',{exact:true}).waitFor();
|
||||
assert.equal(requests.some(r=>r.startsWith('https://tracker.example.test')),false);assert.equal(await page.getByRole('button',{name:/发送测试/}).count(),0);
|
||||
assert.equal(runtime.mail.store.channels()[0].smtp.hasPassword,false);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');
|
||||
const {MailService}=require('../../src/modules/mail/service.cjs');
|
||||
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||||
const {MailStore}=require('../../src/modules/mail/store.cjs');
|
||||
const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: <notice@example.test>\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body');
|
||||
function fixture(){
|
||||
const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}};
|
||||
const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}};
|
||||
const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}});
|
||||
return {service,calls,client};
|
||||
}
|
||||
test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir);
|
||||
const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}});
|
||||
t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const account=store.saveChannel({readOnly:true,name:'历史格式核对',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders@example.test',password:'History-only-123'}});
|
||||
assert.equal(account.readOnly,true);assert.equal(account.enabled,false);assert.equal(account.smtp.hasPassword,false);
|
||||
assert.doesNotMatch(JSON.stringify(store.channels()),/History-only-123/);
|
||||
for(const work of [()=>service.verify(account.id),()=>service.poll(account.id),()=>service.sendTest(account.id,'any')])await assert.rejects(work(),e=>e.status===409&&e.message.includes('只读'));
|
||||
});
|
||||
test('sent history is bounded, read-only, does not download bodies during search, and keeps mailbox cursor untouched',async()=>{
|
||||
const {service,calls}=fixture();
|
||||
const result=await service.history('channel',{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-20',subject:'订单',limit:2});
|
||||
assert.equal(result.messages.length,2);assert.equal(result.truncated,true);assert.deepEqual(result.messages.map(m=>m.uid),[3,2]);
|
||||
assert.ok(calls.some(c=>c.folder==='Sent'&&c.readOnly===true));
|
||||
assert.ok(calls.some(c=>c.query?.sentSince instanceof Date&&c.query.subject==='订单'));
|
||||
assert.ok(!calls.some(c=>c.query?.source));
|
||||
const detail=await service.history('channel',{action:'message',folder:'Sent',uid:3,uidValidity:result.uidValidity});
|
||||
assert.equal(detail.text,'Order body');assert.equal(detail.to[0].address,'orders@example.test');assert.equal(detail.cc[0].address,'factory@example.test');
|
||||
assert.deepEqual(detail.attachments,[]);
|
||||
});
|
||||
test('history rejects wrong folder, stale UID epoch, oversized messages and unbounded dates without leaking provider errors',async()=>{
|
||||
const {service,client}=fixture();
|
||||
for(const input of [{action:'search',folder:'INBOX',since:'2026-10-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2020-01-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2026-02-31',before:'2026-03-05'}])await assert.rejects(service.history('c',input),e=>e.status===400);
|
||||
await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'8'}),e=>e.status===409);
|
||||
client.fetchOne=async()=>({size:20*1024*1024});
|
||||
await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'9'}),e=>e.status===413);
|
||||
client.connect=async()=>{throw Error('secret password');};
|
||||
await assert.rejects(service.history('c',{action:'folders'}),e=>!e.message.includes('secret password'));
|
||||
});
|
||||
@@ -13,3 +13,18 @@ test('template preview is isolated, source attachments downloadable and confirma
|
||||
assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},reader)).status,403);assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},admin)).status,200);assert.equal(mailStore.active(c.id,'').id,d.id);
|
||||
assert.equal((await call('/api/mail/templates/'+d.id+'/source',undefined,reader)).status,403);const source=await call('/api/mail/templates/'+d.id+'/source',undefined,admin);assert.equal(await source.text(),raw.toString());
|
||||
});
|
||||
|
||||
test('history access requires administrator and same origin; isolated history mode rejects SMTP and polling routes',async t=>{
|
||||
const {mail,mailStore,call,login}=await setup(t);mail.historyOnly=true;
|
||||
const admin=await login('admin'),reader=await login('reader');
|
||||
const saved=await call('/api/mail/channels',{readOnly:true,name:'历史核对',email:'orders@example.test',imap:config.imap},admin);
|
||||
assert.equal(saved.status,201);const account=await saved.json();
|
||||
const url='/api/mail/channels/'+account.id;
|
||||
assert.equal((await call(url+'/history',{action:'folders'},reader)).status,403);
|
||||
assert.equal((await call(url+'/history',{action:'folders'},admin,'https://evil.test')).status,403);
|
||||
for(const action of ['verify','poll','test'])assert.equal((await call(url+'/'+action,{},admin)).status,409);
|
||||
assert.equal((await call('/api/mail/channels',config,admin)).status,409);
|
||||
assert.equal(mailStore.channels().length,1);
|
||||
mail.imapFactory=()=>({on(){},async connect(){},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async logout(){},close(){}});
|
||||
const folders=await call(url+'/history',{action:'folders'},admin);assert.equal(folders.status,200);assert.deepEqual((await folders.json()).folders,[{path:'Sent',name:'Sent'}]);
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
'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 crypto=require('node:crypto');
|
||||
const {transition}=require('../../src/modules/order-rules/state.cjs');
|
||||
const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
|
||||
|
||||
const cutoff='2026-10-19T01:00:00.000Z';
|
||||
function rule(patch={}){return {id:'r1',version:1,categoryId:'notice',name:'订单通知',subjectPrefix:'订单通知',intro:'请处理以下订单。',signature:'业务部',to:['USER@example.com','user@example.com'],cc:['copy@example.com','USER@example.com'],attachPdf:true,archiveDirectory:'\\\\nas\\orders',...patch};}
|
||||
function order(id='1',patch={}){return {id,event:{orderNo:`SO-${id}`,brief:'型号 <script>alert(1)</script>',receivedAt:'2026-10-19T00:00:00.000Z'},ruleSnapshot:rule(),archive:{archivedAt:'2026-10-19T00:30:00.000Z',files:[{name:`SO-${id}.pdf`,path:`\\\\nas\\orders\\SO-${id}.pdf`,sha256:'a'.repeat(64),size:100,kind:'pdf'}]},...patch};}
|
||||
|
||||
test('state actions enforce archive, pending and batch progression without skipping evidence stages',()=>{
|
||||
assert.equal(transition('order','identified','prepare'),'preparing');
|
||||
assert.equal(transition('order','preparing','archive'),'archived');
|
||||
assert.equal(transition('order','archived','queue'),'pending');
|
||||
assert.equal(transition('order','pending','batch'),'batched');
|
||||
assert.equal(transition('order','batched','sent'),'sent');
|
||||
assert.throws(()=>transition('order','identified','sent'),{status:409});
|
||||
assert.throws(()=>transition('order','blocked','sent'),{status:409});
|
||||
assert.throws(()=>transition('batch','failed','send'),{status:409});
|
||||
assert.throws(()=>transition('batch','unknown','send'),{status:409});
|
||||
assert.equal(transition('batch','prepared','send'),'sending');
|
||||
assert.equal(transition('batch','sending','unknown'),'unknown');
|
||||
assert.equal(transition('batch','unknown','resolve_sent'),'sent');
|
||||
assert.equal(transition('batch','unknown','retry'),'cancelled');
|
||||
});
|
||||
|
||||
test('batch includes every order above 200 with subject numbers and normalized independent recipients',()=>{
|
||||
const orders=Array.from({length:205},(_,i)=>order(String(i+1)));
|
||||
const batch=buildBatch(rule(),orders,cutoff);
|
||||
assert.equal(batch.orderIds.length,205);
|
||||
assert.equal(batch.attachments.length,205);
|
||||
assert.match(batch.subject,/SO-1/);assert.match(batch.subject,/SO-205/);
|
||||
assert.deepEqual(batch.to,['user@example.com']);assert.deepEqual(batch.cc,['copy@example.com']);
|
||||
assert.equal(batch.cutoff,cutoff);
|
||||
orders[0].archive.files[0].name='mutated';orders[0].event.orderNo='mutated';
|
||||
assert.equal(batch.attachments[0].name,'SO-1.pdf');assert.equal(batch.orderNos[0],'SO-1');
|
||||
});
|
||||
|
||||
test('mail keeps intro signature and escaped summaries with blue clickable UNC evidence',()=>{
|
||||
const batch=buildBatch(rule({intro:'<团队>',signature:'研发 & 业务'}),[order()],cutoff);
|
||||
assert.match(batch.text,/<团队>/);assert.match(batch.text,/研发 & 业务/);
|
||||
assert.match(batch.html,/<script>/);assert.doesNotMatch(batch.html,/<script>/);
|
||||
assert.match(batch.html,/href="file:\/\/nas\/orders\/SO-1.pdf"/);
|
||||
assert.match(batch.html,/color:\s*#(?:00f|0000ff)/i);
|
||||
assert.match(batch.html,/<团队>/);
|
||||
});
|
||||
|
||||
test('missing required PDF or archive evidence blocks the entire category',()=>{
|
||||
assert.throws(()=>buildBatch(rule(),[order(),order('2',{archive:null})],cutoff),/归档/);
|
||||
const onlyNotice=order('2');onlyNotice.archive.files[0].kind='notice';
|
||||
assert.throws(()=>buildBatch(rule(),[order(),onlyNotice],cutoff),/PDF/);
|
||||
const badEvidence=order('2');delete badEvidence.archive.files[0].sha256;
|
||||
assert.throws(()=>buildBatch(rule(),[badEvidence],cutoff),/证据/);
|
||||
});
|
||||
|
||||
test('mixed categories, rule versions, duplicate IDs and after-cutoff items are rejected instead of omitted',()=>{
|
||||
const other=order('2');other.ruleSnapshot.categoryId='change';
|
||||
assert.throws(()=>buildBatch(rule(),[order(),other],cutoff),/类别/);
|
||||
const revised=order('2');revised.ruleSnapshot.version=2;
|
||||
assert.throws(()=>buildBatch(rule(),[order(),revised],cutoff),/版本/);
|
||||
assert.throws(()=>buildBatch(rule(),[order(),order()],cutoff),/重复/);
|
||||
const later=order('2');later.event.receivedAt='2026-10-19T02:00:00.000Z';
|
||||
assert.throws(()=>buildBatch(rule(),[later],cutoff),/截止/);
|
||||
});
|
||||
|
||||
test('strict recipient parsing rejects header injections and malformed lists',()=>{
|
||||
for(const address of ['a@example.com\r\nBcc: intruder@example.com','Name <a@example.com>','a@@example.com','a@example.com,other@example.com','a@localhost','a..b@example.com']){
|
||||
assert.throws(()=>buildBatch(rule({to:[address]}),[order()],cutoff),/邮箱|收件/);
|
||||
}
|
||||
assert.throws(()=>buildBatch(rule({to:[]}),[order()],cutoff),/收件/);
|
||||
});
|
||||
|
||||
test('message size estimate includes base64 overhead and rejects oversize rather than truncating',()=>{
|
||||
const large=order();large.archive.files[0].size=15000;
|
||||
assert.throws(()=>buildBatch(rule(),[large],cutoff,{maxMessageBytes:20000}),/大小|容量/);
|
||||
});
|
||||
|
||||
test('an explicit batch window rejects historical orders and excludes its upper boundary',()=>{
|
||||
const window={start:'2026-10-19T00:00:00.000Z',end:cutoff,startInclusive:true,endInclusive:false};
|
||||
const old=order('old');old.event.receivedAt='2026-10-18T23:59:59.999Z';
|
||||
assert.throws(()=>buildBatch(rule(),[old,order()],cutoff,{window}),/时段|窗口/);
|
||||
const boundary=order('boundary');boundary.event.receivedAt=cutoff;
|
||||
assert.throws(()=>buildBatch(rule(),[boundary],cutoff,{window}),/时段|窗口/);
|
||||
const batch=buildBatch(rule(),[order(),order('2')],cutoff,{window});
|
||||
assert.deepEqual(batch.orderIds,['1','2']);assert.equal(batch.window.start,'2026-10-19T00:00:00.000Z');assert.equal(batch.window.end,cutoff);
|
||||
});
|
||||
|
||||
test('batch refuses inverted windows and windows that do not end at its cutoff',()=>{
|
||||
for(const window of [{start:cutoff,end:'2026-10-19T00:00:00.000Z'},{start:'2026-10-18T00:00:00.000Z',end:'2026-10-19T02:00:00.000Z'}]){
|
||||
assert.throws(()=>buildBatch(rule(),[order()],cutoff,{window}),/时段|窗口/);
|
||||
}
|
||||
});
|
||||
|
||||
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
|
||||
const dispatchCutoff='2026-10-20T01:00:00.000Z';
|
||||
const dispatchWindow={start:'2026-10-19T16:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false};
|
||||
function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,send,result}={}){
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-batch-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
|
||||
const content=Buffer.from('%PDF-1.7\ntrusted evidence');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);
|
||||
const batch={id:'batch1',status:'prepared',categoryId:'notice',subject:'已冻结 SO-1',text:'原正文',html:'<p>原正文</p>',to:['user@example.com'],cc:['copy@example.com'],attachments:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}],cutoff:dispatchCutoff,window:structuredClone(dispatchWindow)};
|
||||
const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]};
|
||||
const config={version:1,enabled,channelId:'channel1'};
|
||||
const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities};
|
||||
const store={settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T16:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}};
|
||||
const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['user@example.com','copy@example.com'],rejected:[]};},close:()=>{}};}};
|
||||
const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'};
|
||||
let now=new Date('2026-10-20T00:59:00.000Z');
|
||||
const dispatcher=new OrderRuleDispatcher({store,mail,settings:()=>({schedule}),calendar:()=>[],clock:()=>now,providersReady:()=>ready});
|
||||
return {dispatcher,store,mail,record,batch,config,caps,file,setNow:value=>{now=new Date(value);}};
|
||||
}
|
||||
async function due(f){await f.dispatcher.tick();f.setNow(dispatchCutoff);await f.dispatcher.tick();}
|
||||
|
||||
test('dispatcher never prepares or touches SMTP while disabled or any provider is unverified',async t=>{
|
||||
for(const input of [{enabled:false},{ready:false},{capabilities:false}]){
|
||||
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.prepared,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('dispatcher verifies recorded bytes and sends the frozen recipients and content once per schedule',async t=>{
|
||||
const f=dispatchFixture(t,{verify:({batch})=>{batch.subject='changed';batch.to=['intruder@example.com'];}});
|
||||
await due(f);await f.dispatcher.tick();
|
||||
assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,1);assert.equal(f.record.begun,1);assert.equal(f.record.locked,1);
|
||||
const sent=f.record.sent[0];assert.equal(sent.subject,'已冻结 SO-1');assert.deepEqual(sent.to,['user@example.com']);assert.deepEqual(sent.cc,['copy@example.com']);
|
||||
assert.equal(sent.attachments[0].content.toString(),'%PDF-1.7\ntrusted evidence');assert.equal(sent.disableFileAccess,true);assert.equal(sent.disableUrlAccess,true);assert.equal(sent.attachments[0].path,undefined);
|
||||
await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher attachment tampering fails before SMTP or sending transition',async t=>{
|
||||
const f=dispatchFixture(t);fs.writeFileSync(f.file,'changed bytes');await due(f);
|
||||
assert.equal(f.record.status,'failed');assert.equal(f.record.begun,0);assert.equal(f.record.smtp,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher maps pre-send verify failure to failed and post-begin errors or partial acceptance to unknown',async t=>{
|
||||
for(const [input,wanted,begun] of [[{verify:()=>{throw Error('verify failure');}},'failed',0],[{send:()=>{throw Error('socket dropped');}},'unknown',1],[{result:{accepted:['user@example.com'],rejected:['copy@example.com']}},'unknown',1]]){
|
||||
const f=dispatchFixture(t,input);await due(f);assert.equal(f.record.status,wanted);assert.equal(f.record.begun,begun);await f.dispatcher.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('dispatcher rechecks pause and provider gates after SMTP verification',async t=>{
|
||||
for(const change of [({config})=>{config.enabled=false;},({caps})=>{caps.pdfExport=false;}]){
|
||||
const f=dispatchFixture(t,{verify:change});await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('dispatcher uses business calendar to skip paused days and stop prevents further sends',async t=>{
|
||||
const f=dispatchFixture(t);f.dispatcher.calendar=()=>[{date:'2026-10-20',kind:'pause'}];await due(f);assert.equal(f.record.prepared,0);
|
||||
await f.dispatcher.stop();f.dispatcher.calendar=()=>[];await f.dispatcher.tick();assert.equal(f.record.sent.length,0);
|
||||
});
|
||||
|
||||
test('dispatcher acquires mailbox before preparing and retries the same slot when busy',async t=>{
|
||||
const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true;
|
||||
f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);};
|
||||
await due(f);assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);
|
||||
busy=false;await f.dispatcher.tick();assert.equal(f.record.prepared,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher recovers a manually prepared batch even when no new orders can be prepared',async t=>{
|
||||
const f=dispatchFixture(t);f.store.prepare=()=>[];
|
||||
await due(f);assert.equal(f.record.sent.length,1);assert.equal(f.record.status,'sent');await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher refuses a prepared snapshot frozen to a different mailbox before SMTP',async t=>{
|
||||
const f=dispatchFixture(t);f.batch.channelId='old-channel';
|
||||
await due(f);assert.equal(f.record.status,'failed');assert.equal(f.record.smtp,0);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.match(f.record.messages[0],/邮箱|渠道/);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher never carries a prepared morning batch into the afternoon slot after a pause',async t=>{
|
||||
const f=dispatchFixture(t);let prepareCount=0;
|
||||
f.store.prepare=()=>{prepareCount++;if(prepareCount===1){f.config.enabled=false;return [f.batch];}return [];};
|
||||
await due(f);assert.equal(f.record.begun,0);
|
||||
f.config.enabled=true;f.setNow('2026-10-20T08:59:00.000Z');await f.dispatcher.tick();
|
||||
f.setNow('2026-10-20T09:00:00.000Z');await f.dispatcher.tick();
|
||||
assert.equal(f.record.status,'prepared');assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher ignores old, future and mismatched-window prepared batches at the current slot',async t=>{
|
||||
for(const mutate of [b=>{b.cutoff='2026-10-19T09:00:00.000Z';},b=>{b.cutoff='2026-10-20T09:00:00.000Z';},b=>{b.window.start='2026-10-18T16:00:00.000Z';},b=>{delete b.window;}]){
|
||||
const f=dispatchFixture(t);mutate(f.batch);f.store.prepare=()=>[];await due(f);assert.equal(f.record.sent.length,0);assert.equal(f.record.smtp,0);await f.dispatcher.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('dispatcher resumes a paused prepared batch only within the same slot grace',async t=>{
|
||||
const f=dispatchFixture(t);let preparation=0;
|
||||
f.store.prepare=()=>{preparation++;if(preparation===1){f.config.enabled=false;return [f.batch];}return [];};
|
||||
await due(f);assert.equal(f.record.sent.length,0);f.setNow('2026-10-20T01:00:15.000Z');await f.dispatcher.tick();
|
||||
f.config.enabled=true;f.setNow('2026-10-20T01:00:30.000Z');await f.dispatcher.tick();
|
||||
assert.equal(f.record.sent.length,1);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher does not resume a prepared batch after its slot grace expires',async t=>{
|
||||
const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true;
|
||||
f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);};
|
||||
await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop();
|
||||
});
|
||||
|
||||
test('dispatcher rechecks slot expiration after asynchronous SMTP verification',async t=>{
|
||||
const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:01:01.000Z')});
|
||||
await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.equal(f.record.status,'failed');await f.dispatcher.stop();
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
'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 {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
test('rule HTTP authorizes drafts and trials, prevents origin forgery and archive-success claims',async t=>{
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace'));
|
||||
store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
|
||||
const orderRules=new RuleStore(path.join(dir,'rules')),server=createDashboard({store,workspace,orderRules,outputDir:dir});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
t.after(async()=>{server.closeAllConnections();await new Promise(r=>server.close(r));workspace.close();orderRules.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
const base='http://127.0.0.1:'+server.address().port;
|
||||
const call=(route,body,cookie,origin=base)=>fetch(base+'/api'+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
const login=async user=>(await call('/login',{username:user,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/order-rules')).status,401);
|
||||
const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
|
||||
const snapshot=await(await call('/order-rules',undefined,viewer)).json();assert.equal(snapshot.rules.length,15);assert.equal(snapshot.settings.enabled,false);
|
||||
const rule=snapshot.rules.find(r=>r.id==='bs-change');
|
||||
assert.equal((await call('/order-rules/rules',rule,operator)).status,403);
|
||||
assert.equal((await call('/order-rules/rules',rule,admin,'https://evil.test')).status,403);
|
||||
assert.equal((await call('/order-rules/rules',rule,admin)).status,200);
|
||||
const sample=snapshot.adapters.find(a=>a.id==='bs-change').sample;
|
||||
assert.equal((await call('/order-rules/preview',{sample},viewer)).status,403);
|
||||
const preview=await(await call('/order-rules/preview',{sample},operator)).json();assert.equal(preview.valid,true);assert.equal(orderRules.snapshot().orders.length,0);
|
||||
assert.equal((await call('/order-rules/orders/not-real/archive',{status:'archived',files:[]},admin)).status,404);
|
||||
assert.equal((await call('/order-rules/settings',{...snapshot.settings,enabled:true,channelId:'fake'},admin)).status,409);
|
||||
assert.equal((await call('/order-rules/events',{sample:{...sample,demo:true}},admin)).status,400);
|
||||
assert.equal((await call('/order-rules/preview',{sample,ruleId:'untrusted'},operator)).status,400);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { seedRules, adapters } = require('../../src/modules/order-rules/catalog.cjs');
|
||||
const { previewMatch, describeRule } = require('../../src/modules/order-rules/matching.cjs');
|
||||
|
||||
const sampleFor = id => structuredClone(adapters.find(item => item.id === id).sample);
|
||||
|
||||
test('title becomes separate order paragraphs without metadata and retains the raw evidence', () => {
|
||||
const sample=sampleFor('bs-change');
|
||||
sample.title='客户等级:C毛利:绿标订单号:148396机芯号:TDY0B8500V2MJS061产品型号:TDY0B-GJK0K06-001客户简称:江苏移动(家客版)总数量:5000订单类别:参考订单订单类型:C业务模式:惠州数字毛利:绿标订单号:HA148396机芯号:TDY0B-GJK0K06-H01客户简称:惠州创维数字技术有限公司总数量:5000';
|
||||
sample.brief='过时的摘要,不应覆盖标题';
|
||||
const result=previewMatch(seedRules(),adapters,sample);
|
||||
assert.equal(result.valid,true);
|
||||
assert.equal(result.event.brief,'订单号:148396机芯号:TDY0B8500V2MJS061产品型号:TDY0B-GJK0K06-001客户简称:江苏移动(家客版)总数量:5000订单类别:参考订单\n订单号:HA148396机芯号:TDY0B-GJK0K06-H01客户简称:惠州创维数字技术有限公司总数量:5000');
|
||||
assert.equal(result.event.rawTitle,sample.title);
|
||||
assert.deepEqual(result.event.titleOrders.map(o=>o.orderNo),['148396','HA148396']);
|
||||
assert.ok(result.event.factoryHints.some(h=>h.value==='惠州数字'&&h.source==='业务模式'));
|
||||
assert.ok(result.fieldTrace.some(f=>f.key==='brief'&&f.path==='title → 订单段落'));
|
||||
});
|
||||
|
||||
test('title extraction accepts Chinese colons and line breaks but rejects missing order identifiers',()=>{
|
||||
const sample=sampleFor('bs-change');
|
||||
sample.title='毛利:绿标<br>订单号:HA1机芯号:X总数量:0订单类型:C';
|
||||
const result=previewMatch(seedRules(),adapters,sample);
|
||||
assert.equal(result.event.brief,'订单号:HA1机芯号:X总数量:0');
|
||||
assert.deepEqual(result.event.factoryHints,[]); // HA alone is not factory evidence.
|
||||
for(const title of ['客户等级:C毛利:绿标','订单号:机芯号:X','订单号:A订单号:机芯号:X']){
|
||||
const invalid=previewMatch(seedRules(),adapters,{...sample,title});
|
||||
assert.equal(invalid.valid,false,title);
|
||||
assert.ok(invalid.issues.some(i=>i.includes('标题')));
|
||||
}
|
||||
});
|
||||
|
||||
test('sample must contain the chosen filename date and serial number before it can authorize a rule',()=>{
|
||||
const rules=seedRules();rules.find(r=>r.id==='bs-change').filenameDate='appDate';
|
||||
const sample=sampleFor('bs-change');delete sample.fields['OFR_BS_Applicant.AppDate'];delete sample.serialNum;
|
||||
const result=previewMatch(rules,adapters,sample);assert.equal(result.valid,false);assert.match(result.issues.join(';'),/申请日期/);assert.match(result.issues.join(';'),/流水/);
|
||||
sample.serialNum='SERIAL-1';sample.fields['OFR_BS_Applicant.AppDate']='2026-02-31';
|
||||
assert.equal(previewMatch(rules,adapters,sample).valid,false);
|
||||
sample.fields['OFR_BS_Applicant.AppDate']='2026-10-19 09:30:00';assert.equal(previewMatch(rules,adapters,sample).valid,true);
|
||||
});
|
||||
|
||||
test('exact process and explicit node alias select overseas change independently of product line', () => {
|
||||
const sample = sampleFor('overseas-change');
|
||||
sample.nodeName = '订单更改通知书';
|
||||
sample.fields['unrelated.ProductLine'] = '备损';
|
||||
const result = previewMatch(seedRules(), adapters, sample);
|
||||
assert.equal(result.valid, true);
|
||||
assert.equal(result.ruleId, 'overseas-change');
|
||||
assert.equal(result.event.orderNo, 'DEMO-OVERSEAS-001');
|
||||
assert.equal(result.event.processVersion, '1.1');
|
||||
assert.equal(result.event.documentNum, 'DEMO-SERIAL-002');
|
||||
assert.equal(result.fieldTrace.find(item => item.key === 'orderNo').path, 'OFR_HWLS_Applicant.OrderNum');
|
||||
assert.equal(sample.demo, true);
|
||||
});
|
||||
|
||||
test('unlisted node and similar process names never silently fuzzy match', () => {
|
||||
for (const patch of [{ nodeName: '订单更改通知' }, { processName: '海外返工订单更改评审(新)' }]) {
|
||||
const result = previewMatch(seedRules(), adapters, { ...sampleFor('overseas-change'), ...patch });
|
||||
assert.equal(result.valid, false);
|
||||
assert.deepEqual(result.candidates, []);
|
||||
assert.ok(result.issues.length > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('supported draft rules normalize raw bound fields and preserve a zero quantity', () => {
|
||||
const rules = seedRules();
|
||||
rules.find(item => item.id === 'bs-change').status = 'draft';
|
||||
const customAdapters = structuredClone(adapters);
|
||||
customAdapters.find(item => item.id === 'bs-change').fields.quantity = 'Demo.Quantity';
|
||||
const sample = sampleFor('bs-change');
|
||||
sample.fields['Demo.Quantity'] = 0;
|
||||
const result = previewMatch(rules, customAdapters, sample);
|
||||
assert.equal(result.valid, true);
|
||||
assert.equal(result.event.quantity, 0);
|
||||
assert.equal(result.event.customer, '演示客户');
|
||||
assert.equal(result.fieldTrace.find(item => item.key === 'quantity').value, 0);
|
||||
});
|
||||
|
||||
test('a missing adapter or wrong adapter process version is never a valid preview', () => {
|
||||
for (const [available, sample] of [[[], sampleFor('bs-change')], [adapters, { ...sampleFor('bs-change'), processVersion: '9.9' }]]) {
|
||||
const result = previewMatch(seedRules(), available, sample);
|
||||
assert.equal(result.valid, false);
|
||||
assert.equal(result.ruleId, 'bs-change');
|
||||
assert.ok(result.checks.some(item => !item.ok && item.label.includes('适配')));
|
||||
}
|
||||
});
|
||||
|
||||
test('colliding exact rules block rather than selecting the first candidate', () => {
|
||||
const rules = seedRules();
|
||||
rules.push({ ...rules.find(item => item.id === 'bs-change'), id: 'collision' });
|
||||
const result = previewMatch(rules, adapters, sampleFor('bs-change'));
|
||||
assert.equal(result.valid, false);
|
||||
assert.equal(result.ruleId, null);
|
||||
assert.deepEqual(result.candidates, ['bs-change', 'collision']);
|
||||
});
|
||||
|
||||
test('reports every missing identity and required field without early return', () => {
|
||||
const sample = sampleFor('bs-change');
|
||||
for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'receivedAt', 'brief']) delete sample[key];
|
||||
delete sample.fields['OFR_BS_Applicant.OrderNum'];
|
||||
const result = previewMatch(seedRules(), adapters, sample);
|
||||
assert.equal(result.valid, false);
|
||||
assert.ok(result.issues.length >= 8);
|
||||
for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'receivedAt', 'orderNo', 'brief']) {
|
||||
assert.ok(result.checks.some(item => !item.ok && item.detail.includes(key)), key);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid timestamps and negative or nonnumeric supplied quantities are rejected, revision zero survives', () => {
|
||||
const customAdapters = structuredClone(adapters);
|
||||
customAdapters.find(item => item.id === 'bs-change').fields.quantity = 'Demo.Quantity';
|
||||
for (const value of [-1, 'not a number']) {
|
||||
const sample = sampleFor('bs-change'); sample.fields['Demo.Quantity'] = value;
|
||||
assert.equal(previewMatch(seedRules(), customAdapters, sample).valid, false);
|
||||
}
|
||||
assert.equal(previewMatch(seedRules(), adapters, { ...sampleFor('bs-change'), receivedAt: 'yesterday' }).valid, false);
|
||||
assert.equal(previewMatch(seedRules(), adapters, { ...sampleFor('bs-change'), revision: 0 }).valid, true);
|
||||
});
|
||||
|
||||
test('all fifteen categories stay separate, paused and privately configurable with deterministic execution summaries', () => {
|
||||
const rules = seedRules();
|
||||
assert.equal(rules.length, 15);
|
||||
assert.equal(new Set(rules.map(item => item.categoryId)).size, 15);
|
||||
assert.deepEqual(rules.map(item => item.sourceRow), Array.from({ length: 15 }, (_, index) => index + 2));
|
||||
assert.ok(rules.every(item => item.status === 'paused' && !item.archiveDirectory && !item.to.length && !item.cc.length));
|
||||
assert.match(describeRule(rules.find(item => item.id === 'bs-change')), /备损订单更改通知书/);
|
||||
assert.match(describeRule(rules[0]), /同类.*一封/);
|
||||
rules[0].processNames.push('mutation');
|
||||
assert.ok(!seedRules()[0].processNames.includes('mutation'));
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
'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 {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
|
||||
function fixture(t,options={}){
|
||||
options={clock:()=>new Date('2026-10-19T02:00:00Z'),...options};
|
||||
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-rules-'));
|
||||
let store=new RuleStore(dir,options);
|
||||
t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
|
||||
return {dir,get store(){return store;},reopen(){store.close();store=new RuleStore(dir,options);return store;}};
|
||||
}
|
||||
function configure(store,id='bs-change'){
|
||||
const current=store.snapshot().rules.find(r=>r.id===id);
|
||||
const rule=store.saveRule({...current,to:['orders@example.test'],archiveDirectory:'\\\\server\\orders\\备损',filenameDate:'appDate'},'admin');
|
||||
const adapter=store.snapshot().adapters.find(a=>a.id===id);
|
||||
const sample={...adapter.sample,connectionId:'connection-1',instanceId:'instance-1',taskId:'task-1',revision:'1',demo:false};
|
||||
assert.equal(store.preview(sample).valid,true);
|
||||
store.publish(id,{version:rule.version},'admin');
|
||||
return sample;
|
||||
}
|
||||
test('draft edits persist and stale saves fail without changing the published rule',t=>{
|
||||
const f=fixture(t),sample=configure(f.store),before=f.store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
const changed=f.store.saveRule({...before,intro:'新版正文'},'admin');
|
||||
assert.throws(()=>f.store.saveRule(before,'admin'),e=>e.status===409);
|
||||
const reopened=f.reopen(),rule=reopened.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
assert.equal(rule.intro,'新版正文');assert.equal(rule.publishedVersion,before.version);assert.equal(rule.hasDraft,true);
|
||||
const order=reopened.ingest(sample,'admin');assert.notEqual(order.ruleSnapshot.intro,changed.intro);
|
||||
});
|
||||
test('preview does not create orders; rule edits do not create duplicate tasks; conflicting revision is rejected',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);assert.equal(store.snapshot().orders.length,0);
|
||||
const one=store.ingest(sample,'admin');assert.equal(store.ingest(sample,'admin').id,one.id);
|
||||
assert.equal(store.snapshot().orders.length,1);
|
||||
assert.throws(()=>store.ingest({...sample,brief:'更改了原文但没改版本'},'admin'),e=>e.status===409);
|
||||
assert.throws(()=>store.ingest({...sample,demo:true},'admin'),e=>e.status===400);
|
||||
});
|
||||
test('unverified providers prevent automatic execution and HTTP-style status claims cannot fake archiving',t=>{
|
||||
const {store}=fixture(t),sample=configure(store),order=store.ingest(sample,'operator');
|
||||
assert.equal(order.status,'blocked');assert.match(order.error,/接入|联调|归档/);
|
||||
assert.throws(()=>store.saveSettings({...store.settings(),enabled:true,channelId:'x'},'admin'),e=>e.status===409);
|
||||
assert.throws(()=>store.recordArchive(order.id,{files:[],archivedAt:new Date().toISOString()},'operator'),e=>e.status===400||e.status===409);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
});
|
||||
test('all same-category orders before cutoff aggregate once; post-cutoff orders stay pending; restart keeps uncertain sends blocked',t=>{
|
||||
const {store,reopen}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
for(let i=0;i<205;i++){
|
||||
const order=store.ingest({...sample,instanceId:'i'+i,taskId:'t'+i,receivedAt:'2026-10-19T01:00:00Z'},'system');
|
||||
store.recordArchive(order.id,{files:[{name:'order'+i+'.pdf',path:'C:\\archive\\order'+i+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');
|
||||
}
|
||||
const later=store.ingest({...sample,instanceId:'later',taskId:'later',receivedAt:'2026-10-19T10:00:00Z'},'system');
|
||||
store.recordArchive(later.id,{files:[{name:'later.pdf',path:'C:\\archive\\later.pdf',sha256:'b'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T10:01:00Z'},'archive-executor');
|
||||
const batches=store.prepare('2026-10-19T03:00:00Z','admin');assert.equal(batches.length,1);assert.equal(batches[0].orderIds.length,205);
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
assert.equal(store.snapshot().orders.find(o=>o.id===later.id).status,'pending');
|
||||
store.beginSending(batches[0].id);
|
||||
const recovered=reopen();assert.equal(recovered.snapshot().batches[0].status,'unknown');
|
||||
assert.equal(recovered.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
recovered.resolve(batches[0].id,{resolution:'sent',note:'已查询服务器确认完整接受'},'admin');
|
||||
assert.equal(recovered.snapshot().orders.filter(o=>o.status==='sent').length,205);
|
||||
});
|
||||
test('one incomplete order blocks the entire category, and publication demands a fresh sample trial',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
store.ingest(sample,'system');assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
const rule=store.snapshot().rules.find(r=>r.id==='bs-change'),draft=store.saveRule({...rule,intro:'新正文'},'admin');
|
||||
assert.throws(()=>store.publish(rule.id,{version:draft.version},'admin'),e=>e.status===409);
|
||||
});
|
||||
|
||||
test('semantic identity ignores JSON key order and numeric/string revision formatting',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);
|
||||
const first=store.ingest({...sample,revision:0},'system');
|
||||
const reordered=Object.fromEntries(Object.entries({...sample,revision:'0'}).reverse());
|
||||
reordered.fields=Object.fromEntries(Object.entries(sample.fields).reverse());
|
||||
assert.equal(store.ingest(reordered,'system').id,first.id);assert.equal(store.snapshot().orders.length,1);
|
||||
});
|
||||
test('demo structure preview cannot authorize publishing a business rule',t=>{
|
||||
const {store}=fixture(t),rule=store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
const saved=store.saveRule({...rule,to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');
|
||||
const sample=store.snapshot().adapters.find(a=>a.id==='bs-change').sample;
|
||||
assert.equal(store.preview(sample).valid,true);
|
||||
assert.throws(()=>store.publish(saved.id,{version:saved.version},'admin'),e=>e.status===409);
|
||||
});
|
||||
test('pausing a rule prevents a prepared batch from entering SMTP sending',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:'one.pdf',path:'C:\\archive\\one.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');
|
||||
const batch=store.prepare('2026-10-19T03:00:00Z','admin')[0],rule=store.snapshot().rules.find(r=>r.id==='bs-change');
|
||||
store.pause(rule.id,{version:rule.version},'admin');assert.throws(()=>store.beginSending(batch.id),e=>e.status===409);
|
||||
assert.equal(store.snapshot().batches[0].status,'prepared');
|
||||
});
|
||||
test('late discovered pre-cutoff orders cannot create a second email for an already frozen category and slot',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const archive=(sample)=>{const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:order.id+'.pdf',path:'C:\\archive\\'+order.id+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');return order;};
|
||||
archive(sample);assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,1);
|
||||
archive({...sample,instanceId:'late',taskId:'late'});
|
||||
assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);
|
||||
assert.equal(store.prepare('2026-10-19T09:00:00Z','admin').length,0);
|
||||
assert.equal(store.snapshot().orders.filter(o=>o.status==='ignored').length,2);
|
||||
});
|
||||
test('old history cannot enter this morning mail while current orders remain eligible',t=>{
|
||||
const {store}=fixture(t,{clock:()=>new Date('2026-10-20T02:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const old=store.ingest({...sample,instanceId:'old',taskId:'old',receivedAt:'2026-10-19T01:00:00Z'},'system');
|
||||
assert.equal(old.status,'ignored');
|
||||
assert.throws(()=>store.recordArchive(old.id,{files:[],archivedAt:'2026-10-20T02:00:00Z'},'archive-executor'),e=>e.status===409);
|
||||
const current=store.ingest({...sample,instanceId:'current',taskId:'current',receivedAt:'2026-10-20T01:00:00Z'},'system');
|
||||
store.recordArchive(current.id,{files:[{name:'current.pdf',path:'C:\\archive\\current.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-20T01:05:00Z'},'archive-executor');
|
||||
const batches=store.prepare('2026-10-20T03:00:00Z','admin');assert.equal(batches.length,1);assert.deepEqual(batches[0].orderIds,[current.id]);
|
||||
assert.equal(batches[0].window.start,'2026-10-19T16:00:00.000Z');
|
||||
});
|
||||
test('paused old publication cannot shadow an enabled replacement for the same process and node',t=>{
|
||||
const {store}=fixture(t),sample=configure(store);
|
||||
const old=store.snapshot().rules.find(r=>r.id==='bs-change');store.pause(old.id,{version:old.version},'admin');
|
||||
store.saveRule({...old,processNames:['暂不使用的旧流程']},'admin');
|
||||
const candidate=store.snapshot().rules.find(r=>r.id==='trial-change');
|
||||
const replacement=store.saveRule({...candidate,processNames:['备损订单更改评审'],nodeNames:['订单专员(订单通知书)'],adapterIds:['bs-change'],to:['replacement@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'appDate'},'admin');
|
||||
assert.equal(store.preview(sample).ruleId,'trial-change');store.publish(replacement.id,{version:replacement.version},'admin');
|
||||
const order=store.ingest(sample,'system');assert.equal(order.categoryId,'trial-change');assert.equal(order.trace.valid,true);
|
||||
});
|
||||
test('paused ingestion retains classification and explicit recheck can recover against the current rule',t=>{
|
||||
const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store);
|
||||
const rule=store.snapshot().rules.find(r=>r.id==='bs-change');store.pause(rule.id,{version:rule.version},'admin');
|
||||
const order=store.ingest(sample,'system');assert.equal(order.categoryId,'bs-change');assert.equal(order.status,'blocked');
|
||||
store.publish(rule.id,{version:rule.version},'admin');
|
||||
const checked=store.recheck(order.id,{note:'已核实规则恢复,重新识别'},'admin');
|
||||
assert.equal(checked.status,'identified');assert.equal(checked.ruleSnapshot.version,rule.version);
|
||||
assert.equal(store.snapshot().orders.length,1);
|
||||
assert.throws(()=>store.prepare('2026-10-19T12:00:00','admin'),e=>e.status===400);
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {Store}=require('../../src/modules/dashboard/store.cjs');
|
||||
const {createDashboard}=require('../../src/app/dashboard.cjs');
|
||||
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
|
||||
const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
|
||||
const {startPreview}=require('../../scripts/preview.cjs');
|
||||
|
||||
test('category editor saves/reloads drafts, previews readable evidence without ingesting, and gates execution',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-web-')),store=new Store(path.join(dir,'users'));
|
||||
store.bootstrap('admin','Test-password-123');
|
||||
const server=createDashboard({store,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
let browser;t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));await fs.rm(dir,{recursive:true,force:true});});
|
||||
const sample={connectionId:'sample',source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'订单流程',nodeName:'通知',fields:{'订单.数量':0}};
|
||||
const data={rules:[{id:'category-1',version:1,status:'draft',name:'示例类别',categoryId:'category-1',processNames:['订单流程'],nodeNames:['通知'],adapterIds:['a1'],archiveDirectory:'',filenameDate:'appDate',subjectPrefix:'通知',intro:'正文',signature:'团队',to:[],cc:[],attachPdf:true}],adapters:[{id:'a1',label:'订单表单',verified:true,processName:'订单流程',fields:{quantity:'订单.数量'},sample}],orders:[],batches:[],settings:{version:1,enabled:false,channelId:'',maxMessageBytes:20971520},audit:[],capabilities:{liveTodo:false,pdfExport:false,automaticArchive:false}};
|
||||
data.window={start:'2026-10-20T00:00:00+08:00',end:'2026-10-20T11:00:00+08:00',label:'工作日第一时段',available:true};
|
||||
const writes=[];browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.clock.install();
|
||||
await page.route('**/api/order-rules**',async route=>{const req=route.request(),url=new URL(req.url());let result=data;if(req.method()==='POST'){const body=req.postDataJSON();writes.push({path:url.pathname,body});if(url.pathname.endsWith('/rules')){data.rules[0]={...data.rules[0],...body,version:data.rules[0].version+1};result=data.rules[0];}else if(url.pathname.endsWith('/preview'))result={valid:true,ruleId:'category-1',checks:[{label:'数量',ok:true,detail:'零数量合法'}],issues:[],explanation:'按类别汇总一封邮件',fieldTrace:[{key:'quantity',label:'数量',path:'订单.数量',value:0}],event:{orderNo:'SAMPLE-1',quantity:0}};else if(url.pathname.endsWith('/publish')){await route.fulfill({status:409,json:{error:'实时待办接入待联调,暂不可发布'}});return;}}await route.fulfill({json:result});});
|
||||
await page.goto('http://127.0.0.1:'+server.address().port+'/#order-rules');await page.getByLabel('账号',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'进入演示空间',exact:true}).count(),0);await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();
|
||||
await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.getByLabel('规则名称',{exact:true}).fill('订单类别更新');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
assert.equal(data.rules[0].name,'订单类别更新');assert.deepEqual(data.rules[0].to,['recipient@example.test']);assert.deepEqual(writes[0].body.processNames,['订单流程']);
|
||||
await page.reload();await page.getByRole('button',{name:'通知规则',exact:true}).click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'订单类别更新');
|
||||
await page.getByLabel('BPM 原始标题',{exact:true}).fill('客户等级:C订单号:148396机芯号:X毛利:绿标订单号:HA148396总数量:5000');await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result').getByText('零数量合法',{exact:true}).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/订单.数量/);assert.match(await page.locator('#order-rule-preview-result').innerText(),/0/);assert.equal(data.orders.length,0);assert.equal(writes.some(x=>x.path.endsWith('/events')),false);assert.equal(writes.find(x=>x.path.endsWith('/preview')).body.sample.title,'客户等级:C订单号:148396机芯号:X毛利:绿标订单号:HA148396总数量:5000');
|
||||
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('实时待办接入待联调,暂不可发布',{exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'设置',exact:true}).click();assert.equal(await page.getByLabel('启用自动分类通知',{exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/待联调/);
|
||||
data.orders=[{id:'old',orderNo:'HISTORICAL-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-19T09:00:00+08:00'},{id:'current',orderNo:'CURRENT-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T09:00:00+08:00'},{id:'future',orderNo:'FUTURE-ORDER',categoryId:'category-1',status:'pending',receivedAt:'2026-10-20T15:00:00+08:00'}];
|
||||
await page.reload();await page.getByRole('button',{name:'待发批次',exact:true}).click();await page.getByText('暂无待发批次',{exact:true}).waitFor();
|
||||
assert.equal(await page.getByLabel('本批截止时间(北京时间)',{exact:true}).count(),0);assert.match(await page.locator('#order-rules-panel').innerText(),/工作日第一时段/);assert.match(await page.locator('#order-rules-panel').innerText(),/CURRENT-ORDER/);assert.doesNotMatch(await page.locator('#order-rules-panel').innerText(),/HISTORICAL-ORDER|FUTURE-ORDER/);
|
||||
await page.getByRole('button',{name:'整理本时段批次',exact:true}).click();assert.deepEqual(writes.find(x=>x.path.endsWith('/prepare')).body,{cutoff:data.window.end});
|
||||
await page.locator('[data-rule-recheck="current"]').locator('..').locator('summary').click();await page.getByLabel('重新核对依据',{exact:true}).fill('已核实更新后的业务分类');await page.getByRole('button',{name:'重新核对此订单',exact:true}).click();await page.getByText('此订单已重新核对,请检查新匹配结果及归档状态。',{exact:true}).waitFor();assert.deepEqual(writes.find(x=>x.path.endsWith('/recheck')).body,{note:'已核实更新后的业务分类'});
|
||||
data.window.available=false;await page.reload();await page.getByRole('button',{name:'待发批次',exact:true}).click();assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),true);assert.match(await page.locator('#order-rules-panel').innerText(),/当前只预览/);
|
||||
data.window.available=true;data.batches=[{id:'fresh-batch',categoryId:'category-1',subject:'自动刷新后的本时段批次',status:'prepared',windowStart:data.window.start,windowEnd:data.window.end,to:[],orderIds:[]}];await page.clock.fastForward(15001);await page.getByText('自动刷新后的本时段批次',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'整理本时段批次',exact:true}).isDisabled(),false);
|
||||
await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('#order-rule-advanced summary').click();const typedSample='{"custom":"保留尚未运行的样本"}';await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(typedSample);await page.clock.fastForward(15001);assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample);await page.getByLabel('规则名称',{exact:true}).fill('保留尚未保存的规则');await page.clock.fastForward(15001);assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'保留尚未保存的规则');assert.equal(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue(),typedSample);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
|
||||
test('isolated preview offers a direct entry button and opens category rules without credentials',{timeout:60000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-preview-web-'));const runtime=await startPreview({stateDir:dir,port:0});let browser;t.after(async()=>{await browser?.close();runtime.server.closeAllConnections();await runtime.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#order-rules');await page.getByRole('button',{name:'进入演示空间',exact:true}).click();await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.getByText('Excel 分类 · 15',{exact:true}).waitFor();assert.equal(runtime.orderRules.snapshot().orders.length,0);assert.equal(await page.getByLabel('规则名称',{exact:true}).isEnabled(),true);
|
||||
});
|
||||
|
||||
test('real catalog workflow publishes a saved and sampled draft while roles and production gates remain enforced',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-rules-real-web-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');
|
||||
for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');
|
||||
const orderRules=new RuleStore(path.join(dir,'rules')),server=createDashboard({store,orderRules,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;
|
||||
t.after(async()=>{await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));orderRules.close();await fs.rm(dir,{recursive:true,force:true});});
|
||||
browser=await loadPlaywright().chromium.launch(browserOptions());const base='http://127.0.0.1:'+server.address().port;
|
||||
async function open(role){const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.goto(base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'通知规则',exact:true}).click();return page;}
|
||||
const page=await open('admin');await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('规则名称',{exact:true}).fill('备损更改通知测试');await page.getByLabel('归档目录',{exact:true}).fill('\\\\fixture-server\\orders\\changes');await page.getByLabel('文件名日期依据',{exact:true}).selectOption('appDate');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
|
||||
await page.reload();await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'备损更改通知测试');
|
||||
await page.locator('#order-rule-advanced summary').click();const realSample=JSON.parse(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue());realSample.demo=false;await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(JSON.stringify(realSample));await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert').getByText(/样本校验通过/).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/OFR_BS_Applicant.OrderNum/);await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('规则版本已发布。自动执行仍由全局设置与接入状态控制。',{exact:true}).waitFor();
|
||||
assert.equal(orderRules.snapshot().rules.find(r=>r.id==='bs-change').status,'enabled');assert.equal(orderRules.snapshot().settings.enabled,false);assert.equal(orderRules.snapshot().orders.length,0);
|
||||
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
|
||||
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/order-rules-mobile.png'),fullPage:true});await page.setViewportSize({width:1440,height:1000});await page.screenshot({path:path.resolve('output/verification/order-rules-desktop.png'),fullPage:true});
|
||||
const operator=await open('operator');assert.equal(await operator.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await operator.getByRole('button',{name:'保存草稿',exact:true}).count(),0);assert.equal(await operator.getByRole('button',{name:'校验已保存规则',exact:true}).count(),1);
|
||||
const viewer=await open('viewer');assert.equal(await viewer.getByLabel('规则名称',{exact:true}).isDisabled(),true);assert.equal(await viewer.getByRole('button',{name:'校验已保存规则',exact:true}).count(),0);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');
|
||||
const {windowForCutoff,upcomingWindow,inWindow}=require('../../src/modules/order-rules/window.cjs');
|
||||
const schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai',weekends:false};
|
||||
test('normal weekday only includes same-day first interval or interval between send times',()=>{
|
||||
const morning=windowForCutoff('2026-10-20T03:00:00Z',schedule),afternoon=windowForCutoff('2026-10-20T09:00:00Z',schedule);
|
||||
assert.equal(morning.start,'2026-10-19T16:00:00.000Z');assert.equal(morning.end,'2026-10-20T03:00:00.000Z');
|
||||
assert.equal(afternoon.start,'2026-10-20T03:00:00.000Z');assert.equal(afternoon.end,'2026-10-20T09:00:00.000Z');
|
||||
assert.equal(inWindow('2026-10-19T08:00:00Z',morning),false);
|
||||
assert.equal(inWindow('2026-10-20T03:00:00Z',morning),false);assert.equal(inWindow('2026-10-20T03:00:00Z',afternoon),true);
|
||||
});
|
||||
test('Monday first mail covers last workday final cutoff through Monday morning, never older history',()=>{
|
||||
const window=windowForCutoff('2026-10-19T03:00:00Z',schedule);
|
||||
assert.equal(window.start,'2026-10-16T09:00:00.000Z');assert.equal(window.end,'2026-10-19T03:00:00.000Z');
|
||||
assert.equal(inWindow('2026-10-16T08:59:59Z',window),false);assert.equal(inWindow('2026-10-17T10:00:00Z',window),true);
|
||||
});
|
||||
test('business calendar determines previous actual working day across a rest period',()=>{
|
||||
const window=windowForCutoff('2026-10-19T03:00:00Z',schedule,[{date:'2026-10-16',kind:'restday',send:false,scan:false}]);
|
||||
assert.equal(window.start,'2026-10-15T09:00:00.000Z');
|
||||
assert.throws(()=>windowForCutoff('2026-10-18T03:00:00Z',schedule),e=>e.status===400);
|
||||
assert.throws(()=>windowForCutoff('2026-10-20T04:00:00Z',schedule),e=>e.status===400);
|
||||
});
|
||||
test('future preview cannot freeze a mail before its cutoff; missed slots do not reopen old windows',()=>{
|
||||
const next=upcomingWindow(new Date('2026-10-20T02:00:00Z'),schedule);
|
||||
assert.equal(next.end,'2026-10-20T03:00:00.000Z');assert.equal(next.available,false);
|
||||
assert.equal(upcomingWindow(new Date('2026-10-20T03:00:30Z'),schedule).available,true);
|
||||
const missed=upcomingWindow(new Date('2026-10-20T03:02:00Z'),schedule);
|
||||
assert.equal(missed.start,'2026-10-20T03:00:00.000Z');assert.equal(missed.available,false);
|
||||
});
|
||||
@@ -22,3 +22,5 @@
|
||||
@media(max-width:767px){.assistant-layout{grid-template-columns:minmax(0,1fr)}.assistant-sidebar{max-height:230px}.assistant-messages{min-height:340px;padding:1rem}.assistant-user{margin-left:5%}.assistant-welcome{padding:2rem .25rem}.assistant-chat .card-footer{padding:1rem}.assistant-chat .btn-list{gap:.4rem}}
|
||||
|
||||
.health-check-item+.health-check-item{border-top:1px solid var(--tblr-border-color,#dce1e7);padding-top:1rem;margin-top:1rem}.health-check-times{display:grid;grid-template-columns:5rem minmax(0,1fr);gap:.4rem .6rem}.health-check-times dt{font-weight:400;color:var(--tblr-secondary,#6c7a91)}.health-check-times dd{margin:0;overflow-wrap:anywhere}#health-runtime .card,#health-groups .card{min-width:0}
|
||||
.order-rule-tabs{display:flex;gap:.5rem;flex-wrap:wrap}.order-rule-tabs .btn{flex:0 0 auto}.order-rules-layout{display:grid;grid-template-columns:240px minmax(0,1fr);gap:1.25rem;align-items:start}.order-rule-main,.order-rule-list,.order-rules .card,.order-rules .card-body{min-width:0}.order-rule-list .list-group-item{text-align:left;padding:1rem;white-space:normal;overflow-wrap:anywhere}.order-rule-list .list-group-item.active{background:#eef6f1;color:#254c3a;border-color:#dce9df;box-shadow:inset 3px 0 #28745b}.order-rule-list strong{font-size:.86rem;font-weight:550}.order-rule-capabilities{display:flex;flex-wrap:wrap;gap:1rem 1.8rem}.order-rule-capabilities>div{display:flex;align-items:center;gap:.65rem;font-size:.82rem}.order-rule-explanation{background:#f0f6f2;border:1px solid #dce9df;border-radius:8px;padding:1rem;line-height:1.85;font-size:.85rem;overflow-wrap:anywhere}.order-rule-record{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.8}.order-rules-empty{padding:2rem 1rem;text-align:center;font-size:.85rem}.order-rules-table td{min-width:140px;max-width:560px;overflow-wrap:anywhere}.order-rules-table th{white-space:nowrap}.order-rule-fields td{vertical-align:top;max-width:240px;overflow-wrap:anywhere}.order-rule-fields code{white-space:normal;overflow-wrap:anywhere}.order-rule-fields th{white-space:nowrap}.order-rule-cutoff{max-width:260px}.order-rules summary{cursor:pointer}.order-rules select[multiple]{min-height:115px}.order-rules #order-rules-feedback:empty{display:none}
|
||||
@media(max-width:991px){.order-rules-layout{grid-template-columns:minmax(0,1fr)}.order-rule-list .list-group{max-height:240px;overflow:auto}}@media(max-width:767px){.order-rule-capabilities{gap:.8rem;flex-direction:column}.order-rule-tabs{gap:.35rem}.order-rule-tabs .btn{padding:.5rem .65rem;font-size:.8rem}.order-rules select[multiple]{width:100%;min-width:0}.order-rule-fields{font-size:.76rem}.order-rule-explanation{padding:.8rem}.order-rules-table td{max-width:300px}}
|
||||
+9
-7
@@ -5,7 +5,7 @@ const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(
|
||||
const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'};
|
||||
const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']};
|
||||
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0;
|
||||
const views={health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['业务通知','配置来源字段、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
const views={'order-rules':['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别配置匹配、归档与邮件,查看订单和批次状态'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
async function api(route,body,{signal}={}) {
|
||||
const response=await fetch('/api'+route,{signal,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});
|
||||
const result=await response.json();
|
||||
@@ -19,7 +19,7 @@ function notify(message,type='success') {
|
||||
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
|
||||
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="#${id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${symbol}</span><span class="nav-link-title">${views[id][0]}</span></a></li>`;}
|
||||
function shell() {
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('health','◉')}${navItem('supervisor','◎')}${navItem('assistant','Z')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('storage','▤')}${navItem('notifications','✉')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('health','◉')}${navItem('supervisor','◎')}${navItem('assistant','Z')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('order-rules','▤')}${navItem('records','≡')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('storage','▤')}${navItem('notifications','✉')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();};
|
||||
document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger'));
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');});
|
||||
@@ -45,7 +45,7 @@ async function viewPdfRecords(container,isActive=()=>true) {
|
||||
}
|
||||
async function viewSchedule(container,isActive=()=>true) {
|
||||
const loaded=await api('/settings');if(!isActive())return;settings=loaded;const s=settings.schedule;const disabled=currentUser.role!=='admin'?'disabled':'';
|
||||
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">请在 <a href="#notifications">业务通知</a> 中配置来源并设置自动发送开关。</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div><div class="col-sm-6"><label class="form-label" for="send-mode">邮件整理方式</label><select class="form-select" id="send-mode" ${disabled}><option value="product_line" ${s.mode==='product_line'?'selected':''}>按产品线汇总为一封邮件</option><option value="order" ${s.mode==='order'?'selected':''}>每个订单单独发送一封</option></select></div><div class="col-sm-6"><label class="form-label" for="missed">停机错过时段后</label><select class="form-select" id="missed" ${disabled}><option value="next_window" ${s.missed==='next_window'?'selected':''}>保留待发订单,下一时段合并处理</option><option value="skip" ${s.missed==='skip'?'selected':''}>跳过错过时段,继续正常计划</option></select></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
|
||||
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">新分类通知在 <a href="#order-rules">分类通知规则</a> 配置,按本时段内 Excel 类别汇总,更早历史不补发。下方整理方式与停机选项供 <a href="#notifications">兼容业务通知</a> 使用。</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div><div class="col-sm-6"><label class="form-label" for="send-mode">邮件整理方式</label><select class="form-select" id="send-mode" ${disabled}><option value="product_line" ${s.mode==='product_line'?'selected':''}>按产品线汇总为一封邮件</option><option value="order" ${s.mode==='order'?'selected':''}>每个订单单独发送一封</option></select></div><div class="col-sm-6"><label class="form-label" for="missed">停机错过时段后</label><select class="form-select" id="missed" ${disabled}><option value="next_window" ${s.missed==='next_window'?'selected':''}>保留待发订单,下一时段合并处理</option><option value="skip" ${s.missed==='skip'?'selected':''}>跳过错过时段,继续正常计划</option></select></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
|
||||
document.querySelector('#schedule-form').onsubmit=async event=>{event.preventDefault();try{const updated=await api('/settings',{version:settings.version,schedule:{times:[document.querySelector('#time-first').value,document.querySelector('#time-second').value],timezone:'Asia/Shanghai',weekends:document.querySelector('#weekends').checked,mode:document.querySelector('#send-mode').value,missed:document.querySelector('#missed').value}});settings=updated;notify('发送计划已保存。');}catch(error){notify(error.message,'danger');}};
|
||||
}
|
||||
async function viewTemplates(container,isActive=()=>true) {
|
||||
@@ -67,7 +67,7 @@ async function viewUsers(container,isActive=()=>true) {
|
||||
document.querySelector('#user-form').onsubmit=async event=>{event.preventDefault();try{await api('/users',{username:document.querySelector('#new-username').value,password:document.querySelector('#new-password').value,role:document.querySelector('#new-role').value});notify('账号已创建。');await viewUsers(container,isActive);}catch(error){notify(error.message,'danger');}};
|
||||
}
|
||||
async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`<div class="card"><div class="card-header"><h2 class="card-title">最近操作记录</h2><span class="text-secondary ms-auto">按时间展示最近 200 条</span></div>${audit.length?`<div class="table-responsive"><table class="table card-table"><thead><tr><th>时间(北京时间)</th><th>操作人</th><th>操作</th><th>详情</th></tr></thead><tbody>${audit.slice(0,200).map(item=>`<tr><td class="small text-secondary">${formatDate(item.at)}</td><td>${esc(item.actor)}</td><td>${esc(window.WorkspaceViews.activityText(item.action))}</td><td class="audit-detail text-secondary">${esc(item.detail)}</td></tr>`).join('')}</tbody></table></div>`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}</div>`;}
|
||||
function viewRules(container){container.innerHTML=`<div class="card"><div class="card-header"><h2 class="card-title">订单识别与匹配</h2><span class="badge bg-yellow-lt">等待业务表格</span></div><div class="card-body"><div class="steps steps-counter steps-blue mb-5"><span class="step-item active">提供业务表格</span><span class="step-item">确认字段对应</span><span class="step-item">预览匹配订单</span><span class="step-item">启用自动处理</span></div>${empty('依据你的表格识别订单','暂无匹配规则')}</div></div>`;}
|
||||
function viewRules(container,isActive){return window.OrderRuleViews.render(container,isActive);}
|
||||
async function renderView() {
|
||||
if(!currentUser)return;
|
||||
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
|
||||
@@ -77,15 +77,17 @@ async function renderView() {
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView));
|
||||
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
|
||||
const container=document.querySelector('#content');container.innerHTML='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
|
||||
const fn={health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
const fn={'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
|
||||
}
|
||||
async function authScreen() {
|
||||
const setup=await api('/bootstrap/status');const initialize=setup.required && setup.canSetup;
|
||||
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form><p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
|
||||
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form>${setup.preview===true?'<div class="card card-body mt-3 text-center"><button class="btn btn-primary" type="button" id="preview-login">进入演示空间</button><p class="small text-secondary mt-3 mb-0">使用独立演示数据,不访问 BPM,不发送邮件。</p></div>':''}<p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
|
||||
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
|
||||
if(setup.preview===true)document.querySelector('#preview-login').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await api('/preview-login',{});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};
|
||||
|
||||
}
|
||||
function enter(){window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
function enter(){window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
|
||||
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
|
||||
window.addEventListener('hashchange',()=>{if(currentUser)renderView();});
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"></head>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/health.js" defer></script><script src="/assistant.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail-history.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage-preview-host.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/order-rules-editor.js" defer></script><script src="/order-rules-preview.js" defer></script><script src="/order-rules.js" defer></script><script src="/health.js" defer></script><script src="/assistant.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
@@ -0,0 +1,51 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
async function render(container,{api,esc,formatDate,notify,user,isActive=()=>true,back}){
|
||||
const data=await api('/mail');if(!isActive())return;
|
||||
if(user.role!=='admin'){container.innerHTML='<div class="alert alert-info">历史邮件仅限管理员查阅。</div>';return;}
|
||||
const channels=data.channels;
|
||||
container.innerHTML=`<section class="card mb-3"><div class="card-header flex-wrap gap-2"><h2 class="card-title">只读查阅已发送邮件</h2>${back?'<button class="btn btn-sm ms-auto" id="history-back">返回邮箱管理</button>':''}<button class="btn btn-primary" id="history-add">添加只读邮箱</button></div><div class="card-body"><p>用于核对历史通知的主题、正文、主送、抄送和附件名称。只读取服务器上的已发送邮件,不更改已读标记,不发信,不导入模板。</p><div class="text-secondary small">邮箱须开通 IMAP。授权码仅在本机表单填写并加密保存;无需 SMTP 配置。若历史邮件仅保存在 Foxmail 本地,IMAP 无法读取。</div></div></section><div id="history-editor"></div><form class="card" id="history-search"><div class="card-body"><label class="form-label" for="history-channel">查询邮箱</label><div class="d-flex flex-wrap gap-2 mb-3"><select class="form-select" style="max-width:100%" id="history-channel"><option value="">请选择邮箱</option>${channels.map(c=>`<option value="${esc(c.id)}">${esc(c.name)} · ${esc(c.email)}</option>`).join('')}</select><button type="button" class="btn" id="history-folders">连接并列出已发送文件夹</button><button type="button" class="btn" id="history-edit">修改只读邮箱配置</button></div><label class="form-label" for="history-folder">已发送文件夹</label><select class="form-select mb-3" id="history-folder" required><option value="">请先连接邮箱</option></select><div class="row g-3"><div class="col-md-4"><label class="form-label" for="history-since">开始日期(包含)</label><input class="form-control" type="date" id="history-since" required></div><div class="col-md-4"><label class="form-label" for="history-before">结束日期(不包含)</label><input class="form-control" type="date" id="history-before" required></div><div class="col-md-4"><label class="form-label" for="history-subject">主题关键词</label><input class="form-control" id="history-subject" maxlength="100" value="订单"></div></div><div class="form-hint mt-2">每次最多31天,显示最近20封匹配邮件;结果多时缩小日期或关键词。</div><div id="history-error" class="text-danger mt-3" role="alert"></div></div><div class="card-footer"><button class="btn btn-primary" type="submit">查询已发送邮件</button></div></form><div id="history-results" class="mt-3"></div><div id="history-detail" class="mt-3"></div>`;
|
||||
const find=id=>container.querySelector('#'+id),read=id=>find(id).value;
|
||||
const day=d=>new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(d);
|
||||
find('history-since').value=day(new Date(Date.now()-14*86400000));find('history-before').value=day(new Date(Date.now()+86400000));
|
||||
let epoch='',resultChannel='',resultFolder='';
|
||||
async function act(button,work){button.disabled=true;find('history-error').textContent='';try{await work();}catch(e){if(isActive())find('history-error').textContent=e.message;}finally{if(button.isConnected)button.disabled=false;}}
|
||||
const query=(id,body)=>api(`/mail/channels/${encodeURIComponent(id)}/history`,body);
|
||||
find('history-back')?.addEventListener('click',back);
|
||||
find('history-add').onclick=()=>editor();
|
||||
find('history-edit').onclick=()=>{const c=channels.find(c=>c.id===read('history-channel'));if(!c?.readOnly){notify('请选择已保存的只读邮箱;发信邮箱请在原邮箱管理页修改。','warning');return;}editor(c);};
|
||||
find('history-channel').onchange=()=>{find('history-folder').innerHTML='<option value="">请先连接邮箱</option>';find('history-results').replaceChildren();find('history-detail').replaceChildren();epoch='';};
|
||||
if(channels.length===1)find('history-channel').value=channels[0].id;
|
||||
find('history-folders').onclick=e=>act(e.target,async()=>{
|
||||
const id=read('history-channel');if(!id)throw Error('请先选择邮箱。');
|
||||
const result=await query(id,{action:'folders'});if(!isActive()||read('history-channel')!==id)return;
|
||||
find('history-folder').innerHTML=result.folders.map(f=>`<option value="${esc(f.path)}">${esc(f.name)}</option>`).join('')||'<option value="">未识别到已发送文件夹</option>';
|
||||
if(!result.folders.length)throw Error('服务器未提供可识别的已发送文件夹,请确认已发送邮件已同步到服务器。');
|
||||
});
|
||||
find('history-search').onsubmit=e=>{e.preventDefault();act(e.submitter,async()=>{
|
||||
const id=read('history-channel'),folder=read('history-folder');if(!id||!folder)throw Error('请先连接邮箱并选择已发送文件夹。');
|
||||
const result=await query(id,{action:'search',folder,since:read('history-since'),before:read('history-before'),subject:read('history-subject'),limit:20});
|
||||
if(!isActive()||read('history-channel')!==id||read('history-folder')!==folder)return;
|
||||
epoch=result.uidValidity;resultChannel=id;resultFolder=folder;find('history-detail').replaceChildren();
|
||||
find('history-results').innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">历史邮件(${result.messages.length})</h3></div>${result.truncated?'<div class="card-body text-warning">仅显示最近20封,请缩小查询范围。</div>':''}<div class="table-responsive"><table class="table card-table"><thead><tr><th>日期 / 主题</th><th></th></tr></thead><tbody>${result.messages.map(m=>`<tr><td class="text-break">${esc(m.subject)}<div class="small text-secondary">${formatDate(m.date)}</div></td><td><button class="btn btn-sm" data-history-uid="${m.uid}">查看邮件</button></td></tr>`).join('')||'<tr><td colspan="2" class="text-secondary">没有匹配的服务器邮件;这不代表本地客户端没有历史邮件。</td></tr>'}</tbody></table></div></section>`;
|
||||
container.querySelectorAll('[data-history-uid]').forEach(b=>b.onclick=()=>act(b,async()=>{
|
||||
const savedEpoch=epoch,savedChannel=resultChannel,savedFolder=resultFolder;
|
||||
const detail=await query(savedChannel,{action:'message',folder:savedFolder,uid:Number(b.dataset.historyUid),uidValidity:savedEpoch});
|
||||
if(!isActive()||savedEpoch!==epoch||savedChannel!==read('history-channel')||savedFolder!==read('history-folder'))return;
|
||||
const address=values=>values.map(a=>a.name?`${a.name} <${a.address}>`:a.address).join(';');
|
||||
find('history-detail').innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title text-break">${esc(detail.subject)}</h3></div><div class="card-body"><div class="small text-break mb-3">日期:${formatDate(detail.date)}<br>主送:${esc(address(detail.to))}<br>抄送:${esc(address(detail.cc))}<br>来源:${esc(detail.folder)} · UID ${detail.uid} · ${esc(detail.messageId)}</div><pre style="white-space:pre-wrap;overflow-wrap:anywhere" id="history-body"></pre>${detail.truncated?'<div class="text-warning">正文过长,仅显示前100000字符。</div>':''}<h4>附件名称</h4><ul>${detail.attachments.map(a=>`<li class="text-break">${esc(a.filename)}(${Math.ceil(a.size/1024)} KB)</li>`).join('')||'<li class="text-secondary">无附件</li>'}</ul></div></section>`;
|
||||
find('history-body').textContent=detail.text;
|
||||
}));
|
||||
});};
|
||||
function editor(c){
|
||||
const host=find('history-editor'),v=c?.imap||{};
|
||||
host.innerHTML=`<form class="card mb-3" id="history-account"><div class="card-header"><h3 class="card-title">${c?'修改':'添加'}只读邮箱</h3></div><div class="card-body"><div class="row g-3">${[['history-name','邮箱名称',c?.name||'','text'],['history-email','邮箱地址',c?.email||'','email'],['history-host','IMAP 服务器',v.host||'','text'],['history-user','IMAP 登录账号',v.user||'','text'],['history-port','IMAP 端口',v.port||993,'number']].map(([id,label,val,type])=>`<div class="col-md-6"><label class="form-label" for="${id}">${label}</label><input class="form-control" id="${id}" type="${type}" value="${esc(val)}" required></div>`).join('')}<div class="col-md-6"><label class="form-label" for="history-security">IMAP 加密方式</label><select class="form-select" id="history-security"><option value="tls">SSL / TLS</option><option value="starttls" ${v.security==='starttls'?'selected':''}>STARTTLS</option></select></div><div class="col-12"><label class="form-label" for="history-password">IMAP 授权码</label><input class="form-control" id="history-password" type="password" maxlength="2048" autocomplete="new-password" ${c?'':'required'} placeholder="${c?'留空保留原授权码':'仅在本机填写'}"></div></div><div id="history-save-error" class="text-danger mt-3" role="alert"></div></div><div class="card-footer btn-list"><button class="btn btn-primary" type="submit">保存只读邮箱</button><button class="btn" type="button" id="history-cancel">取消</button></div></form>`;
|
||||
find('history-cancel').onclick=()=>host.replaceChildren();
|
||||
find('history-account').onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;try{
|
||||
await api('/mail/channels',{...(c?{id:c.id,version:c.version}:{}),readOnly:true,name:read('history-name'),email:read('history-email'),imap:{host:read('history-host'),user:read('history-user'),port:Number(read('history-port')),security:read('history-security'),password:read('history-password')}});
|
||||
find('history-password').value='';if(isActive()){await render(container,{api,esc,formatDate,notify,user,isActive,back});notify('只读邮箱已保存。');}
|
||||
}catch(error){if(isActive())find('history-save-error').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}};
|
||||
}
|
||||
}
|
||||
window.MailHistoryViews={render};
|
||||
})();
|
||||
@@ -9,6 +9,7 @@ window.MailViews=(()=>{
|
||||
function configure(options){({api,esc,formatDate,notify,user}=options);}
|
||||
async function accounts(container,isActive=()=>true){
|
||||
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';
|
||||
if(data.historyOnly)return window.MailHistoryViews.render(container,{api,esc,formatDate,notify,user,isActive});
|
||||
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex flex-wrap align-items-center gap-3"><div><h2 class="card-title mb-1">托管邮箱</h2><div class="text-secondary">SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件</div></div>${admin?'<button class="btn btn-primary ms-auto" id="mail-add">添加邮箱</button>':''}</div></div><div id="mail-editor"></div><div class="row row-cards">${data.channels.map(c=>`<div class="col-lg-6"><div class="card h-100"><div class="card-header"><h3 class="card-title">${esc(c.name)}</h3><span class="badge bg-${c.enabled?'blue':'secondary'}-lt ms-auto">${c.enabled?'收信已开启':'收信已暂停'}</span></div><div class="card-body"><div class="fw-medium mb-3">${esc(c.email)}</div><div class="d-flex gap-2 flex-wrap mb-3"><span class="badge bg-${c.state.smtp?'green':'yellow'}-lt">SMTP ${c.state.smtp?'已连接':'待检查'}</span><span class="badge bg-${c.state.imap?'green':'yellow'}-lt">IMAP ${c.state.imap?'已连接':'待检查'}</span></div><div class="text-secondary">${esc(c.state.message)}</div><div class="small text-secondary mt-2">上次检查:${formatDate(c.state.checkedAt)}<br>上次收信:${formatDate(c.state.pollAt)}</div><div class="small mt-3 text-secondary">模板发件人:${esc(c.senders.join('、'))}</div></div>${admin?`<div class="card-footer btn-list"><button class="btn btn-sm" data-edit="${c.id}">管理邮箱</button><button class="btn btn-sm" data-verify="${c.id}">检查连接</button><button class="btn btn-sm btn-primary" data-poll="${c.id}" ${c.enabled?'':'disabled'}>立即收信</button><a class="btn btn-sm" href="#templates">查看模板</a></div>`:''}</div></div>`).join('')||'<div class="col-12"><div class="card card-body text-center text-secondary py-5">尚未添加托管邮箱</div></div>'}</div><div class="card mt-3"><div class="card-body"><h3 class="card-title">用邮件提交模板</h3><p>新建邮件发送到托管邮箱,主题填写 <code>[模板][产品线]发信标题</code>,正文及附件作为模板。省略产品线时使用默认模板。</p><div class="text-secondary">发件人须在允许名单中。首次收取近 7 天邮件,新模板在“模板与收件群组”中预览确认后生效。</div></div></div><details class="card mt-3"><summary class="card-body cursor-pointer">最近收信记录(${data.receipts.length})</summary><div class="table-responsive"><table class="table card-table"><thead><tr><th>时间 / 邮箱</th><th>结果</th></tr></thead><tbody>${data.receipts.map(r=>`<tr><td class="small">${formatDate(r.at)}<div class="text-secondary">${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')}</div></td><td>${esc(r.detail)}</td></tr>`).join('')||'<tr><td colspan="2" class="text-secondary">暂无收信记录</td></tr>'}</tbody></table></div></details>${data.sends.length?`<details class="card mt-3"><summary class="card-body cursor-pointer">测试发信记录</summary><div class="table-responsive"><table class="table card-table"><tbody>${data.sends.map(s=>`<tr><td>${formatDate(s.at)}</td><td>${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')}</td><td>${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)}</td></tr>`).join('')}</tbody></table></div></details>`:''}`;
|
||||
if(!admin)return;container.querySelector('#mail-add').onclick=()=>editor();
|
||||
container.querySelectorAll('[data-edit]').forEach(b=>b.onclick=()=>editor(data.channels.find(c=>c.id===b.dataset.edit)));
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const list=value=>String(value||'').split(/[,,;;\n]/).map(v=>v.trim()).filter(Boolean);
|
||||
const dates={appDate:'申请日期',receivedAt:'接收日期',archiveDate:'归档日期'};
|
||||
function describe(rule){
|
||||
return `当流程为“${(rule.processNames||[]).join('、')||'待选择'}”、节点为“${(rule.nodeNames||[]).join('、')||'待选择'}”时,按“${rule.name||rule.categoryId}”类别识别订单。归档至“${rule.archiveDirectory||'待配置目录'}”,文件名日期使用${dates[rule.filenameDate]||'待确认日期'};本时段内同类别订单合并一封,更早历史不补发,${rule.attachPdf?'附带通知书 PDF':'不附带 PDF'}。收件人 ${(rule.to||[]).join('、')||'待配置'}。BPM 节点由人工办理。`;
|
||||
}
|
||||
function render(rule,adapters,{esc,admin,processes=[],nodes=[]}){
|
||||
const disabled=admin?'':'disabled';
|
||||
const options=(values,selected)=>[...new Set([...values,...selected])].filter(Boolean).map(v=>`<option value="${esc(v)}" ${selected.includes(v)?'selected':''}>${esc(v)}</option>`).join('');
|
||||
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 multi=(name,label,values,selected)=>`<div class="col-md-6"><label class="form-label" for="rule-${name}">${label}</label><select class="form-select" id="rule-${name}" name="${name}" multiple size="4" ${disabled}>${options(values,selected||[])}</select><div class="form-hint">可选择多项;按完整名称精确匹配。</div></div>`;
|
||||
return `<form id="order-rule-editor"><div class="card"><div class="card-header flex-wrap gap-2"><h3 class="card-title">规则编辑</h3><span class="text-secondary ms-auto">版本 ${esc(rule.version)} · ${esc(rule.categoryId)}</span></div><div class="card-body"><div class="row g-3">${text('name','规则名称',rule.name,'required maxlength="160"')}${text('categoryId','Excel 类别编号',rule.categoryId,'readonly')}${multi('processNames','适用流程',[...processes,...adapters.map(a=>a.processName)],rule.processNames)}${multi('nodeNames','触发节点',[...nodes,...adapters.flatMap(a=>[a.nodeName,a.sample?.nodeName])],rule.nodeNames)}<div class="col-12"><label class="form-label" for="rule-adapterIds">表单字段适配</label><select class="form-select" id="rule-adapterIds" name="adapterIds" multiple size="4" ${disabled}>${adapters.map(a=>`<option value="${esc(a.id)}" ${(rule.adapterIds||[]).includes(a.id)?'selected':''}>${esc(a.label||a.id)} · ${esc(a.processName||'未标注流程')} · ${a.verified?'样本结构已核验':'待核验'}</option>`).join('')}${(rule.adapterIds||[]).filter(id=>!adapters.some(a=>a.id===id)).map(id=>`<option selected value="${esc(id)}">${esc(id)} · 适配器缺失</option>`).join('')}</select></div>${text('archiveDirectory','归档目录',rule.archiveDirectory,'maxlength="1200" placeholder="完整 UNC 共享归档目录"')}<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>${text('subjectPrefix','邮件主题前缀',rule.subjectPrefix,'maxlength="200"')}${text('signature','邮件签名',rule.signature,'maxlength="4000"')}<div class="col-12"><label class="form-label" for="rule-intro">正文引导语</label><textarea class="form-control" id="rule-intro" name="intro" rows="3" maxlength="4000" ${disabled}>${esc(rule.intro)}</textarea></div><div class="col-md-6"><label class="form-label" for="rule-to">收件人</label><textarea class="form-control" id="rule-to" name="to" rows="3" maxlength="20000" ${disabled}>${esc((rule.to||[]).join('\n'))}</textarea><div class="form-hint">每行一个邮箱,也可用逗号分隔。</div></div><div class="col-md-6"><label class="form-label" for="rule-cc">抄送人</label><textarea class="form-control" id="rule-cc" name="cc" rows="3" maxlength="20000" ${disabled}>${esc((rule.cc||[]).join('\n'))}</textarea></div><div class="col-12"><label class="form-check"><input class="form-check-input" type="checkbox" name="attachPdf" ${rule.attachPdf?'checked':''} ${disabled}><span class="form-check-label">附带通知书 PDF</span></label></div></div><div class="order-rule-explanation mt-4"><strong id="order-rule-explanation-title">已保存规则的执行说明</strong><p class="mb-0 mt-2" id="order-rule-explanation">${esc(rule.explanation||describe(rule))}</p></div><div id="order-rule-dirty" class="small text-warning mt-2" role="status"></div></div>${admin?'<div class="card-footer d-flex align-items-center gap-2 flex-wrap"><span class="text-secondary small">保存生成草稿;历史批次保留原规则。</span><button class="btn btn-primary ms-auto" type="submit">保存草稿</button></div>':''}</div></form>`;
|
||||
}
|
||||
function read(form,rule){
|
||||
const result={...rule};
|
||||
for(const name of ['name','archiveDirectory','subjectPrefix','intro','signature','filenameDate'])result[name]=form.elements.namedItem(name).value.trim();
|
||||
for(const name of ['processNames','nodeNames','adapterIds'])result[name]=[...form.elements.namedItem(name).selectedOptions].map(o=>o.value);
|
||||
for(const name of ['to','cc'])result[name]=list(form.elements.namedItem(name).value);
|
||||
result.attachPdf=form.elements.namedItem('attachPdf').checked;
|
||||
return result;
|
||||
}
|
||||
window.OrderRuleEditor={render,read,describe};
|
||||
})();
|
||||
@@ -0,0 +1,18 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
const labels={orderNo:'订单号',appDate:'申请日期',customer:'客户',productLine:'产品线',quantity:'数量',changeReason:'更改原因',changeContent:'更改内容',totalAmount:'总金额',brief:'简要说明',serialNum:'通知书编号',nodeName:'节点',processName:'流程'};
|
||||
const value=v=>v===undefined||v===null?'未提供':typeof v==='object'?JSON.stringify(v):String(v);
|
||||
function panel(adapters,{esc,operator}){
|
||||
return `<section class="card"><div class="card-header"><h3 class="card-title">字段对应与样本试运行</h3></div><div class="card-body"><label class="form-label" for="order-rule-sample-source">表单样本</label><select class="form-select mb-3" id="order-rule-sample-source"><option value="">请选择表单样本</option>${adapters.map(a=>`<option value="${esc(a.id)}">${esc(a.label||a.id)}${a.sample?'':' · 暂无样本'}</option>`).join('')}</select><div id="order-rule-adapter"></div>${operator?'<label class="form-label mt-3" for="order-rule-title">BPM 原始标题</label><textarea class="form-control" id="order-rule-title" rows="3" maxlength="20000" placeholder="粘贴标题,例如:毛利:绿标订单号:148396机芯号:…"></textarea><div class="form-hint">填写后以此标题生成正文;每个订单号单独一段,只保留订单号、机芯号、产品型号、客户简称、总数量、订单类别。留空沿用样本。</div><details class="mt-3" id="order-rule-advanced"><summary>高级:查看或替换 JSON 样本</summary><label class="form-label mt-3" for="order-rule-sample">待校验 JSON 样本</label><textarea class="form-control font-monospace" id="order-rule-sample" rows="8" maxlength="80000"></textarea></details><p class="small text-secondary mt-3">校验使用已保存的规则。预览不会创建订单、归档文件、办理 BPM 或发送邮件。</p><button class="btn" type="button" id="order-rule-preview">校验已保存规则</button>':'<div class="text-secondary small mt-3">操作员和管理员可运行样本校验;当前账号仅查看字段对应。</div>'}<div id="order-rule-preview-result" class="mt-3" aria-live="polite"></div></div></section>`;
|
||||
}
|
||||
function adapter(a,{esc}){
|
||||
if(!a)return '<p class="text-secondary">选择表单后显示业务字段、来源路径及样本值。</p>';
|
||||
const fields=Array.isArray(a.fields)?a.fields.map(f=>[f.key,f]):Object.entries(a.fields||{});
|
||||
return `<div class="small mb-3">${esc(a.processName||'流程未标注')} · ${a.verified?'样本字段结构已核验':'样本字段结构待核验'}<br><span class="text-secondary">演示样本用于理解字段;发布需真实业务样本校验,且不代表实时接入已完成。</span></div><div class="table-responsive"><table class="table table-sm order-rule-fields"><thead><tr><th>业务字段</th><th>来源路径</th><th>样本值</th></tr></thead><tbody>${fields.map(([key,f])=>{const field=typeof f==='string'?{path:f}:f||{},p=field.path||field.xdatabind||field.bind||'';const v=a.sample?.fields?.[p]??a.sample?.[p];return `<tr><td>${esc(field.label||labels[key]||key)}</td><td><code>${esc(p||'未映射')}</code></td><td class="text-break">${esc(value(v))}</td></tr>`;}).join('')||'<tr><td colspan="3" class="text-secondary">暂无字段映射</td></tr>'}</tbody></table></div>`;
|
||||
}
|
||||
function result(r,{esc,demo=false}){
|
||||
const title=r.event?.rawTitle!==undefined?`<section class="card mb-3"><div class="card-body"><h4>标题提取结果</h4><pre style="white-space:pre-wrap;overflow-wrap:anywhere">${esc(r.event.brief||'')}</pre>${r.event.factoryHints?.length?`<div class="alert alert-warning">惠州线索待核实:${r.event.factoryHints.map(h=>esc(h.source+':'+h.value)).join(';')}。额外通知要求尚未确认,不会自动多发。</div>`:''}<details><summary>查看 BPM 原始标题</summary><div class="text-break mt-2">${esc(r.event.rawTitle)}</div></details></div></section>`:'';
|
||||
return title+`<div class="alert alert-${r.valid?'success':'warning'}">${r.valid?'样本校验通过':'样本校验未通过'}${r.ruleId?' · 命中规则 '+esc(r.ruleId):''}</div>${demo?'<div class="alert alert-warning">本次使用演示样本,仅校验字段结构,不能作为规则发布的真实业务样本。</div>':''}${r.issues?.length?`<ul class="text-danger">${r.issues.map(issue=>`<li>${esc(typeof issue==='string'?issue:issue.message||issue.detail||JSON.stringify(issue))}</li>`).join('')}</ul>`:''}${r.explanation?`<p class="order-rule-explanation">${esc(r.explanation)}</p>`:''}${r.checks?.length?`<div class="list-group list-group-flush mb-3">${r.checks.map(c=>`<div class="list-group-item px-0"><span class="badge bg-${c.ok?'green':'yellow'}-lt me-2">${c.ok?'通过':'待处理'}</span>${esc(c.label)}<div class="small text-secondary mt-1">${esc(c.detail)}</div></div>`).join('')}</div>`:''}${r.fieldTrace?.length?`<div class="table-responsive"><table class="table table-sm order-rule-fields"><thead><tr><th>业务字段</th><th>来源路径</th><th>实际值</th></tr></thead><tbody>${r.fieldTrace.map(f=>`<tr><td>${esc(f.label||labels[f.key]||f.key)}</td><td><code>${esc(f.path)}</code></td><td class="text-break">${esc(value(f.value))}</td></tr>`).join('')}</tbody></table></div>`:''}`;
|
||||
}
|
||||
window.OrderRulePreview={panel,adapter,result};
|
||||
})();
|
||||
@@ -0,0 +1,73 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
let api,esc,formatDate,notify,user;
|
||||
const tabs={workbench:'工作台',rules:'通知规则',pending:'待发批次',orders:'订单记录',history:'发送记录',settings:'设置'};
|
||||
const statuses={draft:'草稿',enabled:'已发布',paused:'已暂停',identified:'已识别',preparing:'准备中',archived:'已归档',pending:'待发',batched:'已编入批次',blocked:'受阻',prepared:'已准备',sending:'发送中',sent:'已提交邮件服务器',failed:'失败',unknown:'结果待核实',cancelled:'已取消',ignored:'更早历史,不补发'};
|
||||
const status=s=>`<span class="badge bg-${['unknown','blocked','failed'].includes(s)?'yellow':s==='sent'?'green':'secondary'}-lt">${esc(statuses[s]||s||'未记录')}</span>`;
|
||||
const empty=text=>`<div class="order-rules-empty text-secondary">${esc(text)}</div>`;
|
||||
const table=(heads,rows,none)=>`<div class="table-responsive"><table class="table card-table order-rules-table"><thead><tr>${heads.map(h=>`<th>${h}</th>`).join('')}</tr></thead><tbody>${rows.join('')||`<tr><td colspan="${heads.length}">${empty(none)}</td></tr>`}</tbody></table></div>`;
|
||||
const list=v=>(v||[]).join('、')||'未配置';
|
||||
const capabilityNames={liveTodo:'实时待办接入',pdfExport:'通知书 PDF 导出',automaticArchive:'自动归档'};
|
||||
const ready=c=>Object.keys(capabilityNames).every(k=>c[k]===true);
|
||||
function capabilities(c){return `<div class="order-rule-capabilities">${Object.entries(capabilityNames).map(([key,label])=>`<div><span class="badge bg-${c[key]===true?'green':'yellow'}-lt">${c[key]===true?'已就绪':'待联调'}</span><span>${label}</span></div>`).join('')}</div>`;}
|
||||
async function render(container,isActive=()=>true){
|
||||
const [snapshot,mail]=await Promise.all([api('/order-rules'),api('/mail').catch(()=>({channels:[]}))]);if(!isActive())return;
|
||||
const data={rules:[],adapters:[],orders:[],batches:[],audit:[],settings:{},capabilities:{},...snapshot},admin=user.role==='admin',operator=user.role!=='viewer';
|
||||
let tab='workbench',selectedId=data.rules[0]?.id,dirty=false,refreshing=false,timer;
|
||||
container.innerHTML=`<div class="order-rules"><div id="order-rule-state" class="alert alert-${data.settings.enabled?'success':'info'}">分类通知${data.settings.enabled?'已启用':'自动执行已暂停'}。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。</div><div class="order-rule-tabs mb-3" role="group" aria-label="规则中心页面">${Object.entries(tabs).map(([id,label])=>`<button class="btn ${id===tab?'btn-primary':''}" type="button" data-rule-tab="${id}">${label}</button>`).join('')}</div><div class="d-flex flex-wrap gap-2 align-items-center mb-3"><span class="small text-secondary" id="order-rule-updated" aria-live="polite">时段与运行状态每 15 秒刷新</span><button class="btn btn-sm ms-auto" type="button" id="order-rule-refresh">刷新时段与状态</button></div><div id="order-rules-feedback" role="alert" aria-live="polite"></div><div id="order-rules-panel"></div></div>`;
|
||||
const panel=container.querySelector('#order-rules-panel');
|
||||
const feedback=(message,type='success')=>{if(!isActive())return;const node=container.querySelector('#order-rules-feedback');node.textContent=message;node.className='alert alert-'+type;};
|
||||
async function action(button,work){if(button)button.disabled=true;try{await work();}catch(error){feedback(error.message,'danger');}finally{if(button?.isConnected)button.disabled=false;}}
|
||||
async function reload(){const fresh=await api('/order-rules');if(!isActive())return false;Object.assign(data,fresh);syncState();dirty=false;draw();return true;}
|
||||
function syncState(){const node=container.querySelector('#order-rule-state');node.className='alert alert-'+(data.settings.enabled?'success':'info');node.textContent='分类通知'+(data.settings.enabled?'已启用':'自动执行已暂停')+'。按 Excel 类别汇总,本时段内同类别订单合并一封,更早历史不补发;通知与更改单独归类,BPM 节点由人工办理。';}
|
||||
function keepInputs(){return dirty||tab==='rules'||tab==='settings'||[...panel.querySelectorAll('textarea')].some(input=>input.value.trim());}
|
||||
async function refreshStatus(){if(refreshing)return;refreshing=true;try{const fresh=await api('/order-rules');if(!isActive())return;Object.assign(data,fresh);syncState();container.querySelector('#order-rule-updated').textContent='时段与状态更新于 '+formatDate(new Date().toISOString());if(!keepInputs())draw();}finally{refreshing=false;}}
|
||||
function ordersTable(orders){return table(['订单 / 类别','状态与原因','接收时间'],orders.map(o=>`<tr><td><strong>${esc(o.orderNo||o.event?.orderNo||'订单号未提供')}</strong><div class="small text-secondary">${esc(data.rules.find(r=>r.categoryId===o.categoryId)?.name||o.categoryId||'未分类')}</div><details class="mt-2"><summary class="small">查看订单信息</summary><div class="small order-rule-record mt-2">流程:${esc(o.processName||o.event?.processName||'—')}<br>节点:${esc(o.nodeName||o.event?.nodeName||'—')}<br>流程实例:${esc(o.instanceId||o.event?.instanceId||'—')}<br>任务:${esc(o.taskId||o.event?.taskId||'—')}<br>来源版本:${esc(o.revision||o.event?.revision||'—')}<br>规则版本:${esc(o.ruleVersion??'—')}<br>数量:${esc(o.quantity??o.event?.quantity??'—')}<br>${esc(o.brief||o.event?.brief||'')}</div></details></td><td>${status(o.status)}${o.error||o.reason?`<div class="small text-danger mt-2">${esc(o.error||o.reason)}</div>`:''}${admin&&!o.batchId&&['pending','blocked'].includes(o.status)?`<details class="mt-3"><summary class="small">按当前发布规则重新核对</summary><form data-rule-recheck="${esc(o.id)}" class="mt-2"><p class="small text-secondary">重新匹配会清除原归档证据,需重新校验和归档;更早历史仍不补发。</p><label class="form-label" for="rule-recheck-${esc(o.id)}">重新核对依据</label><textarea class="form-control mb-2" id="rule-recheck-${esc(o.id)}" name="note" rows="2" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">重新核对此订单</button></form></details>`:''}</td><td class="small text-secondary">${formatDate(o.receivedAt||o.event?.receivedAt||o.createdAt)}</td></tr>`),'暂无订单记录。样本预览不会创建订单。');}
|
||||
function batchesTable(batches,pending){return table(['类别 / 主题','订单与收件人','状态'],batches.map(b=>`<tr><td><strong>${esc(b.subject||b.categoryId)}</strong><div class="small text-secondary mt-1">${esc(b.categoryId)} · ${formatDate(b.createdAt)}</div><details class="mt-2"><summary class="small">查看冻结内容</summary><div class="order-rule-record small mt-2">业务时段:${formatDate(b.windowStart)} 至 ${formatDate(b.windowEnd||b.cutoff)}<br>收件人:${esc(list(b.to))}<br>抄送:${esc(list(b.cc))}<br>附件:${esc((b.attachments||[]).map(a=>a.name||a.filename).join('、')||'无')}<pre class="notification-brief mt-2">${esc(b.text||'')}</pre></div></details></td><td class="small">${esc(list(b.orderNos||b.orderIds))}<div class="text-secondary mt-2">${esc(list(b.to))}</div></td><td>${status(b.status)}${b.error?`<div class="small text-danger mt-2">${esc(b.error)}</div>`:''}${b.status==='unknown'&&admin?`<form class="mt-3" data-rule-resolve="${esc(b.id)}"><label class="form-label" for="rule-resolution-${esc(b.id)}">人工核验结论</label><select class="form-select mb-2" id="rule-resolution-${esc(b.id)}" name="resolution"><option value="sent">已核实邮件服务器接受</option><option value="retry">已核实未发送,允许重试</option></select><label class="form-label" for="rule-resolution-note-${esc(b.id)}">核验依据</label><textarea class="form-control mb-2" id="rule-resolution-note-${esc(b.id)}" name="note" rows="2" required minlength="5" maxlength="2000"></textarea><button class="btn btn-sm" type="submit">保存核验结论</button></form>`:''}</td></tr>`),pending?'暂无待发批次':'暂无发送记录');}
|
||||
function windowInfo(){const w=data.window;return w&&Number.isFinite(Date.parse(w.start))&&Number.isFinite(Date.parse(w.end))&&Date.parse(w.start)<Date.parse(w.end)?w:null;}
|
||||
function inWindow(order){const w=windowInfo(),at=Date.parse(order.receivedAt||order.event?.receivedAt);return !!w&&Number.isFinite(at)&&at>=Date.parse(w.start)&&at<Date.parse(w.end);}
|
||||
function windowCard(prepare=false){const w=windowInfo();return `<section class="card mb-3"><div class="card-header"><h3 class="card-title">本时段范围</h3>${w?`<span class="text-secondary small ms-auto">${esc(w.label||'配置发送时段')}</span>`:''}</div><div class="card-body">${w?`<strong>${formatDate(w.start)} 至 ${formatDate(w.end)}</strong><div class="small text-secondary mt-2">以订单接收时间归入时段。本时段内同类别订单合并一封,更早历史不补发。</div>`:`<div class="text-secondary">${esc(data.window?.error||'当前没有已确认的发送时段。请先确认发送计划及工作日规则。')}</div>`}${prepare&&admin?`<form id="order-rule-prepare" class="mt-3"><button class="btn" type="submit" ${!w||w.available!==true?'disabled':''}>整理本时段批次</button><div class="form-hint">${w&&w.available!==true?'未到配置发送时点,当前只预览。':''}按服务器确定的时段整理已接入订单并冻结规则和附件,不发送邮件。缺少归档证据时将阻塞该类别。</div></form>`:''}</div></section>`;}
|
||||
function windowOrders(){const groups=new Map();for(const order of data.orders.filter(o=>inWindow(o)&&['pending','blocked','archived','preparing','identified'].includes(o.status))){const id=order.categoryId||'未分类';if(!groups.has(id))groups.set(id,[]);groups.get(id).push(order);}return `<div class="card mb-3"><div class="card-header"><h3 class="card-title">本时段订单 · 按类别预览</h3></div>${groups.size?[...groups.entries()].map(([id,orders])=>`<section><div class="px-4 pt-3"><strong>${esc(data.rules.find(r=>r.categoryId===id)?.name||id)}</strong><span class="small text-secondary ms-2">${orders.length} 单</span></div>${ordersTable(orders)}</section>`).join(''):empty('本时段暂无待整理订单;更早历史不计入。')}</div>`;}
|
||||
function drawWorkbench(){
|
||||
panel.innerHTML=`${windowCard()}<div class="workspace-metrics">${[['已发布规则',data.rules.filter(r=>r.publishedVersion||r.status==='enabled').length],['本时段待发订单',data.orders.filter(o=>inWindow(o)&&['pending','batched'].includes(o.status)).length],['本时段受阻订单',data.orders.filter(o=>inWindow(o)&&o.status==='blocked').length],['结果待核实',data.batches.filter(b=>b.status==='unknown').length]].map(([label,count])=>`<div class="card"><div class="card-body"><div class="text-secondary">${label}</div><div class="metric-number">${count}<span>项</span></div></div></div>`).join('')}</div><div class="card mb-3"><div class="card-header"><h3 class="card-title">接入状态</h3></div><div class="card-body">${capabilities(data.capabilities)}<p class="text-secondary small mb-0 mt-3">规则草稿和样本试运行可独立配置;自动执行需全部接入就绪并由管理员启用。样本结构核验不等于实时接口验证。</p></div></div><div class="card"><div class="card-header"><h3 class="card-title">本时段受阻订单</h3></div>${ordersTable(data.orders.filter(o=>inWindow(o)&&o.status==='blocked'))}</div>`;
|
||||
}
|
||||
function drawRules(){
|
||||
if(!data.rules.length){panel.innerHTML=`<div class="card">${empty('暂无分类规则,请先导入经确认的 Excel 分类。')}</div>`;return;}
|
||||
const rule=data.rules.find(r=>r.id===selectedId)||data.rules[0];selectedId=rule.id;
|
||||
panel.innerHTML=`<div class="order-rules-layout"><aside class="card order-rule-list"><div class="card-header"><h3 class="card-title">Excel 分类 · ${data.rules.length}</h3></div><div class="list-group list-group-flush">${data.rules.map(r=>`<button class="list-group-item list-group-item-action ${r.id===rule.id?'active':''}" type="button" data-rule-id="${esc(r.id)}"><strong>${esc(r.name)}</strong><div class="small mt-2">${status(r.status)} <span class="text-secondary">v${esc(r.version)}${r.hasDraft?' · 有草稿':''}</span></div></button>`).join('')}</div></aside><div class="order-rule-main"><div class="d-flex gap-2 flex-wrap align-items-center mb-3"><span class="small text-secondary">已发布版本:${esc(rule.publishedVersion??'无')} · Excel 行 ${esc(rule.sourceRow??'—')}</span>${admin?`<button type="button" class="btn btn-sm ms-auto" id="order-rule-publish">发布此版本</button><button type="button" class="btn btn-sm" id="order-rule-pause" ${!rule.publishedVersion||rule.status==='paused'?'disabled':''}>暂停此规则</button>`:''}</div>${rule.validationIssues?.length?`<div class="alert alert-warning">发布前待补全:${rule.validationIssues.map(v=>esc(typeof v==='string'?v:v.message||JSON.stringify(v))).join(';')}</div>`:''}${window.OrderRuleEditor.render(rule,data.adapters,{esc,admin,processes:data.rules.flatMap(r=>r.processNames||[]),nodes:data.rules.flatMap(r=>r.nodeNames||[])})}<div class="mt-3">${window.OrderRulePreview.panel(data.adapters,{esc,operator})}</div></div></div>`;
|
||||
const form=panel.querySelector('#order-rule-editor');
|
||||
function changed(){dirty=true;panel.querySelector('#order-rule-explanation-title').textContent='当前表单的执行说明(尚未保存)';panel.querySelector('#order-rule-explanation').textContent=window.OrderRuleEditor.describe(window.OrderRuleEditor.read(form,rule));panel.querySelector('#order-rule-dirty').textContent='有未保存的修改。保存草稿后再校验或发布。';for(const id of ['#order-rule-publish','#order-rule-preview','#order-rule-pause']){const button=panel.querySelector(id);if(button)button.disabled=true;}}
|
||||
if(admin){form.oninput=changed;form.onchange=changed;form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/rules',window.OrderRuleEditor.read(form,rule));if(await reload())feedback('规则草稿已保存。');});};
|
||||
panel.querySelector('#order-rule-publish').onclick=e=>action(e.currentTarget,async()=>{await api('/order-rules/rules/'+encodeURIComponent(rule.id)+'/publish',{version:rule.version});if(await reload())feedback('规则版本已发布。自动执行仍由全局设置与接入状态控制。');});
|
||||
panel.querySelector('#order-rule-pause').onclick=e=>action(e.currentTarget,async()=>{await api('/order-rules/rules/'+encodeURIComponent(rule.id)+'/pause',{version:rule.version});if(await reload())feedback('此规则已暂停。');});
|
||||
}
|
||||
panel.querySelectorAll('[data-rule-id]').forEach(button=>button.onclick=()=>{if(dirty){feedback('当前规则有未保存修改,请先保存草稿或刷新页面放弃修改。','warning');return;}selectedId=button.dataset.ruleId;drawRules();});
|
||||
const source=panel.querySelector('#order-rule-sample-source');
|
||||
const preferred=(rule.adapterIds||[]).find(id=>data.adapters.some(a=>a.id===id&&a.sample));source.value=preferred||'';
|
||||
function choose(){const a=data.adapters.find(a=>a.id===source.value);panel.querySelector('#order-rule-adapter').innerHTML=window.OrderRulePreview.adapter(a,{esc});const input=panel.querySelector('#order-rule-sample');if(input)input.value=a?.sample?JSON.stringify(a.sample,null,2):'';panel.querySelector('#order-rule-preview-result').innerHTML='';}source.onchange=choose;choose();
|
||||
if(operator)panel.querySelector('#order-rule-preview').onclick=e=>action(e.currentTarget,async()=>{let sample;try{sample=JSON.parse(panel.querySelector('#order-rule-sample').value);}catch{throw Error('请选择样本,或在高级选项中提供有效的 JSON 对象。');}if(!sample||typeof sample!=='object'||Array.isArray(sample))throw Error('样本必须是 JSON 对象。');const title=panel.querySelector('#order-rule-title').value;if(title.trim())sample.title=title;const result=await api('/order-rules/preview',{sample});if(!isActive()||tab!=='rules'||selectedId!==rule.id||panel.querySelector('#order-rule-editor')!==form)return;panel.querySelector('#order-rule-preview-result').innerHTML=window.OrderRulePreview.result(result,{esc,demo:sample.demo===true});});
|
||||
}
|
||||
function drawSettings(){
|
||||
const config=data.settings,canEnable=ready(data.capabilities),disabled=admin?'':'disabled';
|
||||
panel.innerHTML=`<form class="card settings-width" id="order-rule-settings"><div class="card-header"><h3 class="card-title">分类通知设置</h3></div><div class="card-body">${capabilities(data.capabilities)}${!canEnable?'<div class="alert alert-info mt-3">自动执行待联调。可保存邮箱与附件大小限制;全部接入验证通过后才可启用。</div>':''}<div class="row g-3 mt-1"><div class="col-md-6"><label class="form-label" for="order-rule-channel">分类通知发件邮箱</label><select class="form-select" name="channelId" id="order-rule-channel" ${disabled}><option value="">请选择托管邮箱</option>${(mail.channels||[]).map(c=>`<option value="${esc(c.id)}" ${c.id===config.channelId?'selected':''}>${esc(c.name)} · ${esc(c.email)}</option>`).join('')}${config.channelId&&!(mail.channels||[]).some(c=>c.id===config.channelId)?`<option selected value="${esc(config.channelId)}">原邮箱 ${esc(config.channelId)} · 请核实可用性</option>`:''}</select><div class="form-hint"><a href="#mail">管理邮箱</a></div></div><div class="col-md-6"><label class="form-label" for="order-rule-max-size">单封邮件上限(MiB)</label><input class="form-control" type="number" name="maxSize" id="order-rule-max-size" min="1" max="100" step="0.5" required value="${Number(config.maxMessageBytes||20971520)/1048576}" ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="order-rule-enabled" name="enabled" ${config.enabled?'checked':''} ${!admin||!canEnable?'disabled':''}><span class="form-check-label">启用自动分类通知</span></label></div></div><hr><p class="small text-secondary mb-0">发送时段与工作日可在 <a href="#schedule">发送计划</a>、<a href="#calendar">业务日历</a> 配置。本规则中心按配置时段内的 Excel 类别汇总,更早历史不补发;原通知模块的产品线 / 单订单整理选项仅供兼容模块使用。</p></div>${admin?'<div class="card-footer text-end"><button class="btn btn-primary" type="submit">保存分类通知设置</button></div>':''}</form>`;
|
||||
if(admin)panel.querySelector('form').onsubmit=e=>{e.preventDefault();const form=e.currentTarget;return action(e.submitter,async()=>{await api('/order-rules/settings',{version:config.version,channelId:form.elements.channelId.value,maxMessageBytes:Math.round(Number(form.elements.maxSize.value)*1048576),enabled:canEnable&&form.elements.enabled.checked});if(await reload())feedback('分类通知设置已保存。');});};
|
||||
}
|
||||
function draw(){
|
||||
if(!isActive())return;
|
||||
if(tab==='workbench')drawWorkbench();else if(tab==='rules')drawRules();else if(tab==='settings')drawSettings();
|
||||
else if(tab==='orders')panel.innerHTML=`<div class="card"><div class="card-header"><h3 class="card-title">订单记录 · ${data.orders.length}</h3></div>${ordersTable(data.orders)}</div>`;
|
||||
else if(tab==='pending')panel.innerHTML=`${windowCard(true)}${windowOrders()}<div class="card"><div class="card-header"><h3 class="card-title">本时段待发批次</h3></div>${batchesTable(data.batches.filter(b=>{const w=windowInfo();return w&&['prepared','sending','unknown','failed'].includes(b.status)&&Date.parse(b.windowStart)===Date.parse(w.start)&&Date.parse(b.windowEnd||b.cutoff)===Date.parse(w.end);}),true)}</div>`;
|
||||
else if(tab==='history')panel.innerHTML=`<div class="alert alert-info">“已提交邮件服务器”表示 SMTP 接受,不代表最终送达。结果不明的批次须人工核实。</div><div class="card mb-3"><div class="card-header"><h3 class="card-title">发送记录</h3></div>${batchesTable(data.batches.filter(b=>['sent','cancelled','failed','unknown'].includes(b.status)),false)}</div><div class="card"><div class="card-header"><h3 class="card-title">规则与执行操作记录</h3></div>${table(['时间','操作人 / 操作','说明'],data.audit.map(a=>`<tr><td class="small">${formatDate(a.at||a.createdAt)}</td><td>${esc(a.actor?.username||a.actor||'系统')}<div class="small text-secondary">${esc(a.action)}</div></td><td class="small text-break">${esc(typeof a.detail==='object'?JSON.stringify(a.detail):a.detail||a.note||'')}</td></tr>`),'暂无操作记录')}</div>`;
|
||||
const prepare=panel.querySelector('#order-rule-prepare');if(prepare)prepare.onsubmit=e=>{e.preventDefault();const w=windowInfo();if(!w||w.available!==true)return;return action(e.submitter,async()=>{await api('/order-rules/prepare',{cutoff:w.end});if(await reload())feedback('本时段批次整理已完成,请查看实际批次与受阻原因。');});};
|
||||
panel.querySelectorAll('[data-rule-recheck]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/orders/'+encodeURIComponent(form.dataset.ruleRecheck)+'/recheck',{note:form.elements.note.value});if(await reload())feedback('此订单已重新核对,请检查新匹配结果及归档状态。');});});
|
||||
panel.querySelectorAll('[data-rule-resolve]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/order-rules/batches/'+encodeURIComponent(form.dataset.ruleResolve)+'/resolve',{resolution:form.elements.resolution.value,note:form.elements.note.value});if(await reload())feedback('核验结论已保存。');});});
|
||||
}
|
||||
container.querySelectorAll('[data-rule-tab]').forEach(button=>button.onclick=()=>{if(dirty){feedback('当前规则有未保存修改,请先保存草稿或刷新页面放弃修改。','warning');return;}return action(button,async()=>{const fresh=await api('/order-rules');if(!isActive())return;Object.assign(data,fresh);syncState();tab=button.dataset.ruleTab;container.querySelectorAll('[data-rule-tab]').forEach(b=>b.classList.toggle('btn-primary',b===button));draw();});});
|
||||
container.querySelector('#order-rule-refresh').onclick=e=>action(e.currentTarget,async()=>{await refreshStatus();});
|
||||
const stopRefresh=()=>{clearInterval(timer);window.removeEventListener('pagehide',stopRefresh);};
|
||||
timer=setInterval(()=>{if(!isActive()){stopRefresh();return;}if(!dirty&&!document.hidden)refreshStatus().catch(error=>feedback(error.message,'danger'));},15000);
|
||||
window.addEventListener('pagehide',stopRefresh,{once:true});
|
||||
draw();
|
||||
}
|
||||
window.OrderRuleViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render};
|
||||
})();
|
||||
Reference in new issue
Block a user