feat(records): add source history and Tabler record ledgers

This commit is contained in:
abaishu0730 committed 2026-10-20 17:34:17 +08:00
1 parent 1421edd6d4
commit 20bb68615f
27 files changed
+291 -91

No files matched your search

+6
View File
@@ -1,5 +1,11 @@
# 开发交接(2026-10-20)
## 本轮订单与导出记录台账
用户选择A台账方案,确认删除连接后记录自动进入历史归档、默认聚焦订单相关流程。已实现统一Tabler分段导航(`#records`/`#records-pdf`)、分页台账、来源与日期筛选、详情侧栏和窄屏布局。Workspace删除事务保留安全来源档案;旧孤立来源不猜账号。PDF导出状态、文件可用性和存储归档回执独立,缺失或越界文件不显示下载;不按订单号猜BPM连接归属。
专项回归50项通过,最终页面回归7项通过,新鲜完整514项中513通过、0失败、1可选ZCode CLI跳过;249个JS/CJS文件语法、6份文档33条本地链接及差异检查通过。本机实例已停服并保护备份,恢复核验随后补记。最终结果和恢复记录见[台账验收](records-ledger-verification-2026-10-20.md),设计与步骤见[已确认设计](superpowers/specs/2026-10-20-records-ledger-design.md)及[实施计划](superpowers/plans/2026-10-20-records-ledger.md)。保持自动通知false、version:1,不发真实邮件、不办理BPM、不操作服务机,保留账号/密钥/原业务数据和当前分支,不推送合并。
## 本轮BPM系统设置改造
用户已确认BPM可恢复启停、轻量连接检测和原生被动监听方案,本轮在既有本机测试工作树顺序实施。连接停用改为保留账号/会话的暂停,启用恢复检查;真正删除才清除身份。卡片分别显示登录会话、订单接口与到达监听状态,后台复用近期成功业务请求,明确区分认证过期、权限不足和网络失败。
+2
View File
@@ -10,6 +10,8 @@
业务横栏:分类通知规则、字段映射。系统横栏:BPM连接、邮箱管理、存储服务器、助手设置、系统健康、团队账号、操作记录。团队账号仅管理员可见;个人改密在右上角。助手主页面只保留对话和授权操作卡片。
订单与导出记录采用用户确认的A台账方案:顶部流程到达记录/PDF导出记录复用同一Tabler分段导航,对应`#records`/`#records-pdf`。到达记录默认现有连接、订单相关流程及全部到达类型,统一表格每页25条;来源与日期放更多筛选,长标题和完整来源信息在详情侧栏。历史是累计到达台账,不宣称当前待办。删除BPM连接在同一事务保留安全来源档案,关联记录进入历史归档;停用仍属现有来源,旧孤立来源保留ID且不猜账号。PDF导出状态、本地文件可下载与实际存储归档回执分别显示,无连接关联时不按订单号猜测归属。详见[台账设计](superpowers/specs/2026-10-20-records-ledger-design.md)及[验收](records-ledger-verification-2026-10-20.md)。
表单离开保护提供保存并继续/放弃/留下;密码、新建账号等敏感或不可自动提交表单只允许放弃或留下。刷新受浏览器原生 beforeunload 保护,不可能自定义其三个按钮。提交禁重、错误保留输入;持久保存与刷新失败分别提示;旧页/旧登录响应不得覆盖当前页面。
## 唯一业务分类与窗口
@@ -0,0 +1,28 @@
# 订单与导出记录台账验收
日期:2026-10-20(北京时间)。基线`1421edd`;指定工作树`C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支`codex/modular-refactor`。用户选择[设计A](superpowers/specs/2026-10-20-records-ledger-design.md),并确认删除连接转历史、默认订单相关。只更新本机测试实例,自动发信保持暂停,不发真实邮件、不办理BPM、不操作服务机、不推送合并。
## 实际行为
- `#records`/`#records-pdf`共用Tabler分段导航,可刷新、前后退及直达;查询输入不触发业务表单的未保存保护。
- 到达台账默认现有来源、订单相关、全部类型。订单相关精确取分类目录与已配置规则,包含暂停规则;其他流程保留在全部流程筛选。每页25条,长标题截断,完整标题、来源及观察时间在详情。
- 删除连接时,同一Workspace事务保留安全来源档案;停用仍在现有来源。新到达保存首次来源快照,重扫保留。旧孤立记录仍可查,未记录的账号/删除时间不推断。归档列表不提供同步动作。
- 到达时间、首次采集、最近观察各自显示;累计记录不冒充当前待办。旧日期分组API保持兼容,新ledger模式提供明确的分页和范围。
- PDF导出完成、本地文件可下载、持久存储归档分别显示。缺失/越界/不是PDF的文件不能下载;归档结果按任务查询完整回执,不用最近100条窗口猜测。没有可靠BPM来源关联的导出任务保持独立。
- 后台状态刷新保留筛选输入与页码;PDF加载迟到不能吞掉用户搜索。详情使用Tabler Offcanvas,离页清理;窄屏保留详情操作,辅助字段合并到主信息或详情。
## 证据
- 修改前观察失败:台账查询缺失、归档来源丢失、PDF缺失仍可下载,以及旧页面没有统一导航和详情。
- 后端、HTTP、存储和导航专项50项通过;日志`output-records-focused-final.log`。额外慢响应回归先失败后通过,确认加载过程中输入的搜索仍会发送;日志`output-records-race-red.log`/`output-records-race-green.log`。
- 真实本地SQLite验证跨重启归档、停用不归档、旧来源、首次身份快照、精确业务筛选及日期/分页。真实临时文件验证PDF下载边界,真实持久回执验证超过100条历史仍可查询。
- 最终真实浏览器回归7项通过,覆盖统一导航、详情、后台新记录、搜索、原权限、历史范围、扫描服务失败时PDF入口、直接刷新PDF页、关闭详情后跳页及390px布局;661px到达表格检查详情按钮位于视口内。隔离样例用于视觉复查,发现并修正窄屏操作列被挤出视口;最终业务页面截图随本机恢复补记。
- `npm ci`成功,锁定依赖未变。最终249个JS/CJS文件语法检查通过,`git diff --check`通过;6份相关文档33条本地链接均存在。
- 新鲜完整`npm test`:514项,513通过、0失败、0取消、1项可选ZCode CLI跳过,退出码0,耗时875,750.9513毫秒(约14分36秒);日志`output-records-full-test.log`。完整套件启动后没有修改业务源码。
- 本地复核确认:来源档案只保留安全身份字段,真正删除仍清除凭据;历史源ID不会重新挂靠新连接。新旧API并存,来源归档不改变PDF或业务执行状态;实际下载复用文件边界检查,页面查询不读取SMB或发起归档/发送。后台查询与业务保存分离,离页清理详情和定时器。
## 本机数据与服务
修改前自动通知`enabled:false`、`version:1`,用户1个、采样31份、字段草稿31份、批次0个。已停止原本机测试实例,完整保护备份在`%LOCALAPPDATA%/OrderNotificationAutomationBackups/records-ledger-20261020-165333`;7257个文件摘要匹配、12份SQLite quick_check通过,未读取或复制account-recovery。证据:`output/records-ledger-backup-verification.json`。
全量测试通过后恢复原实例,并核对原账号、密钥、规则、采样、草稿、订单、批次、双端口和暂停状态。Workspace新增来源档案表为预期迁移,不删除到达记录、不搬动PDF、不更改既有业务设置。
@@ -0,0 +1,39 @@
# 订单与导出记录台账 Implementation Plan
> **For agentic workers:** 使用 executing-plans 在当前会话顺序实施,不自动分派子代理。用户已选择A并确认归档与默认业务范围,不重复请求批准。
**Goal:** 交付可追溯历史来源、清楚文件状态的Tabler台账页面。
**Architecture:** Workspace在删除事务中保留安全来源档案;到达查询模块将档案与旧记录结合,在SQLite分页和筛选。PDF记录查询单独核验本地文件与持久回执。两页接入现有路由导航和统一详情侧栏,执行/发送引擎不改。
**Tech Stack:** 既有Node、SQLite、原生JS、Tabler 1.6.1及Playwright;不增加依赖。
**Spec:** [已确认设计](../../superpowers/specs/2026-10-20-records-ledger-design.md)。仅指定modular-refactor工作树开发,原共享检出不改。
## Task 1:历史来源和台账查询
- [x] 先写并观察失败测试:删除后名称/账号可追溯、停用保留正常范围、旧孤立来源不猜身份、跨重启、精确业务筛选和稳定分页。
- [x] Workspace删除事务保留安全来源档案;采集保存首次来源快照。新增records-query,扩展scan-store分页读取,旧日期分组接口兼容。
- [x] scan-api装配分类目录与安全来源,新增ledger模式;历史查询不产生远端动作,权限保持。
- [x] 运行专项回归并复核删除/在途工作协调。
## Task 2:PDF可用性和归档回执
- [x] 先写并观察失败测试:成功任务文件缺失、真实文件可下载、越界/链接拒绝、空记录、分页和真实归档回执。
- [x] 独立job-records模块复用受限文件定位,按分页核验本地文件;storage按jobId查询完整持久回执,避免最近100条窗口误判。
- [x] dashboard保留原API结构并提供ledger分页;概览下载状态使用同一核验,不更改导出/归档动作。
- [x] 运行HTTP、文件与存储专项回归。
## Task 3:两页Tabler台账
- [x] 先更新/新增真实浏览器回归,观察缺失统一导航、默认业务筛选、历史范围和详情的失败。
- [x] 统一nav-segmented路由,保留#records并新增#records-pdf;流程台账与PDF页面分别管理筛选、分页、加载和错误状态。
- [x] 详情侧栏使用Tabler;列表长标题截断,完整内容按需展开;离页销毁定时器/详情,后台刷新不覆盖用户输入或跳回第一页。
- [x] 测试权限、空态、后台更新、延迟响应、后退/刷新直达和窄屏。
## Task 4:验收和本机交付
- [ ] 同步设计要求、操作清单、HANDOFF及验收记录;本地评审来源追溯、文件边界与页面生命周期。
- [ ] npm ci、全量npm test、所有JS/CJS语法、文档链接及git diff --check;提交代码。
- [ ] 停服保护备份并恢复原本机服务,核对双端口、原身份/数据、真实页面及自动通知false/version1;不操作服务机、不发真实邮件、不办理BPM。
- [ ] 保留分支工作树,提交验收,无推送合并。
@@ -0,0 +1,25 @@
# 订单与导出记录:台账式设计
用户已选择A:借鉴[Baserow表格](https://baserow.io/user-docs/guide-to-grid-view),配一行[Windmill运行摘要](https://www.windmill.dev/docs/core_concepts/monitor_past_and_future_runs),导航复用[Tabler分段导航](https://docs.tabler.io/ui/components/segmented-control)。另已确认删除BPM连接后记录自动转历史、默认只看订单相关流程。此确认授权本轮实施及原本机测试服务更新,不另行请求同项批准。
## 页面
- 一级入口仍为订单与导出记录;`#records`为流程到达记录,`#records-pdf`为PDF导出记录。共享现有业务设置的Tabler导航,刷新、后退、直达均保持页签。
- 到达记录默认现有连接、订单相关、全部到达类型,每页25条,按到达时间倒序。来源范围可选现有连接/历史归档/全部;停用仍属现有连接。类型区分待办到达、待阅到达,累计历史不声称当前待办。
- 筛选包含搜索、日期起止、来源、业务范围和到达类型。订单相关严格取分类规则涉及的流程与已有分类目录,包含暂停规则;不按标题猜分类。
- 统一表格展示流水号/流程、节点/类型、标题摘要、来源、到达时间与详情入口。长标题截断;详情侧栏展示原完整标题、流程版本、任务身份、首次采集/最近观察、来源及历史原因。只读,不提供BPM办理或自动重试。
- 一行摘要展示实际推送连接数、最近同步与现有对账周期;手工同步沿用原权限,历史范围不显示同步动作。扫描设置折叠,不占主要列表。
- PDF表格展示订单/通知书编号、项目/型号、导出状态、文件可用性、存储归档结果和时间。成功但文件丢失时保留导出历史并停止显示下载。详情显示实际归档回执;来源无关联就明确未记录,不按订单号猜连接。
## 数据和接口
- Workspace SQLite新增已删除连接的安全来源档案,与连接删除处于同一事务,仅保存ID、名称、负责人、账号显示身份及删除时间;不含凭据。删除仍先停用和排空,真正删除继续清除账号/Cookie。
- 新采集行保存首次来源快照,重扫不改写首次来源。已删除且无快照的旧记录仍进入历史,显示历史连接短ID和信息缺失,不能从相似名称推断原账号或删除日期。
- `GET /api/arrivals?view=ledger`返回分页items、total、page、pageSize和安全来源目录;筛选scope=current|archived|all、business=orders|all、kind=all|todo|inform、q、connectionId、from、to。缺省为current/orders/all,页大小25、上限100;日期按北京时间的到达日,起止均包含。稳定次序为到达时间、来源、任务身份。
- 无view参数的原到达接口保持日期分组和待阅默认值,既有扫描、去重和历史数据不重建。
- `GET /api/jobs?view=ledger`提供搜索、状态与25条分页,补充实际文件可用状态和本地持久归档回执。原jobs返回结构兼容;下载入口继续验证输出目录边界,页面不读取SMB目录、不产生归档或发信。
- 来源归档与PDF存储归档是独立事实;现有PDF导出任务缺少连接关联时不跟随删除动作。未开放重新挂靠、批量删除和批量重试。
## 验收和交付
临时SQLite/文件/假BPM验证删除档案跨重启、停用不归档、旧孤立来源、精确业务筛选、分页/日期/权限、文件缺失/目录越界和归档回执。真实浏览器验证导航、详情关闭、筛选保留、空态、后台刷新不覆盖输入及离页迟到响应。npm ci、新鲜全量测试、语法/链接/差异检查完成后提交,备份并恢复原本机实例,核对账号、密钥、31份采样/草稿及发信暂停。不发真实邮件、不办理BPM、不操作服务机、不推送合并。
+2
View File
@@ -78,6 +78,8 @@
| B03 托管账号、更新/移除、填入、检查保存 | 管理员/负责人;本机或HTTPS | DPAPI加密会话/身份,真实状态 | 不绕验证码,不写回明文;bpm-account-* | 已验证可用 |
| B04 连接检查与状态观察 | 管理员/负责人检查,其他角色按原只读范围 | 登录/待办/监听三项;复用业务证据,轻量检查与续登分离 | 403/401/网络分开、检查合并、输入保留;connection-health/bpm-ui | 专项验收 |
| B05 原生监听、重连、完整对账、到达类型切换 | 启用连接、日历与原执行门控 | 事件名仅提示变化,待办/待阅分开,失败原子保留 | 真实本地Hub、事件合并、同数量替换、停止清理;signalr-client/arrival-monitor/bpm-scan-http-ui | 专项验收 |
| B06 到达台账、历史来源、分页和详情 | 已登录;只读查询 | 默认现有来源/订单流程,删除后保留来源档案,历史可按来源查询;旧孤立来源不猜身份 | 删除/停用/重启、精确流程、日期与分页、只读角色、后台刷新和离页;records-ledger/bpm-scan-http-ui | 本轮验收 |
| F04 PDF台账、文件可用性、归档回执 | 已登录;仅允许本地输出目录内PDF下载 | 导出成功不等于文件仍存在;实际文件检查及持久归档回执分别显示,不移动文件 | 文件缺失、越界、格式、旧回执超100条、详情及窄屏;job-records/dashboard-http/bpm-scan-http-ui | 本轮验收 |
| M01 添加/编辑邮箱、保留空密码、保存/取消 | 管理员;本机/HTTPS、有效参数 | 加密SMTP/IMAP配置与版本 | 错误保留输入;mail-ui/mail-http | 已验证可用 |
| M02 检查邮箱、收取模板、自发测试 | 管理员;已托管非只读邮箱 | 验证状态、收件记录、自身测试记录 | SMTP/IMAP异常明确;未知结果先核验;mail-service | 已验证可用 |
| M03 只读邮箱、文件夹、日期/主题查询、正文/返回 | 管理员;IMAP;最多31天 | 只读Sent历史、To/Cc/附件名 | UID变化重查;不标读删移;history-* | 已验证可用 |
+2
View File
@@ -13,6 +13,8 @@ function createAssets(){
'/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'},
'/record-ui.js':{path:path.join(webRoot,'modules/records/shared.js'),type:'text/javascript'},
'/pdf-records.js':{path:path.join(webRoot,'modules/records/pdf.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},
'/storage-preview.js':{path:path.join(webRoot,'modules/storage/preview.js'),type:'text/javascript',preview:true},
+1 -1
View File
@@ -38,7 +38,7 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,
if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));}
if(await bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await bpmScanApi({scanner,workspace,bpmMonitor,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await bpmScanApi({scanner,workspace,bpmMonitor,orderRules,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 orderExecutionApi({execution:orderExecution,orderRules,dispatcher:orderDispatcher,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
+1 -1
View File
@@ -64,7 +64,7 @@ class BpmArrivalMonitor{
const runId=this.scanner.store.begin(id,principal.user.username,'todo');
const promise=Promise.resolve().then(async()=>{
try{let rows;try{rows=await this.provider.scan(connection,principal);}catch(error){if(error.status!==401)throw error;const result=await this.manager.ensure(connection,principal);if(result.status!=='connected')throw error;rows=await this.provider.scan(connection,principal);}
if(this.stopped||this.workspace.getConnection(id).status==='disabled')fail('连接已暂停,本次对账未提交。',409);return {...this.scanner.store.complete(runId,id,rows.map(todoArrival)),runId};
const current=this.workspace.getConnection(id);if(this.stopped||current.status==='disabled')fail('连接已暂停,本次对账未提交。',409);return {...this.scanner.store.complete(runId,id,rows.map(todoArrival),current),runId};
}catch(error){this.scanner.store.fail(runId,error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');throw error;}
}).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise};
}
+15
View File
@@ -0,0 +1,15 @@
'use strict';
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
function queryLedger({store,workspace,processNames},input={}){
const filters={scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1,pageSize:25,...input};
if(!['current','archived','all'].includes(filters.scope)||!['orders','all'].includes(filters.business)||!['all','todo','inform'].includes(filters.kind))fail('记录筛选范围无效。');
for(const key of ['q','connectionId'])if(typeof filters[key]!=='string'||filters[key].length>200)fail('记录查询条件过长。');
const date=value=>!value||typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(Date.parse(value+'T00:00:00Z'))&&new Date(value+'T00:00:00Z').toISOString().slice(0,10)===value;
if(!date(filters.from)||!date(filters.to)||filters.from&&filters.to&&filters.from>filters.to)fail('请选择有效的起止日期。');
if(!Number.isSafeInteger(filters.page)||filters.page<1||filters.page>1000000||!Number.isInteger(filters.pageSize)||filters.pageSize<1||filters.pageSize>100)fail('记录分页无效。');
const catalog=workspace.recordSources(),sources=new Map(catalog.map(c=>[c.id,{...c,missing:false}]));
for(const id of store.sourceIds())if(!sources.has(id))sources.set(id,{id,name:'历史连接 · '+id.slice(0,8),owner:'',identity:'',status:'archived',enabled:false,archivedAt:null,missing:true});
const page=store.ledger(filters,catalog.filter(c=>c.status==='current').map(c=>c.id),[...new Set(processNames)]);
return {...page,items:page.items.map(row=>{const current=sources.get(row.connectionId),first=row.origin;const origin={...current};if(first)for(const key of ['name','owner','identity'])if(typeof first[key]==='string')origin[key]=first[key].slice(0,200);return {...row,kind:row.source.startsWith('todo:')?'todo':'inform',origin};}),sources:[...sources.values()]};
}
module.exports={queryLedger};
+7 -1
View File
@@ -1,9 +1,15 @@
'use strict';
async function bpmScanApi({scanner,workspace,bpmMonitor,user,sessionId,url,route,method,body,reply}){
async function bpmScanApi({scanner,workspace,bpmMonitor,orderRules,user,sessionId,url,route,method,body,reply}){
if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false;
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
if(!scanner)fail('BPM 扫描暂不可用。',503);
if(route==='/api/arrivals'&&method==='GET'){
if(url.searchParams.get('view')==='ledger'){
const filters={};for(const key of ['scope','business','kind','q','connectionId','from','to','page','pageSize'])if(url.searchParams.has(key))filters[key]=['page','pageSize'].includes(key)?Number(url.searchParams.get(key)):url.searchParams.get(key);
const configured=(orderRules?.all('rules')||[]).flatMap(r=>[...(r.draft?.processNames||[]),...(r.published?.processNames||[]),...(r.draft?.scopes||[]).map(s=>s.processName),...(r.published?.scopes||[]).map(s=>s.processName)]);
const processNames=[...require('../order-rules/catalog.cjs').seedRules().flatMap(r=>r.processNames),...configured];
reply(200,require('./records-query.cjs').queryLedger({store:scanner.store,workspace,processNames},filters));return true;
}
const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7),kind:url.searchParams.get('kind')||'inform'};
reply(200,scanner.store.list(filters));return true;
}
+16 -2
View File
@@ -21,15 +21,29 @@ class BpmScanStore{
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
begin(connectionId,actor,kind='inform'){if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status,kind) VALUES(?,?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running',kind);return id;}
complete(id,connectionId,rows){return this.transaction(()=>{
complete(id,connectionId,rows,connection){return this.transaction(()=>{
let added=0;const now=new Date().toISOString();
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row),key=row.recordKey||row.taskId;added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);}
const prior=this.db.prepare('SELECT value FROM arrivals WHERE connection_id=? AND source=? AND task_id=?');
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const key=row.recordKey||row.taskId,old=prior.get(connectionId,row.source,key),snapshot=old?JSON.parse(old.value).origin:null,saved={...row};delete saved.origin;if(snapshot||connection)saved.origin=snapshot||{id:connectionId,name:connection.name,owner:connection.owner,identity:connection.identity||''};const value=JSON.stringify(saved);added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);}
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
});}
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
status(){return {config:this.config(),total:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source NOT LIKE 'todo:%'").get().n,todoTotal:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source LIKE 'todo:%'").get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message,kind FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
sourceIds(){return this.db.prepare('SELECT DISTINCT connection_id AS id FROM arrivals').all().map(row=>row.id);}
ledger({scope,business,kind,q,connectionId,from,to,page,pageSize},currentIds,processNames){
const conditions=[],args=[];
if(scope!=='all'){conditions.push('connection_id '+(scope==='archived'?'NOT IN':'IN')+' (SELECT value FROM json_each(?))');args.push(JSON.stringify(currentIds));}
if(business==='orders'){conditions.push("json_extract(value,'$.processName') IN (SELECT value FROM json_each(?))");args.push(JSON.stringify(processNames));}
if(kind!=='all')conditions.push(kind==='todo'?"source LIKE 'todo:%'":"source NOT LIKE 'todo:%'");
if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}
if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
if(from){conditions.push('day>=?');args.push(from);}if(to){conditions.push('day<=?');args.push(to);}
const where=conditions.length?' WHERE '+conditions.join(' AND '):'',total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
const items=this.db.prepare("SELECT connection_id AS connectionId,source,task_id AS storageKey,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals"+where+" ORDER BY json_extract(value,'$.arrivedAt') DESC,connection_id,source,task_id LIMIT ? OFFSET ?").all(...args,pageSize,(page-1)*pageSize).map(({value,storageKey,...rest})=>({...JSON.parse(value),...rest,recordId:JSON.stringify([rest.connectionId,rest.source,storageKey])}));
return {items,total,page,pageSize};
}
list({connectionId='',q='',before='',days=7,kind='inform'}={}){
if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
+1 -1
View File
@@ -12,7 +12,7 @@ class BpmScanner{
if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409);
const runId=this.store.begin(id,principal.user.username);
const operation=Promise.resolve().then(async()=>{
try{const rows=await this.manager.scanArrivals(connection,principal);if(this.workspace.getConnection(id).status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows),runId};}
try{const rows=await this.manager.scanArrivals(connection,principal);const current=this.workspace.getConnection(id);if(current.status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows,current),runId};}
catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;}
}).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId};
}
+8 -8
View File
@@ -1,6 +1,6 @@
const fs=require('node:fs');const path=require('node:path');
const {nextSlots}=require('../../shared/schedule.cjs');
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
const {queryJobs,publicJobs,jobFile}=require('./job-records.cjs');
async function dashboardApi({store,outputDir,workspace,mail,scanner,storage,orderRules,user,route,request,response,body,reply,fail}){
const handled=(...args)=>{reply(...args);return true;};
if(route==='/api/overview' && request.method==='GET') {
@@ -11,13 +11,17 @@ const handled=(...args)=>{reply(...args);return true;};
const rules=orderRules?.snapshot(),published=rules?.rules?.filter(r=>r.status==='enabled')||[];
const capabilities=rules?.capabilities||{},ready=['liveTodo','pdfExport','automaticArchive'].every(key=>capabilities[key]===true);
const automation={enabled:rules?.settings?.enabled===true,ready,reason:rules?.settings?.enabled!==true?'分类自动发信已暂停;请先完成类别字段、目录、邮箱与预览核验。':ready?'分类执行链路已完成实际接入检查。':'分类执行链路仍有未通过的实际检查,请查看订单执行中的阻塞原因。'};
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'&&(r.kind||'inform')==='inform'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'&&(r.kind||'inform')==='inform'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:await publicJobs(jobs.slice(0,6),outputDir,storage?.store),audit:store.audit().slice(0,5)});
}
if(route==='/api/settings') {
if(request.method==='GET')return handled(200,store.settings());
if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');if(Object.hasOwn(body,'groups')||Object.hasOwn(body,'templates'))fail(410,'旧群组与通用模板写入已停用,请在分类规则维护收件人,在邮件模板维护类别关联。');return handled(200,store.saveSettings({...body,schedule:{...store.settings().schedule,...body.schedule}},body.version,user.username));}
}
if(route==='/api/jobs' && request.method==='GET')return handled(200,{jobs:store.jobs().map(publicJob)});
if(route==='/api/jobs' && request.method==='GET'){
const params=new URL(request.url,'http://localhost').searchParams;
if(params.get('view')==='ledger'){const filters={};for(const key of ['q','status','page','pageSize'])if(params.has(key))filters[key]=['page','pageSize'].includes(key)?Number(params.get(key)):params.get(key);return handled(200,await queryJobs({jobs:store.jobs(),outputDir,archiveStore:storage?.store},filters));}
return handled(200,{jobs:await publicJobs(store.jobs(),outputDir,storage?.store)});
}
if(route==='/api/audit' && request.method==='GET')return handled(200,{audit:store.audit()});
if(route==='/api/users') {
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
@@ -27,11 +31,7 @@ const handled=(...args)=>{reply(...args);return true;};
const download=/^\/api\/jobs\/([\w-]+)\/file$/.exec(route);
if(download && request.method==='GET') {
const job=store.jobs().find(job=>job.jobId===download[1]);
if(!job || job.status!=='success' || !job.path)fail(404,'文件不可用。');
let realRoot,realFile;
try{[realRoot,realFile]=await Promise.all([fs.promises.realpath(outputDir),fs.promises.realpath(job.path)]);}catch{fail(404,'文件不存在。');}
const relative=path.relative(realRoot,realFile);
if(!relative || relative.startsWith('..'+path.sep) || relative==='..' || path.isAbsolute(relative) || path.extname(realFile).toLowerCase()!=='.pdf')fail(404,'文件不可用。');
const {file:realFile}=await jobFile(job,outputDir);
const bytes=await fs.promises.readFile(realFile);
response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(realFile))}`});response.end(bytes);return true;
}
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const fs=require('node:fs/promises'),path=require('node:path');
const fail=(message,status=400,code)=>Object.assign(new Error(message),{status,code});
async function jobFile(job,outputDir){
if(job?.status!=='success'||typeof job.path!=='string')throw fail('文件尚不可下载。',404,'unavailable');
let root,file;try{[root,file]=await Promise.all([fs.realpath(outputDir),fs.realpath(job.path)]);}catch{throw fail('本地文件不存在。',404,'missing');}
const relative=path.relative(root,file);if(!relative||relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative)||path.extname(file).toLowerCase()!=='.pdf')throw fail('文件不在允许的输出目录。',404,'unavailable');
let handle;try{handle=await fs.open(file,'r');const stat=await handle.stat();if(!stat.isFile())throw fail('文件不可用。',404,'unavailable');const signature=Buffer.alloc(5);await handle.read(signature,0,5,0);if(signature.toString()!=='%PDF-')throw fail('文件不是有效的PDF输出。',404,'unavailable');return {file,filename:path.basename(file),bytes:stat.size};}catch(e){if(e.status)throw e;throw fail('文件暂不可读取。',404,'unavailable');}finally{await handle?.close();}
}
async function publicJobs(jobs,outputDir,archiveStore){
const receipts=archiveStore?.archivesForJobs?.(jobs.map(j=>j.jobId))||[],result=new Array(jobs.length);let next=0;
async function worker(){while(next<jobs.length){const index=next++,{path:ignored,...job}=jobs[index];let fileStatus=job.status==='running'?'pending':'unavailable',fileBytes=null;if(job.status==='success')try{const file=await jobFile(jobs[index],outputDir);fileStatus='available';fileBytes=file.bytes;}catch(e){fileStatus=e.code==='missing'?'missing':'unavailable';}
result[index]={...job,downloadable:fileStatus==='available',fileStatus,fileBytes,fileCheckedAt:new Date().toISOString(),archiveKnown:!!archiveStore?.archivesForJobs,archiveReceipts:receipts.filter(r=>r.jobId===job.jobId).map(({id,status,serverName,relativePath,finishedAt})=>({id,status,serverName:serverName||'',relativePath:relativePath||'',finishedAt:finishedAt||null}))};
}}await Promise.all(Array.from({length:Math.min(8,jobs.length)},worker));return result;
}
async function queryJobs({jobs,outputDir,archiveStore},input={}){
const {q='',status='',page=1,pageSize=25}=input;
if(typeof q!=='string'||q.length>200||!['','success','running','error','interrupted'].includes(status)||!Number.isSafeInteger(page)||page<1||page>1000000||!Number.isInteger(pageSize)||pageSize<1||pageSize>100)throw fail('导出记录查询条件无效。');
const needle=q.trim().toLowerCase(),filtered=jobs.filter(j=>(!status||j.status===status)&&(!needle||[j.metadata?.order,j.metadata?.project,j.metadata?.model,j.metadata?.serial,j.filename].join(' ').toLowerCase().includes(needle))).sort((a,b)=>String(b.updatedAt||'').localeCompare(String(a.updatedAt||''))||String(a.jobId).localeCompare(String(b.jobId)));
return {jobs:await publicJobs(filtered.slice((page-1)*pageSize,page*pageSize),outputDir,archiveStore),total:filtered.length,page,pageSize};
}
module.exports={queryJobs,publicJobs,jobFile};
+1
View File
@@ -77,6 +77,7 @@ class StorageStore{
beginArchive(serverId,jobId,actor,directory){const prior=this.db.prepare('SELECT id,value FROM archives WHERE server_id=? AND job_id=?').get(serverId,jobId),id=prior?.id||crypto.randomUUID();const value={...(prior?JSON.parse(prior.value):{}),actor,directory,startedAt:now(),finishedAt:null,error:null};this.db.prepare('INSERT INTO archives VALUES(?,?,?,?,?) ON CONFLICT(server_id,job_id) DO UPDATE SET status=excluded.status,value=excluded.value').run(id,serverId,jobId,'running',JSON.stringify(value));return {id,serverId,jobId,status:'running',...value};}
finishArchive(id,status,patch){const row=this.db.prepare('SELECT value FROM archives WHERE id=?').get(id);const value={...JSON.parse(row.value),...patch,finishedAt:now()};const saved=this.db.prepare('UPDATE archives SET status=?,value=? WHERE id=? RETURNING id,server_id AS serverId,job_id AS jobId,status').get(status,JSON.stringify(value),id);return {...value,...saved};}
archives(){return this.db.prepare("SELECT id,server_id AS serverId,job_id AS jobId,status,value FROM archives ORDER BY COALESCE(json_extract(value,'$.finishedAt'),json_extract(value,'$.startedAt')) DESC,rowid DESC LIMIT 100").all().map(({value,...r})=>({...JSON.parse(value),...r}));}
archivesForJobs(ids){return this.db.prepare("SELECT id,server_id AS serverId,job_id AS jobId,status,value FROM archives WHERE job_id IN (SELECT value FROM json_each(?)) ORDER BY COALESCE(json_extract(value,'$.finishedAt'),json_extract(value,'$.startedAt')) DESC,rowid DESC").all(JSON.stringify(ids)).map(({value,...r})=>({...JSON.parse(value),...r}));}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
}
module.exports={StorageStore};
+5 -1
View File
@@ -15,6 +15,7 @@ class WorkspaceStore {
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS exceptions(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS connection_archives(id TEXT PRIMARY KEY,value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS audit(seq INTEGER PRIMARY KEY AUTOINCREMENT,value TEXT NOT NULL);`);
const insert=this.db.prepare('INSERT OR IGNORE INTO metadata(key,value) VALUES(?,?)');
insert.run('calendar',JSON.stringify({version:1,overrides:[]}));insert.run('supervisor',JSON.stringify({version:1,defaultOwner:'',notifyChannel:'none',maxAttempts:0}));
@@ -132,7 +133,10 @@ class WorkspaceStore {
});
}
deleteConnection(id,actor){
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};});
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);const archive={id,name:item.name,owner:item.owner,identity:item.identity||'',archivedAt:new Date().toISOString()};this.db.prepare('INSERT INTO connection_archives(id,value) VALUES(?,?)').run(id,JSON.stringify(archive));this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};});
}
recordSources(){
return this.transaction(()=>[...this.db.prepare('SELECT value FROM connections').all().map(({value})=>{const c=JSON.parse(value);return {id:c.id,name:c.name,owner:c.owner,identity:c.identity||'',status:'current',enabled:c.status!=='disabled',archivedAt:null};}),...this.db.prepare('SELECT value FROM connection_archives').all().map(({value})=>({...JSON.parse(value),status:'archived',enabled:false}))]);
}
saveSupervisor(input,actor,members){
authorize(actor,['admin']);object(input,['version','defaultOwner','notifyChannel','maxAttempts']);version(input.version);const defaultOwner=owner(input.defaultOwner,members);
+7
View File
@@ -0,0 +1,7 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
let queryJobs;try{({queryJobs}=require('../../src/modules/dashboard/job-records.cjs'));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'job-records-')),outputDir=path.join(dir,'pdf');fs.mkdirSync(outputDir);const result={dir,outputDir};t.after(()=>{result.close?.();fs.rmSync(dir,{recursive:true,force:true});});return result;}
test('PDF ledger retains export success but only offers existing in-root PDFs for download',async t=>{assert.equal(typeof queryJobs,'function');const f=fixture(t);fs.writeFileSync(path.join(f.outputDir,'ok.pdf'),'%PDF-1.4\nfixture');fs.writeFileSync(path.join(f.dir,'outside.pdf'),'%PDF-1.4\nprivate');fs.writeFileSync(path.join(f.outputDir,'bad.pdf'),'not a PDF');const jobs=['ok','missing','outside','bad'].map(id=>({jobId:id,status:'success',path:path.join(id==='outside'?f.dir:f.outputDir,id+'.pdf'),metadata:{order:id},updatedAt:'2026-10-20T01:00:00Z'}));const result=await queryJobs({jobs,outputDir:f.outputDir});assert.equal(result.total,4);assert.equal(result.jobs.find(j=>j.jobId==='ok').downloadable,true);for(const id of ['missing','outside','bad'])assert.equal(result.jobs.find(j=>j.jobId===id).downloadable,false);assert.equal(result.jobs.every(j=>j.status==='success'),true);assert.equal(JSON.stringify(result).includes(f.dir.replace(/\\/g,'\\\\')),false);assert.equal(result.jobs.some(j=>'path'in j),false);});
test('PDF ledger pages filtered records independently from connection lifecycle and has an honest empty page',async t=>{assert.equal(typeof queryJobs,'function');const f=fixture(t),jobs=Array.from({length:27},(_,i)=>({jobId:'job-'+i,status:'error',metadata:{order:'ORD-'+i},error:'fixture',updatedAt:'2026-10-20T01:00:00Z'}));assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{page:2})).jobs.length,2);assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{q:'ORD-26'})).total,1);assert.equal((await queryJobs({jobs,outputDir:f.outputDir},{status:'success'})).total,0);const empty=await queryJobs({jobs:[],outputDir:f.outputDir});assert.equal(empty.total,0);assert.deepEqual(empty.jobs,[]);for(const filters of [{page:0},{pageSize:101},{status:'unknown'}])await assert.rejects(queryJobs({jobs,outputDir:f.outputDir},filters),e=>e.status===400);});
test('archive history lookup returns older job receipts beyond the latest one hundred entries',async t=>{const {StorageStore}=require('../../src/modules/storage/store.cjs');const f=fixture(t),store=new StorageStore(path.join(f.dir,'storage'));f.close=()=>store.close();assert.equal(typeof store.archivesForJobs,'function');for(let i=0;i<105;i++)store.db.prepare('INSERT INTO archives VALUES(?,?,?,?,?)').run('receipt-'+i,'server','job-'+i,'success',JSON.stringify({relativePath:i+'/file.pdf',finishedAt:'2026-10-20T01:00:00Z'}));const receipt=store.archivesForJobs(['job-0']);assert.equal(receipt.length,1);assert.equal(receipt[0].jobId,'job-0');assert.equal(receipt[0].relativePath,'0/file.pdf');});
+23 -11
View File
@@ -4,12 +4,12 @@ async function setup(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'scan-http-')),store=new Store(path.join(dir,'users')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scanStore=new BpmScanStore(path.join(dir,'scan'));
store.bootstrap('admin','Test-password-123');store.addUser({username:'reader',password:'Test-password-123',role:'viewer'},'admin');store.addUser({username:'other',password:'Test-password-123',role:'operator'},'admin');
const connection={id:'fixture',name:'测试连接',owner:'admin',status:'connected',lastConnectedAt:new Date().toISOString()};workspace.db.prepare('INSERT INTO connections VALUES(?,?)').run(connection.id,JSON.stringify(connection));
const rows=['2026-10-15T16:33:58','2026-10-14T10:00:00'].map((date,i)=>normalizeArrival({taskId:String(i),serialNum:'TEST-'+i,processName:'测试流程',startTime:date,processInstanceSubject:i?'昨天的流程':'<script>bad()</script>订单号:123'},'portal-v8'));
const rows=['2026-10-15T16:33:58','2026-10-14T10:00:00'].map((date,i)=>normalizeArrival({taskId:String(i),serialNum:'TEST-'+i,processName:'海外运营订单评审',startTime:date,processInstanceSubject:i?'昨天的流程':'<script>bad()</script>订单号:123'},'portal-v8'));
const scanner=new BpmScanner({store:scanStore,workspace,manager:{scanArrivals:async()=>rows},settings:()=>store.settings()});
const server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));
t.after(async()=>{await scanner.stop();await new Promise(r=>server.close(r));scanStore.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+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 username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,scanner,scanStore};
const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {base,call,login,scanner,scanStore,workspace,store,dir};
}
test('scan API enforces owner, role and origin; scan results and overview reflect database',async t=>{
const {call,login,scanner}=await setup(t);assert.equal((await call('/api/arrivals')).status,401);const admin=await login('admin'),reader=await login('reader'),other=await login('other');
@@ -20,21 +20,33 @@ test('scan API enforces owner, role and origin; scan results and overview reflec
const page=await (await call('/api/arrivals',undefined,reader)).json();assert.equal(page.groups.length,2);assert.equal(page.groups[0].day,'2026-10-15');assert.equal(page.groups[0].items[0].subject,'订单号:123');
const overview=await (await call('/api/overview',undefined,reader)).json();assert.equal(overview.scan.total,2);assert.equal(overview.connections.find(c=>c.name==='到达历史扫描').ready,true);assert.equal(overview.connections.find(c=>c.name==='BPM 待办执行').ready,false);assert.equal(overview.connections.some(c=>c.name==='BPM 自动扫描'),false);
});
test('browser displays separate arrival days, searches, scans and preserves PDF entry',async t=>{
test('ledger browser keeps filtering, details and addressable PDF navigation independent from scanner failures',async t=>{
const {base,scanner,scanStore}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();
await page.locator('[data-arrival-day="2026-10-15"]').waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),2);
const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'新增流程',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]);
await page.getByText('后台扫描新增',{exact:true}).waitFor({timeout:20000});
await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-day]').length===1);await page.getByText('昨天的流程',{exact:true}).waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),1);
await page.getByRole('button',{name:'立即扫描',exact:true}).click();await page.getByText(/扫描完成/).waitFor();
await page.getByRole('button',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('#record-search').isVisible(),true);
await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})}));
await page.getByRole('link',{name:'工作总览',exact:true}).click();await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.locator('#pdf-fallback').waitFor();await page.locator('#pdf-fallback').click();await page.locator('#record-search').waitFor();
await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('[data-arrival-row]').count(),2);assert.equal(await page.getByRole('navigation',{name:'记录导航'}).getByRole('link',{name:'流程到达记录',exact:true}).getAttribute('aria-current'),'page');
await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'流程到达详情'}).waitFor();await page.getByRole('dialog').getByText('订单号:123',{exact:true}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();
const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'海外运营订单评审',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]);
await page.getByText('后台扫描新增',{exact:true}).filter({visible:true}).waitFor({timeout:20000});await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-row]').length===1);await page.getByText('昨天的流程',{exact:true}).filter({visible:true}).waitFor();
await page.setViewportSize({width:661,height:900});assert.equal(await page.getByRole('button',{name:'查看详情',exact:true}).first().evaluate(node=>node.getBoundingClientRect().right<=innerWidth),true);await page.setViewportSize({width:1280,height:900});await page.getByLabel('到达类型',{exact:true}).selectOption('inform');await page.getByRole('button',{name:'立即同步',exact:true}).click();await page.getByText(/同步完成/).waitFor();
await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(new URL(page.url()).hash,'#records-pdf');await page.reload();await page.locator('#record-search').waitFor();
await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})}));await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.getByText(/扫描暂不可用/).waitFor();await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('.offcanvas-backdrop').count(),0);
});
test('deleted sources enter read-only history while other BPM processes remain available through explicit filters',async t=>{
const {base,workspace,scanner,scanStore,call,login}=await setup(t);await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});scanStore.complete(scanStore.begin('orphan','old'),'orphan',[normalizeArrival({taskId:'OLD',processName:'采购审批',startTime:'2026-10-15T12:00:00',processInstanceSubject:'非订单历史'},'portal-v4')]);workspace.disableConnection('fixture',{username:'admin',role:'admin'});workspace.deleteConnection('fixture',{username:'admin',role:'admin'});const cookie=await login('reader');const data=await(await call('/api/arrivals?view=ledger&scope=archived',undefined,cookie)).json();assert.equal(data.total,2);assert.equal(data.items[0].origin.name,'测试连接');assert.equal((await(await call('/api/arrivals?view=ledger',undefined,cookie)).json()).total,0);
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();await page.goto(base+'/#records');await page.locator('#username').fill('reader');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();await page.getByText('暂无匹配的到达记录',{exact:true}).waitFor();await page.getByLabel('记录范围',{exact:true}).selectOption('archived');await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('[data-arrival-row]').count(),2);assert.equal(await page.getByRole('button',{name:'立即同步',exact:true}).count(),0);await page.getByLabel('业务范围',{exact:true}).selectOption('all');await page.getByText('非订单历史',{exact:true}).filter({visible:true}).waitFor();await page.locator('[data-arrival-row]').filter({hasText:'非订单历史'}).getByRole('button',{name:'查看详情',exact:true}).click();await page.getByRole('dialog',{name:'流程到达详情'}).getByText(/来源信息缺失/).waitFor();await page.goto(base+'/#records-pdf');await page.locator('#record-search').waitFor();await page.waitForFunction(()=>!document.querySelector('.offcanvas-backdrop'));
});
test('todo arrival queries stay separate from inform history and cannot invoke an unavailable todo listener',async t=>{
const {call,login,scanner,scanStore}=await setup(t),cookie=await login('admin');await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'});
const row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO-1',instanceId:'INSTANCE',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]);
const todo=await (await call('/api/arrivals?kind=todo',undefined,cookie)).json();assert.equal(todo.total,1);assert.equal(todo.groups[0].items[0].kind,'todo');assert.equal((await (await call('/api/arrivals',undefined,cookie)).json()).total,2);assert.equal((await call('/api/arrivals?kind=unknown',undefined,cookie)).status,400);assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture',kind:'todo'},cookie)).status,503);
});
test('a successful todo observation does not claim that the independent inform-history source was verified',async t=>{const {call,login,scanStore}=await setup(t),cookie=await login('admin'),row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO',instanceId:'I',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]);const overview=await (await call('/api/overview',undefined,cookie)).json();assert.equal(overview.connections.find(c=>c.name==='到达历史扫描').ready,false);});
test('a delayed initial PDF response cannot discard a search typed while loading',async t=>{const {base}=await setup(t);const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage();let release;const captured=new Promise(resolve=>release=resolve);let first=true;await page.route('**/api/jobs?*',async route=>{if(first){first=false;release(route);return;}await route.continue();});await page.goto(base+'/#records-pdf');await page.locator('#username').fill('admin');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();await page.locator('#record-search').waitFor();const held=await captured;const searched=page.waitForRequest(request=>new URL(request.url()).pathname==='/api/jobs'&&new URL(request.url()).searchParams.get('q')==='UNMATCHED',{timeout:3000});await page.locator('#record-search').fill('UNMATCHED');await held.continue();await searched;await page.getByText('暂无匹配的导出记录',{exact:true}).waitFor();});
test('PDF HTTP and browser separate missing files from completed exports and clean a closing detail on route change',async t=>{
const {base,store,dir,call,login}=await setup(t);fs.writeFileSync(path.join(dir,'available.pdf'),'%PDF-1.4\nfixture');store.recordJob({jobId:'live-pdf',status:'success',path:path.join(dir,'available.pdf'),filename:'available.pdf',metadata:{order:'LIVE-1',project:'项目',model:'型号',serial:'通知-1'}});store.recordJob({jobId:'lost-pdf',status:'success',path:path.join(dir,'lost.pdf'),filename:'lost.pdf',metadata:{order:'LOST-1'}});const cookie=await login('reader');const data=await(await call('/api/jobs?view=ledger',undefined,cookie)).json();assert.equal(data.total,2);assert.equal(data.jobs.find(j=>j.jobId==='lost-pdf').status,'success');assert.equal(data.jobs.find(j=>j.jobId==='lost-pdf').downloadable,false);assert.equal((await call('/api/jobs/live-pdf/file',undefined,cookie)).status,200);assert.equal((await call('/api/jobs/lost-pdf/file',undefined,cookie)).status,404);assert.equal((await call('/api/jobs?view=ledger&page=0',undefined,cookie)).status,400);
const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}}),errors=[];page.on('pageerror',error=>errors.push(error.message));await page.goto(base+'/#records-pdf');await page.locator('#username').fill('reader');await page.locator('#password').fill('Test-password-123');await page.locator('#login-form button').click();const lost=page.locator('[data-pdf-row]').filter({hasText:'LOST-1'});await lost.waitFor();assert.match(await lost.innerText(),/已完成/);assert.match(await lost.innerText(),/文件缺失/);assert.equal(await lost.getByRole('link',{name:'下载 PDF',exact:true}).count(),0);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);await lost.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByRole('dialog',{name:'PDF 导出详情'}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.goto(base+'/#records');await page.locator('#arrival-query').waitFor();await page.waitForTimeout(450);assert.equal(await page.locator('.offcanvas-backdrop').count(),0);assert.equal(await page.evaluate(()=>document.body.style.overflow),'');assert.deepEqual(errors,[]);
});
+11
View File
@@ -0,0 +1,11 @@
'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 {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs');
const actor={username:'admin',role:'admin'};
function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'records-ledger-'));let workspace=new WorkspaceStore(path.join(dir,'workspace'));const scan=new BpmScanStore(path.join(dir,'scan'));t.after(()=>{scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const c=workspace.createConnection({name:'原业务连接',owner:'admin'},actor,[actor]);workspace.updateConnectionSession(c.id,{status:'connected',identity:'原账号',checkedAt:'2026-10-20T01:00:00Z',checks:{portal:{ok:true,message:'ok'}}},actor);return {dir,scan,c,get workspace(){return workspace;},restart(){workspace.close();workspace=new WorkspaceStore(path.join(dir,'workspace'));}};}
const row=(taskId,processName='海外运营订单评审',day='2026-10-20')=>({source:'portal-v4',taskId,processName,subject:'订单号:TEST-'+taskId,arrivalDay:day,arrivedAt:day+'T01:00:00.000Z',activityName:'通知节点'});
function query(f,filters={}){const modulePath='../../src/modules/bpm/records-query.cjs';let queryLedger;try{({queryLedger}=require(modulePath));}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;}assert.equal(typeof queryLedger,'function','ledger query must be implemented');return queryLedger({store:f.scan,workspace:f.workspace,processNames:['海外运营订单评审']},filters);}
test('deletion preserves a safe source archive across restart, while pause stays current',t=>{const f=fixture(t);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('one')]);f.workspace.disableConnection(f.c.id,actor);assert.equal(query(f).total,1);f.workspace.deleteConnection(f.c.id,actor);f.restart();assert.equal(query(f).total,0);const old=query(f,{scope:'archived'});assert.equal(old.total,1);assert.equal(old.items[0].origin.name,'原业务连接');assert.equal(old.items[0].origin.identity,'原账号');assert.equal(old.items[0].origin.status,'archived');assert.ok(old.items[0].origin.archivedAt);assert.equal(/cookie|password|token/i.test(JSON.stringify(old)),false);});
test('legacy orphans remain searchable without inventing a source identity or deletion date',t=>{const f=fixture(t);f.scan.complete(f.scan.begin('old-source','old'),'old-source',[row('old')]);const old=query(f,{scope:'archived'});assert.equal(old.total,1);assert.equal(old.items[0].origin.id,'old-source');assert.equal(old.items[0].origin.identity,'');assert.equal(old.items[0].origin.archivedAt,null);assert.equal(old.items[0].origin.missing,true);assert.equal(query(f,{scope:'archived',connectionId:'old-source',q:'TEST-old'}).total,1);});
test('ledger filters exact configured processes, both arrival types, dates and stable pages',t=>{const f=fixture(t);const rows=[row('a'),row('b'),row('c','采购审批'),{...row('d'),source:'todo:portal-v4',kind:'todo',recordKey:'instance-d'}];f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,rows);const first=query(f,{pageSize:1});assert.equal(first.total,3);assert.equal(first.items.length,1);const second=query(f,{pageSize:1,page:2});assert.notEqual(first.items[0].taskId,second.items[0].taskId);assert.equal(query(f,{business:'all'}).total,4);assert.equal(query(f,{kind:'todo'}).total,1);assert.equal(query(f,{from:'2026-10-20',to:'2026-10-20'}).total,3);assert.equal(query(f,{from:'2026-10-21'}).total,0);for(const filters of [{scope:'bad'},{business:'bad'},{kind:'bad'},{page:0},{pageSize:101},{from:'2026-02-30'},{from:'2026-10-21',to:'2026-10-20'}])assert.throws(()=>query(f,filters),e=>e.status===400);assert.equal(f.scan.list().total,3);});
test('rescan retains the first observed source snapshot and preserves arrival identity',t=>{const f=fixture(t);const original=f.workspace.getConnection(f.c.id);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('a')],original);f.workspace.updateConnectionSession(f.c.id,{status:'connected',identity:'新账号',checkedAt:'2026-10-20T02:00:00Z',checks:{portal:{ok:true,message:'ok'}}},actor);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,[row('a')],f.workspace.getConnection(f.c.id));const records=query(f);assert.equal(records.total,1);assert.equal(records.items[0].origin.identity,'原账号');});
+5
View File
@@ -47,3 +47,8 @@
.rule-workbench-grid{grid-template-columns:280px minmax(0,1fr);gap:24px}.rule-category-directory{overflow:hidden}.rule-category-directory .card-header{padding:18px}.rule-category-list{max-height:calc(100vh - 355px);min-height:220px;overflow:auto;overscroll-behavior:contain;padding:6px}.rule-category-item{border:1px solid transparent;border-radius:10px;margin:4px 0;overflow:hidden}.rule-category-item.is-selected{background:#f0f7f3;border-color:#b8d5c5}.rule-category-select{display:block;width:100%;border:0;background:none;text-align:left;padding:13px 12px 6px;color:inherit;overflow-wrap:anywhere}.rule-category-select:hover{background:#28745b08}.rule-category-select:focus-visible{outline:2px solid #28745b;outline-offset:-2px;border-radius:8px}.rule-category-select strong{display:block;font-size:.86rem;font-weight:600;line-height:1.6}.rule-category-kind{display:block;font-size:.65rem;color:#83928a;margin-bottom:4px;letter-spacing:.03em}.rule-category-meta{display:block;font-size:.69rem;color:#79857e;margin-top:6px}.rule-category-readiness,.rule-category-ready{display:block;font-size:.69rem;margin-top:5px;color:#a47430}.rule-category-ready{color:#368266}.rule-category-control{display:flex;justify-content:space-between;align-items:center;padding:7px 12px 12px;gap:12px}.rule-category-control .small{font-size:.7rem}.rule-category-control .form-switch .form-check-input{width:2.25rem;height:1.25rem;cursor:pointer;margin:0;float:none}.rule-category-control .form-switch{min-height:0;padding:0;display:flex}.rule-category-control .form-check-input:checked{background-color:#28745b;border-color:#28745b}.rule-category-control .form-check-input:disabled{cursor:default}.rule-recognition-flow{display:flex;align-items:center;gap:12px;flex-wrap:wrap;font-size:.8rem}.rule-recognition-flow span:nth-child(odd){padding:8px 12px;border:1px solid #dfe9e2;background:#f8fbf9;border-radius:8px}.rule-recognition-coverage,.rule-empty-recognition{font-size:.8rem;padding:14px;border-radius:8px;background:#f5f7fa;border:1px solid #e9edf1;line-height:1.8}.rule-archive-destination,.rule-folder-browser{background:#f8faf9;border:1px solid #e3eae5;border-radius:8px;padding:12px;font-size:.8rem}.rule-folder-browser .list-group{max-height:260px;overflow:auto}.rule-recognition-check select{flex-basis:65%;width:auto;min-width:0}.rule-recognition-check .btn{align-self:start}.rule-result-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.rule-business-summary{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font-size:.8rem;background:#f7f9fb;border-radius:8px;padding:12px}.rule-editor-column{max-width:1080px}.rule-effect-preview dl{margin-top:16px}.rule-config-section summary{font-size:.8rem;color:#53645b;cursor:pointer}.rule-save-bar>span{flex:1 1 300px}.rule-category-directory .card-footer{line-height:1.8;font-size:.7rem}@media(max-width:1350px){.rule-workbench-grid{grid-template-columns:250px minmax(0,1fr)}}@media(max-width:991px){.rule-workbench-grid{grid-template-columns:minmax(0,1fr)}.rule-category-list{max-height:280px;min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:4px}.rule-category-item{margin:0}.rule-category-directory{position:static}.rule-category-directory .card-footer{display:none}.rule-editor-column{max-width:100%}.rule-save-bar>span{flex-basis:100%}}@media(max-width:440px){.rule-category-select{padding:10px 9px 5px}.rule-category-select strong{font-size:.78rem}.rule-category-meta{font-size:.65rem}.rule-category-control{padding:6px 9px 10px}.rule-recognition-flow{gap:7px;font-size:.7rem}.rule-recognition-flow span:nth-child(odd){padding:6px 8px}.rule-recognition-check select{flex-basis:100%;width:100%}}
.rule-scope-row{grid-template-columns:repeat(2,minmax(0,1fr))}.rule-scope-node-control{flex-wrap:nowrap;align-items:stretch}.rule-scope-node-control>.form-select{min-width:0}.rule-scope-node-control>.rule-scope-remove{flex:0 0 38px;width:38px;height:auto;min-width:0;min-height:0;padding:0;font-size:22px;line-height:1;border-color:#dfe6eb;color:var(--tblr-secondary);background:#fff;display:inline-flex;align-items:center;justify-content:center;border-radius:0 7px 7px 0}.rule-scope-node-control>.rule-scope-remove:hover{color:#b42318;background:#fff5f4}.rule-scope-node-control>.rule-scope-remove:focus-visible{outline:2px solid #73a591;outline-offset:2px;z-index:3}@media(max-width:991px){.rule-scope-row{grid-template-columns:minmax(0,1fr)}}
/* Record ledgers reuse Tabler tables, segmented navigation and offcanvas. */
.record-monitor{margin-bottom:16px;padding:10px 14px;background:var(--tblr-bg-surface);border:1px solid var(--tblr-border-color);border-radius:8px}.record-filters{border-bottom:1px solid var(--tblr-border-color)}.record-ledger td{padding-top:13px;padding-bottom:13px}.record-summary-cell{min-width:200px;max-width:400px}.record-summary{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;line-height:1.5;overflow-wrap:anywhere}.record-detail{--tblr-offcanvas-width:560px;width:min(560px,100vw)!important}.record-detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px 24px}.record-detail-field{min-width:0}.record-detail-field:last-child{grid-column:1/-1}.record-detail-field dt{font-size:.8rem;font-weight:400;color:var(--tblr-secondary);margin-bottom:5px}.record-detail-field dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.record-receipt{padding:12px 0;border-top:1px solid var(--tblr-border-color);overflow-wrap:anywhere}@media(max-width:575px){.record-detail-grid{grid-template-columns:1fr}.record-ledger{font-size:.85rem}.record-monitor{line-height:1.7}}
.record-identity{min-width:140px}.record-identity strong{display:block;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.record-node{min-width:115px}.record-source{min-width:120px}.record-action{white-space:nowrap}.record-inline-source,.record-inline-time,.record-inline-summary,.record-inline-export{display:none}@media(max-width:991px){.record-ledger .record-node,.record-ledger .record-source{display:none}.record-inline-source{display:block;margin-top:4px;max-width:200px;overflow-wrap:anywhere}}@media(max-width:767px){.record-ledger .record-time{display:none}.record-inline-time{display:block;margin-top:3px;font-size:.72rem}.record-identity{min-width:140px}}@media(max-width:575px){.record-ledger .record-summary-cell,.record-ledger .record-export-state,.record-ledger .record-file{display:none}.record-inline-summary{display:-webkit-box;margin-top:7px}.record-inline-export{display:block;margin-top:5px}.record-ledger .record-identity{min-width:0}.record-identity strong{max-width:200px}.record-pdf-actions{flex-direction:column;align-items:stretch}.record-action{width:90px}.record-ledger td{padding-left:14px;padding-right:14px}}
+7 -14
View File
@@ -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,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0;
const views={'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['通知订单','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['待发批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','从真实 BPM 样本选择字段,按表单版本保存对应关系'],'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护 Excel 分类规则、收件人和真实字段对应'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
const views={'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['通知订单','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['待发批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','从真实 BPM 样本选择字段,按表单版本保存对应关系'],'assistant-settings':['助手设置','配置 ZCode 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护 Excel 分类规则、收件人和真实字段对应'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
const pendingWrites=new Map();
async function api(route,body,{signal,ownerCheck,managedOutcome=false}={}) {
const originGeneration=viewGeneration,originUser=currentUser,originRevision=window.PageLifecycle?.revision;const originActive=()=>viewGeneration===originGeneration&&currentUser===originUser&&window.PageLifecycle?.revision===originRevision;const submission=window.PageLifecycle?.submission,hasBody=body!==undefined,write=hasBody&&route!=='/order-rules/field-mappings/propose',key=originGeneration+':'+originRevision+':'+route+':'+JSON.stringify(body);const pending=pendingWrites.get(key);if(write&&pending?.user===originUser)return pending.work;
@@ -50,16 +50,9 @@ async function viewOverview(container,isActive=()=>true) {
container.innerHTML=empty('工作台模块未加载','请刷新页面后重试。');
}catch(error){if(ownsResponse())throw error;}
}
async function viewRecords(container,isActive=()=>true) {
await window.OrderViews.records(container,isActive,viewPdfRecords);if(!isActive())return;const notice=document.createElement('div');notice.className='alert alert-info';notice.innerHTML='此处查询采集与 PDF 导出记录;分类和邮件批次请到 <a href="#notification-orders">通知订单</a> 查看。';container.prepend(notice);const history=document.createElement('section');history.className='mt-3';history.innerHTML='<button class="btn mb-3" id="legacy-notifications-open">查看旧通知历史(只读)</button><div id="legacy-notification-history"></div>';container.append(history);history.querySelector('button').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{await window.NotificationViews.history(history.querySelector('#legacy-notification-history'),isActive);}catch(error){if(isActive())notify(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}};
}
async function viewPdfRecords(container,isActive=()=>true) {
const {jobs}=await api('/jobs');if(!isActive())return;
container.innerHTML=`<div class="card"><div class="card-header gap-3 flex-wrap"><h2 class="card-title">导出记录 <span class="text-secondary">${jobs.length}</span></h2><div class="ms-auto d-flex gap-2"><input class="form-control" id="record-search" placeholder="搜索订单号、项目或型号" aria-label="搜索订单"><select class="form-select" id="record-status" aria-label="任务状态"><option value="">全部状态</option><option value="success">已完成</option><option value="running">处理中</option><option value="error">失败</option><option value="interrupted">已中断</option></select></div></div><div id="records-body"></div><div class="card-footer d-flex align-items-center"><span class="text-secondary" id="records-count"></span><div class="btn-list ms-auto"><button class="btn btn-sm" id="prev-page">上一页</button><button class="btn btn-sm" id="next-page">下一页</button></div></div></div>`;
let page=0;
function render(){const search=document.querySelector('#record-search').value.toLowerCase().trim();const status=document.querySelector('#record-status').value;const filtered=jobs.filter(job=>(!status || job.status===status) && (!search || [job.metadata?.order,job.metadata?.project,job.metadata?.model,job.metadata?.serial,job.filename].join(' ').toLowerCase().includes(search)));page=Math.max(0,Math.min(page,Math.ceil(filtered.length/25)-1));const selected=filtered.slice(page*25,page*25+25);document.querySelector('#records-body').innerHTML=selected.length?jobTable(selected):empty('暂无匹配记录','调整搜索条件,或先从订单页面导出一份通知书。');document.querySelector('#records-count').textContent=`共 ${filtered.length} 条 · 第 ${page+1} 页`;document.querySelector('#prev-page').disabled=page===0;document.querySelector('#next-page').disabled=(page+1)*25>=filtered.length;}
document.querySelector('#record-search').oninput=()=>{page=0;render();};document.querySelector('#record-status').onchange=()=>{page=0;render();};document.querySelector('#prev-page').onclick=()=>{page--;render();};document.querySelector('#next-page').onclick=()=>{page++;render();};render();
}
function recordHistory(container,isActive){const history=document.createElement('section');history.className='mt-3';history.innerHTML='<button class="btn btn-sm mb-3" id="legacy-notifications-open">查看旧通知历史(只读)</button><div id="legacy-notification-history"></div>';container.append(history);history.querySelector('button').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{await window.NotificationViews.history(history.querySelector('#legacy-notification-history'),isActive);}catch(error){if(isActive())notify(error.message,'danger');}finally{if(button.isConnected)button.disabled=false;}};}
async function viewRecords(container,isActive=()=>true){await window.OrderViews.records(container,isActive);if(isActive())recordHistory(container,isActive);}
async function viewPdfRecords(container,isActive=()=>true){await window.PdfRecordViews.records(container,isActive);if(isActive())recordHistory(container,isActive);}
async function viewSchedule(container,isActive=()=>true) {
const loaded=await api('/settings');if(!isActive())return;let draft=loaded;const s=draft.schedule;const disabled=currentUser.role!=='admin'?'disabled':'';
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">收件人及类别要求在 <a href="#order-rules">分类通知规则</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></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>`;
@@ -103,12 +96,12 @@ async function renderView() {
window.AppNavigation.renderTabs(document.querySelector('#settings-tabs'),{id:currentView,user:currentUser,views,esc});
document.querySelectorAll('[data-view]').forEach(link=>{const active=link.dataset.view===(section||currentView);link.classList.toggle('active',active);if(active)link.setAttribute('aria-current','page');else link.removeAttribute('aria-current');});
const sectionTitle=section==='order-notifications'?'订单通知管理':views[section]?.[0];
const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView;breadcrumb.innerHTML=breadcrumb.hidden?'':`<a href="#${section}" aria-label="返回${sectionTitle}">← ${sectionTitle}</a> <span class="text-secondary"> / ${esc(views[currentView][0])}</span>`;
const breadcrumb=document.querySelector('#view-breadcrumb');breadcrumb.hidden=!section||section===currentView||section==='records';breadcrumb.innerHTML=breadcrumb.hidden?'':`<a href="#${section}" aria-label="返回${sectionTitle}">← ${sectionTitle}</a> <span class="text-secondary"> / ${esc(views[currentView][0])}</span>`;
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 notificationSections={'order-notifications':'workbench','notification-execution':'execution','notification-orders':'orders','notification-batches':'pending','notification-history':'history','notification-settings':'settings'};
const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
const fn={'rule-fields':(host,active)=>window.OrderRuleViews.render(host,active,'fields'),...Object.fromEntries(Object.entries(notificationSections).map(([route,section])=>[route,(host,active)=>window.OrderNotificationViews.render(host,active,section)])),'assistant-settings':window.AssistantViews?.settings,account:window.AccountViews?.account,'order-rules':window.OrderRuleViews?.render,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,records:viewRecords,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
void updateAutomationStatus(isActive);
try{window.PageLifecycle?.attach(container);const host=window.AppNavigation.isConfiguration(currentView)?configurationHost(container):container;await fn(host,isActive);if(isActive())window.PageLifecycle?.bind();}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
}
@@ -119,7 +112,7 @@ async function authScreen() {
}
async function passwordChanged(actorId){if(currentUser&&currentUser.id!==actorId)return false;currentUser=null;++viewGeneration;clearInterval(refreshTimer);await window.PageLifecycle?.dispose();await window.BpmLogin?.dispose().catch(()=>{});await boot();return true;}
function enter(){window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.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&&!document.hidden){const statusGeneration=viewGeneration,statusUser=currentUser;void updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser);}if(currentUser && currentView==='overview' && !document.hidden){const generation=viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
function enter(){window.PdfRecordViews?.configure({api,esc,formatDate,notify,user:currentUser});window.AccountViews?.configure({api,esc,formatDate,notify,user:currentUser,onPasswordChanged:passwordChanged});window.OrderRuleViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderNotificationViews?.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&&!document.hidden){const statusGeneration=viewGeneration,statusUser=currentUser;void updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser);}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('page-operation-error',event=>notify(event.detail.message,'danger'));
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
+1 -1
View File
@@ -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"><link href="/field-mappings.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-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="/field-sample-picker.js" defer></script><script src="/field-recognition-panel.js" defer></script><script src="/order-rules-scopes.js" defer></script><script src="/order-rules-resources.js" defer></script><script src="/order-rules-import.js" defer></script><script src="/order-rules-editor.js" defer></script><script src="/order-rules-preview.js" defer></script><script src="/field-mappings.js" defer></script><script src="/order-execution.js" defer></script><script src="/order-notifications-shared.js" defer></script><script src="/order-notifications.js" defer></script><script src="/order-rules.js" defer></script><script src="/health.js" defer></script><script src="/assistant.js" defer></script><script src="/account.js" defer></script><script src="/navigation.js" defer></script><script src="/page-lifecycle.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="/record-ui.js" defer></script><script src="/orders.js" defer></script><script src="/pdf-records.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="/field-sample-picker.js" defer></script><script src="/field-recognition-panel.js" defer></script><script src="/order-rules-scopes.js" defer></script><script src="/order-rules-resources.js" defer></script><script src="/order-rules-import.js" defer></script><script src="/order-rules-editor.js" defer></script><script src="/order-rules-preview.js" defer></script><script src="/field-mappings.js" defer></script><script src="/order-execution.js" defer></script><script src="/order-notifications-shared.js" defer></script><script src="/order-notifications.js" defer></script><script src="/order-rules.js" defer></script><script src="/health.js" defer></script><script src="/assistant.js" defer></script><script src="/account.js" defer></script><script src="/navigation.js" defer></script><script src="/page-lifecycle.js" defer></script><script src="/app.js" defer></script></body></html>
+21 -47
View File
@@ -1,52 +1,26 @@
'use strict';
window.OrderViews=(()=>{
let api,esc,formatDate,notify,user,filters={q:'',connectionId:'',kind:'inform'};
const configure=options=>{if(user?.username!==options.user.username)filters={q:'',connectionId:''};({api,esc,formatDate,notify,user}=options);};
async function records(container,isActive,renderPdf){
let initial;
try{initial=await api('/bpm-scan');}catch(cause){
if(!isActive())return;
container.innerHTML=`<div class="alert alert-warning">${esc(cause.message)}</div><button class="btn mb-3" id="pdf-fallback">PDF 导出记录</button><div id="pdf-fallback-panel"></div>`;
container.querySelector('#pdf-fallback').onclick=()=>renderPdf(container.querySelector('#pdf-fallback-panel'),isActive).catch(e=>notify(e.message,'danger'));return;
}
if(!isActive())return;
let mode='arrivals',before='',loading=false,revision=0,watching=false,lastSignature='',status=initial;
const names=new Map(initial.connections.map(c=>[c.id,c.name]));
const nodeLabel=value=>value==='sysInform'?'知会':value||'—';
container.innerHTML=`<div class="btn-list mb-3"><button class="btn btn-primary" id="arrivals-tab">流程到达记录</button><button class="btn" id="pdf-tab">PDF 导出记录</button></div><div id="order-panel"></div>`;
const panel=container.querySelector('#order-panel');
const active=()=>isActive()&&mode==='arrivals';
function toolbar(){panel.innerHTML=`<section class="card mb-4"><div class="card-header flex-wrap gap-3"><div><h2 class="card-title mb-1">BPM 自动扫描</h2><div class="text-secondary small" id="scan-summary"></div></div><div class="ms-auto btn-list"><a class="btn" href="#bpm">管理连接</a>${user.role!=='viewer'?'<button class="btn btn-primary" id="scan-now">立即扫描</button>':''}</div></div><div class="card-body"><form id="arrival-filter" class="row g-3 align-items-end"><div class="col-md-4"><label class="form-label" for="arrival-query">搜索流程记录</label><input class="form-control" id="arrival-query" value="${esc(filters.q)}" placeholder="流水号、流程名、标题或发起人" maxlength="200"></div><div class="col-md-3"><label class="form-label" for="arrival-connection">BPM 连接</label><select class="form-select" id="arrival-connection"><option value="">全部连接</option>${initial.connections.map(c=>`<option value="${esc(c.id)}" ${c.id===filters.connectionId?'selected':''}>${esc(c.name)}${c.status==='disabled'?'(已停用)':''}</option>`).join('')}</select></div><div class="col-md-3"><label class="form-label" for="arrival-kind">到达类型</label><select class="form-select" id="arrival-kind"><option value="inform" ${filters.kind!=='todo'?'selected':''}>待阅记录</option><option value="todo" ${filters.kind==='todo'?'selected':''}>真实待办</option></select></div><div class="col-md-2"><button class="btn w-100" type="submit">查询</button></div></form><div id="scan-result" class="small mt-3" role="status"></div>${user.role==='admin'?`<details class="mt-3"><summary class="text-secondary">扫描设置</summary><form id="scan-config" class="d-flex flex-wrap align-items-center gap-3 mt-3"><label class="form-check form-switch mb-0"><input id="scan-enabled" class="form-check-input" type="checkbox" ${status.config.enabled?'checked':''}><span class="form-check-label">自动扫描</span></label><label class="d-flex align-items-center gap-2">间隔(分钟)<input id="scan-interval" class="form-control scan-interval" type="number" min="1" max="1440" required value="${status.config.intervalMinutes}"></label><button class="btn" type="submit">保存设置</button><a href="#calendar" class="small">业务日历</a></form></details>`:''}</div></section><div class="d-flex align-items-center mb-3"><h2 class="h3 m-0">按到达日期</h2><span class="text-secondary small ms-auto" id="arrival-count"></span></div><div id="arrival-groups"></div><div class="text-center mt-3"><button id="arrival-more" class="btn" hidden>加载更早日期</button></div>`;
panel.querySelector('#arrival-filter').onsubmit=event=>{event.preventDefault();filters={q:panel.querySelector('#arrival-query').value.trim(),connectionId:panel.querySelector('#arrival-connection').value,kind:panel.querySelector('#arrival-kind').value};load(false).catch(showError);};
panel.querySelector('#arrival-more').onclick=()=>load(true).catch(showError);
panel.querySelector('#scan-config')?.addEventListener('submit',async event=>{event.preventDefault();const button=event.target.querySelector('button');button.disabled=true;try{status.config=await api('/bpm-scan/config',{enabled:panel.querySelector('#scan-enabled').checked,intervalMinutes:Number(panel.querySelector('#scan-interval').value)});if(active()){summary();notify('扫描设置已保存。');}}catch(e){showError(e);}finally{button.disabled=false;}});
panel.querySelector('#scan-now')?.addEventListener('click',async()=>{
const button=panel.querySelector('#scan-now');button.disabled=true;
try{const selected=panel.querySelector('#arrival-connection').value,connections=status.connections.filter(c=>c.status!=='disabled'&&(!selected||c.id===selected)&&(user.role==='admin'||c.owner===user.username));if(!connections.length)throw Error('没有可扫描的连接,请先在 BPM 连接中完成登录。');
for(const c of connections)await api('/bpm-scan/run',{connectionId:c.id,...(filters.kind==='todo'?{kind:'todo'}:{})});if(active()){panel.querySelector('#scan-result').textContent='正在扫描…';await refresh();watch();}
}catch(e){showError(e);}finally{if(active())button.disabled=false;}
});summary();
}
function showError(e){if(active())notify(e.message,'danger');}
function summary(){
if(!active())return;panel.querySelector('#scan-summary').textContent=`${status.config.enabled?'已开启':'已暂停'} · 推送连接 ${status.connections.filter(c=>c.monitoring?.status==='listening').length} 个 · 每 ${status.config.intervalMinutes} 分钟完整对账 · 按业务日历运行`;
const runs=status.runs.filter(r=>(r.kind||'inform')===(filters.kind||'inform')),latest=runs[0],ok=runs.find(r=>r.status==='success');
const el=panel.querySelector('#scan-result');el.className='small mt-3 '+(latest?.status==='error'?'text-danger':'text-secondary');
el.textContent=latest?.status==='running'?'正在扫描…':latest?.status==='error'?`${names.get(latest.connectionId)||'BPM'}:${latest.message}`:ok?`扫描完成 · ${formatDate(ok.finishedAt)} · 本次 ${ok.seen} 条,新增 ${ok.added} 条`:'尚无扫描记录';
}
function groupHtml(group){return `<details open class="card arrival-day mb-4" data-arrival-day="${esc(group.day)}"><summary class="card-header"><span class="arrival-date">${esc(group.day)}</span><span class="badge bg-blue-lt ms-3">${group.items.length} 条</span><span class="small text-secondary ms-auto">到达时间 · 北京时间</span></summary><div class="table-responsive"><table class="table table-vcenter card-table arrival-table"><thead><tr><th>到达时间 / 连接</th><th>流水号 / 流程</th><th>标题</th><th>发起人 / 节点</th></tr></thead><tbody>${group.items.map(row=>`<tr><td class="text-secondary small">${formatDate(row.arrivedAt)}<div class="mt-1">${esc(names.get(row.connectionId)||'已删除连接')}</div></td><td><strong>${esc(row.serialNum||'—')}</strong><div class="text-secondary small mt-1">${esc(row.processName||'—')}</div></td><td class="arrival-subject">${esc(row.subject||'—')}</td><td>${esc(row.initiator||'—')}<div class="text-secondary small mt-1">${esc(nodeLabel(row.activityName))}</div></td></tr>`).join('')}</tbody></table></div></details>`;}
async function load(append=false){
if(loading&&append)return;loading=true;const request=++revision;
try{const params=new URLSearchParams({...filters,...(append&&before?{before}:{} )});const result=await api('/arrivals?'+params);if(!active()||request!==revision)return;
const groups=panel.querySelector('#arrival-groups'),html=result.groups.map(groupHtml).join('');if(append)groups.insertAdjacentHTML('beforeend',html);else groups.innerHTML=html||'<div class="card"><div class="card-body text-center text-secondary py-5">暂无匹配的流程记录</div></div>';
before=result.nextBefore;panel.querySelector('#arrival-more').hidden=!before;panel.querySelector('#arrival-count').textContent=`共 ${result.total} 条流程`;
}finally{if(request===revision)loading=false;}
}
async function refresh(){const next=await api('/bpm-scan');if(!active())return;status=next;summary();const signature=JSON.stringify(status.runs.map(r=>[r.id,r.status]));if(lastSignature&&signature!==lastSignature)await load(false);lastSignature=signature;}
function watch(){if(watching||!active())return;watching=true;setTimeout(async()=>{watching=false;if(!active())return;try{await refresh();}catch(e){showError(e);}if(active())watch();},status.runs.some(r=>r.status==='running')?1500:10000);}
container.querySelector('#pdf-tab').onclick=async()=>{mode='pdf';++revision;container.querySelector('#pdf-tab').classList.add('btn-primary');container.querySelector('#arrivals-tab').classList.remove('btn-primary');try{await renderPdf(panel,()=>isActive()&&mode==='pdf');}catch(e){if(isActive())notify(e.message,'danger');}};
container.querySelector('#arrivals-tab').onclick=async()=>{mode='arrivals';container.querySelector('#arrivals-tab').classList.add('btn-primary');container.querySelector('#pdf-tab').classList.remove('btn-primary');toolbar();try{await load();await refresh();watch();}catch(e){showError(e);}};
toolbar();await load();await refresh();watch();
let api,esc,formatDate,notify,user,filters;
const defaults=()=>({scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1});
function configure(options){if(user?.username!==options.user.username)filters=defaults();({api,esc,formatDate,notify,user}=options);}
async function records(container,isActive){
let disposed=false,revision=0,status=null,timer,lastSignature='',controller;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;clearTimeout(timer);controller?.abort();});
const option=(value,label,current)=>'<option value="'+esc(value)+'" '+(value===current?'selected':'')+'>'+esc(label)+'</option>';
container.innerHTML='<div class="record-monitor small text-secondary" data-monitor aria-live="polite">正在读取监听状态…</div><div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-2"><h2 class="card-title">流程到达台账</h2><div class="btn-list ms-auto"><a href="#bpm" class="btn btn-sm">管理连接</a>'+(user.role!=='viewer'?'<button type="button" class="btn btn-primary btn-sm" id="scan-now">立即同步</button>':'')+'</div></div><div class="card-body record-filters"><div class="row g-3"><div class="col-12 col-sm-6 col-lg-4"><label class="form-label" for="arrival-query">搜索流程记录</label><input class="form-control" id="arrival-query" maxlength="200" placeholder="流水号、流程、订单标题" value="'+esc(filters.q)+'"></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-scope">记录范围</label><select class="form-select" id="arrival-scope">'+option('current','现有连接',filters.scope)+option('archived','历史归档',filters.scope)+option('all','全部来源',filters.scope)+'</select></div><div class="col-6 col-sm-3 col-lg-2"><label class="form-label" for="arrival-business">业务范围</label><select class="form-select" id="arrival-business">'+option('orders','订单相关流程',filters.business)+option('all','全部 BPM 流程',filters.business)+'</select></div><div class="col-6 col-sm-8 col-lg-2"><label class="form-label" for="arrival-kind">到达类型</label><select class="form-select" id="arrival-kind">'+option('all','全部到达类型',filters.kind)+option('todo','待办到达记录',filters.kind)+option('inform','待阅到达记录',filters.kind)+'</select></div><div class="col-6 col-sm-4 col-lg-2 d-flex align-items-end"><button type="button" class="btn w-100" id="arrival-submit">查询</button></div></div><details class="mt-3"><summary class="small text-secondary">更多筛选:来源与日期</summary><div class="row g-3 mt-0"><div class="col-12 col-md-4"><label class="form-label" for="arrival-connection">来源连接</label><select class="form-select" id="arrival-connection"><option value="">全部来源连接</option></select></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-from">起始日期</label><input class="form-control" id="arrival-from" type="date" value="'+esc(filters.from)+'"></div><div class="col-6 col-md-4"><label class="form-label" for="arrival-to">结束日期</label><input class="form-control" id="arrival-to" type="date" value="'+esc(filters.to)+'"></div></div></details></div><div data-arrival-list></div>'+window.RecordUi.footer+'</section><div class="small text-secondary mt-2">按北京时间记录到达历史 · 分类与邮件批次见 <a href="#notification-orders">通知订单</a></div><div id="record-scan-settings"></div>';
const detail=window.RecordUi.details(container,'流程到达详情');
function error(message){if(!live())return;const node=container.querySelector('[data-record-error]');node.hidden=!message;node.textContent=message||'';}
function candidates(){return status?.connections?.filter(c=>c.status!=='disabled'&&(!filters.connectionId||c.id===filters.connectionId)&&(user.role==='admin'||c.owner===user.username))||[];}
function monitor(){if(!live()||!status)return;const active=status.connections.filter(c=>c.status!=='disabled'),listening=active.filter(c=>c.monitoring?.status==='listening').length,times=active.map(c=>c.monitoring?.lastSyncAt).filter(Boolean).sort();container.querySelector('[data-monitor]').textContent=(status.config.enabled?'监听已开启':'自动同步已暂停')+' · 推送连接 '+listening+' 个 · 每 '+status.config.intervalMinutes+' 分钟完整对账'+(times.length?' · 最近同步 '+formatDate(times.at(-1)):'');const button=get('scan-now');if(button){button.hidden=filters.scope==='archived';button.disabled=filters.scope==='archived'||!candidates().length;}}
function sourceOptions(sources){get('arrival-connection').innerHTML='<option value="">全部来源连接</option>'+sources.filter(s=>filters.scope==='all'||s.status===filters.scope).map(s=>option(s.id,s.name+(s.status==='archived'?'(历史)':s.enabled?'':'(已停用)'),filters.connectionId)).join('');if(filters.connectionId&&!sources.some(s=>s.id===filters.connectionId&&(filters.scope==='all'||s.status===filters.scope)))get('arrival-connection').innerHTML+=option(filters.connectionId,'所选历史来源',filters.connectionId);}
function open(row,trigger){const f=(label,value)=>window.RecordUi.field(esc,label,value);detail.show('<dl class="record-detail-grid">'+f('流水号',row.serialNum)+f('流程',row.processName)+f('流程版本',row.processVersion)+f('节点',row.activityName)+f('到达类型',row.kind==='todo'?'待办到达记录':'待阅到达记录')+f('到达时间',formatDate(row.arrivedAt))+f('来源连接',row.origin.name)+f('来源账号',row.origin.identity||'账号未记录')+f('负责人',row.origin.owner)+f('来源状态',row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'现有连接 · 已停用')+f('来源归档时间',row.origin.archivedAt?formatDate(row.origin.archivedAt):row.origin.status==='archived'?'未记录':'—')+(row.origin.missing?f('来源说明','来源信息缺失,保留原连接标识:'+row.connectionId):'')+f('首次采集',formatDate(row.firstSeenAt))+f('最近观察',formatDate(row.lastSeenAt))+f('任务标识',row.taskId)+f('完整标题',row.subject)+'</dl>',trigger);}
function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=data.items.length?'<div class="table-responsive"><table class="table table-vcenter table-hover card-table record-ledger"><thead><tr><th scope="col">流水号/流程</th><th scope="col" class="record-node">节点/类型</th><th scope="col">标题摘要</th><th scope="col" class="record-source">来源</th><th scope="col" class="record-time">到达时间</th><th scope="col">详情</th></tr></thead><tbody>'+data.items.map((row,index)=>'<tr data-arrival-row><td class="record-identity"><strong>'+esc(row.serialNum||'—')+'</strong><div class="small text-secondary">'+esc(row.processName)+'</div><div class="record-inline-source small text-secondary">'+esc(row.origin.name)+(row.origin.status==='archived'?' · 历史归档':row.origin.enabled?'':' · 已停用')+'</div><div class="record-inline-time small text-secondary">'+esc(formatDate(row.arrivedAt))+'</div><div class="record-inline-summary record-summary small">'+esc(row.subject||'—')+'</div></td><td class="record-node">'+esc(row.activityName==='sysInform'?'知会':row.activityName||'—')+'<div class="small text-secondary">'+(row.kind==='todo'?'待办到达':'待阅到达')+'</div></td><td class="record-summary-cell"><div class="record-summary">'+esc(row.subject||'—')+'</div></td><td class="record-source"><div>'+esc(row.origin.name)+'</div><span class="badge bg-'+(row.origin.status==='archived'?'secondary':row.origin.enabled?'green':'yellow')+'-lt">'+(row.origin.status==='archived'?'历史归档':row.origin.enabled?'现有连接':'已停用')+'</span></td><td class="record-time small text-secondary text-nowrap">'+esc(formatDate(row.arrivedAt))+'</td><td class="record-action"><button type="button" class="btn btn-sm" data-arrival-detail="'+index+'">查看详情</button></td></tr>').join('')+'</tbody></table></div>':'<div class="empty py-5"><p class="empty-title">暂无匹配的到达记录</p><p class="empty-subtitle text-secondary">可调整日期、业务范围或查看历史归档。</p></div>';host.querySelectorAll('[data-arrival-detail]').forEach(button=>button.onclick=()=>open(data.items[Number(button.dataset.arrivalDetail)],button));window.RecordUi.pager(container,{...data,change:page=>{filters.page=page;void load();}});}
async function load(){const request=++revision;controller?.abort();controller=new AbortController();try{const data=await api('/arrivals?'+new URLSearchParams({view:'ledger',...filters,pageSize:25}),undefined,{signal:controller.signal});if(!live()||request!==revision)return;error('');sourceOptions(data.sources);draw(data);monitor();}catch(e){if(live()&&request===revision)error(e.message+';可重试查询,已有记录仍保留。');}}
function apply(){const scope=get('arrival-scope').value;filters={q:get('arrival-query').value.trim(),scope,business:get('arrival-business').value,kind:get('arrival-kind').value,connectionId:filters.scope!==scope?'':get('arrival-connection').value,from:get('arrival-from').value,to:get('arrival-to').value,page:1};monitor();void load();}
get('arrival-submit').onclick=apply;get('arrival-query').onkeydown=event=>{if(event.key==='Enter')apply();};for(const id of ['arrival-scope','arrival-business','arrival-kind','arrival-connection'])get(id).onchange=apply;
async function refresh(){try{const next=await api('/bpm-scan');if(!live())return;status=next;monitor();const signature=JSON.stringify([status.runs.map(r=>[r.id,r.status]),status.connections.map(c=>[c.id,c.status])]);if(lastSignature&&signature!==lastSignature)await load();lastSignature=signature;const runs=status.runs.filter(r=>(filters.kind==='all'||(r.kind||'inform')===filters.kind)&&(!filters.connectionId||r.connectionId===filters.connectionId));if(runs[0]?.status==='error')container.querySelector('[data-monitor]').textContent+=' · 最近同步失败:'+runs[0].message;else if(runs[0]?.status==='success')container.querySelector('[data-monitor]').textContent+=' · 同步完成 '+formatDate(runs[0].finishedAt);}catch(e){if(live())error('监听状态读取失败:'+e.message);}finally{if(live())timer=setTimeout(refresh,status?.runs.some(r=>r.status==='running')?1500:10000);}}
if(get('scan-now'))get('scan-now').onclick=async()=>{const button=get('scan-now');button.disabled=true;try{for(const c of candidates())for(const kind of filters.kind==='all'?['todo','inform']:[filters.kind])await api('/bpm-scan/run',{connectionId:c.id,kind});if(live()){notify('只读同步已启动。');clearTimeout(timer);await refresh();}}catch(e){if(live())error(e.message+';已接受的同步请查看最新结果。');}finally{if(live())monitor();}};
await load();if(!live())return;await refresh();if(live()&&user.role==='admin'&&status){get('record-scan-settings').innerHTML='<details class="record-settings mt-3"><summary class="small text-secondary">同步设置</summary><form id="scan-config" class="d-flex flex-wrap gap-3 align-items-center mt-3"><label class="form-check form-switch mb-0"><input type="checkbox" class="form-check-input" id="scan-enabled" '+(status.config.enabled?'checked':'')+'><span class="form-check-label">自动同步</span></label><label class="d-flex gap-2 align-items-center">完整对账间隔(分钟)<input type="number" min="1" max="1440" required class="form-control scan-interval" id="scan-interval" value="'+status.config.intervalMinutes+'"></label><button type="submit" class="btn btn-sm">保存设置</button><a href="#calendar" class="small">业务日历</a></form></details>';get('scan-config').onsubmit=async event=>{event.preventDefault();const config=await api('/bpm-scan/config',{enabled:get('scan-enabled').checked,intervalMinutes:Number(get('scan-interval').value)});if(live()){status.config=config;monitor();notify('同步设置已保存。');}};}
}
return {configure,records};
})();
+4 -3
View File
@@ -2,6 +2,7 @@
window.AppNavigation=(()=>{
const primary=[['overview','overview'],['order-notifications','mail'],['records','file'],['exceptions','alert'],['assistant','spark'],['business-settings','rules'],['system-settings','settings']];
const groups={
records:['records','records-pdf'],
'order-notifications':['order-notifications','notification-execution','notification-orders','notification-batches','notification-history','schedule'],
'business-settings':['order-rules','rule-fields'],
'system-settings':['bpm','mail','storage','assistant-settings','health','users','audit']
@@ -24,7 +25,7 @@ window.AppNavigation=(()=>{
link:'M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2 M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2',
users:'M8 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M2 21v-3a6 6 0 0 1 12 0v3 M17 3a4 4 0 0 1 0 8 M18 15a5 5 0 0 1 4 5'
};
const routeIcons={'order-notifications':'overview','notification-execution':'play','notification-orders':'file','notification-batches':'batches','notification-history':'history',schedule:'calendar',calendar:'calendar',templates:'mail','notification-settings':'settings','order-rules':'rules','rule-fields':'fields',bpm:'link',mail:'mail',storage:'batches','assistant-settings':'spark',health:'alert',users:'users',audit:'history'};
const routeIcons={records:'history','records-pdf':'file','order-notifications':'overview','notification-execution':'play','notification-orders':'file','notification-batches':'batches','notification-history':'history',schedule:'calendar',calendar:'calendar',templates:'mail','notification-settings':'settings','order-rules':'rules','rule-fields':'fields',bpm:'link',mail:'mail',storage:'batches','assistant-settings':'spark',health:'alert',users:'users',audit:'history'};
const resolve=id=>aliases[id]||id;
const isConfiguration=id=>configuration.includes(resolve(id));
function sectionFor(id){id=resolve(id);if(isConfiguration(id))return 'order-notifications';return Object.keys(groups).find(section=>groups[section].includes(id))||null;}
@@ -38,8 +39,8 @@ window.AppNavigation=(()=>{
function links(ids,active,{views,esc},labels={}){return ids.map(id=>`<a class="nav-link settings-tab ${active===id?'active':''}" href="#${id}" ${active===id?'aria-current="page"':''}>${icon(routeIcons[id])}<span>${esc(labels[id]||views[id][0])}</span></a>`).join('');}
function renderTabs(container,{id,user,views,esc}){
const section=sectionFor(id);container.hidden=!section;
container.className='nav nav-segmented settings-tabs';container.setAttribute('aria-label',section==='order-notifications'?'订单通知管理导航':section==='business-settings'?'业务设置导航':'系统设置导航');
container.innerHTML=section?links(groups[section].filter(item=>item!=='users'||user.role==='admin'),isConfiguration(id)?'schedule':id,{views,esc},{schedule:'通知配置'}):'';
container.className='nav nav-segmented settings-tabs';container.setAttribute('aria-label',section==='records'?'记录导航':section==='order-notifications'?'订单通知管理导航':section==='business-settings'?'业务设置导航':'系统设置导航');
container.innerHTML=section?links(groups[section].filter(item=>item!=='users'||user.role==='admin'),isConfiguration(id)?'schedule':id,{views,esc},{schedule:'通知配置',records:'流程到达记录','records-pdf':'PDF 导出记录'}):'';
reveal(container);
}
function renderConfiguration(container,{id,views,esc}){
+16
View File
@@ -0,0 +1,16 @@
'use strict';
window.PdfRecordViews=(()=>{
let api,esc,formatDate,notify,user,filters;
function configure(options){if(user?.username!==options.user.username)filters={q:'',status:'',page:1};({api,esc,formatDate,notify,user}=options);}
async function records(container,isActive){
let disposed=false,revision=0,controller,pollTimer,searchTimer;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id),states={success:'已完成',running:'处理中',error:'失败',interrupted:'已中断'},files={available:'可下载',missing:'文件缺失',unavailable:'不可下载',pending:'等待导出'};
window.PageLifecycle?.onDispose(()=>{disposed=true;controller?.abort();clearTimeout(pollTimer);clearTimeout(searchTimer);});
container.innerHTML='<div class="alert alert-warning" data-record-error hidden role="alert"></div><section class="card"><div class="card-header flex-wrap gap-3"><h2 class="card-title">PDF 导出台账</h2><div class="ms-auto d-flex gap-2"><input class="form-control" id="record-search" maxlength="200" aria-label="搜索订单" placeholder="搜索订单号、项目或型号" value="'+esc(filters.q)+'"><select class="form-select" id="record-status" aria-label="任务状态"><option value="">全部状态</option>'+Object.entries(states).map(([value,label])=>'<option value="'+value+'" '+(filters.status===value?'selected':'')+'>'+label+'</option>').join('')+'</select></div></div><div data-pdf-list></div>'+window.RecordUi.footer+'</section><div class="small text-secondary mt-2">文件下载与存储归档分别记录 · 分类订单见 <a href="#notification-orders">通知订单</a></div>';
const detail=window.RecordUi.details(container,'PDF 导出详情'),archiveLabel=job=>job.archiveReceipts.some(r=>r.status==='success')?'已存储归档':job.archiveReceipts.some(r=>r.status==='running')?'归档中':job.archiveReceipts.some(r=>r.status==='error')?'归档失败':job.archiveKnown?'无归档记录':'归档状态未提供';
function open(job,button){const f=(label,value)=>window.RecordUi.field(esc,label,value);detail.show('<dl class="record-detail-grid">'+f('订单号',job.metadata?.order)+f('通知书编号',job.metadata?.serial)+f('项目',job.metadata?.project)+f('型号',job.metadata?.model)+f('导出状态',states[job.status]||job.status)+f('文件名',job.filename)+f('本地文件',files[job.fileStatus])+f('文件大小',job.fileBytes?job.fileBytes+' 字节':'—')+f('文件检查',formatDate(job.fileCheckedAt))+f('创建时间',formatDate(job.createdAt))+f('更新时间',formatDate(job.updatedAt))+f('导出来源','浏览器导出,未记录BPM连接关联')+f('错误信息',job.error)+f('存储归档',archiveLabel(job))+'</dl>'+job.archiveReceipts.map(r=>'<div class="record-receipt"><strong>'+esc(r.serverName||'存储服务器')+'</strong><div>'+esc(r.relativePath||'目录未记录')+'</div><div class="small text-secondary">'+esc(({success:'归档完成',running:'归档中',error:'归档失败'})[r.status]||r.status)+' · '+esc(formatDate(r.finishedAt))+'</div></div>').join('')+(job.downloadable?'<a class="btn btn-primary mt-3" href="/api/jobs/'+encodeURIComponent(job.jobId)+'/file">下载 PDF</a>':''),button);}
async function load(){const request=++revision;controller?.abort();controller=new AbortController();try{const data=await api('/jobs?'+new URLSearchParams({view:'ledger',...filters,pageSize:25}),undefined,{signal:controller.signal});if(!live()||request!==revision)return;container.querySelector('[data-record-error]').hidden=true;const host=container.querySelector('[data-pdf-list]');host.innerHTML=data.jobs.length?'<div class="table-responsive"><table class="table table-vcenter table-hover card-table record-ledger"><thead><tr><th scope="col">订单/通知书编号</th><th scope="col" class="record-node">项目/型号</th><th scope="col" class="record-export-state">导出状态</th><th scope="col" class="record-file">本地文件</th><th scope="col" class="record-source">存储归档</th><th scope="col" class="record-time">更新时间</th><th scope="col">操作</th></tr></thead><tbody>'+data.jobs.map((job,index)=>'<tr data-pdf-row><td class="record-identity"><strong>'+esc(job.metadata?.order||'订单号未记录')+'</strong><div class="small text-secondary">'+esc(job.metadata?.serial||'—')+'</div><div class="record-inline-export small">'+esc(states[job.status]||job.status)+' · '+esc(files[job.fileStatus])+'</div></td><td class="record-node">'+esc(job.metadata?.project||'—')+'<div class="small text-secondary">'+esc(job.metadata?.model||'—')+'</div></td><td class="record-export-state"><span class="badge bg-'+(job.status==='success'?'green':job.status==='running'?'blue':'red')+'-lt">'+esc(states[job.status]||job.status)+'</span></td><td class="record-file">'+esc(files[job.fileStatus]||'待检查')+'</td><td class="record-source">'+esc(archiveLabel(job))+'</td><td class="record-time small text-secondary text-nowrap">'+esc(formatDate(job.updatedAt))+'</td><td class="record-action"><div class="btn-list record-pdf-actions"><button class="btn btn-sm" type="button" data-pdf-detail="'+index+'">查看详情</button>'+(job.downloadable?'<a class="btn btn-sm" href="/api/jobs/'+encodeURIComponent(job.jobId)+'/file">下载 PDF</a>':'')+'</div></td></tr>').join('')+'</tbody></table></div>':'<div class="empty py-5"><p class="empty-title">暂无匹配的导出记录</p><p class="empty-subtitle text-secondary">可调整筛选,或从订单页面导出通知书。</p></div>';host.querySelectorAll('[data-pdf-detail]').forEach(button=>button.onclick=()=>open(data.jobs[Number(button.dataset.pdfDetail)],button));window.RecordUi.pager(container,{...data,change:page=>{filters.page=page;void load();}});clearTimeout(pollTimer);if(data.jobs.some(j=>j.status==='running'))pollTimer=setTimeout(load,3000);
}catch(e){if(live()&&request===revision){const error=container.querySelector('[data-record-error]');error.hidden=false;error.textContent=e.message+';请刷新重试。';}}}
get('record-search').oninput=()=>{clearTimeout(searchTimer);searchTimer=setTimeout(()=>{filters.q=get('record-search').value.trim();filters.page=1;void load();},300);};get('record-status').onchange=()=>{filters.status=get('record-status').value;filters.q=get('record-search').value.trim();filters.page=1;void load();};await load();
}
return {configure,records};
})();
+15
View File
@@ -0,0 +1,15 @@
'use strict';
window.RecordUi=(()=>{
function details(container,title){
const panel=document.createElement('section');panel.className='offcanvas offcanvas-end record-detail';panel.tabIndex=-1;panel.setAttribute('aria-label',title);
panel.innerHTML='<div class="offcanvas-header"><h2 class="offcanvas-title h3 mb-0"></h2><button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="关闭详情"></button></div><div class="offcanvas-body"></div>';panel.querySelector('h2').textContent=title;container.append(panel);
const instance=new window.tabler.Offcanvas(panel);let disposed=false;
const destroy=()=>new Promise(resolve=>{if(disposed)return resolve();disposed=true;let timer,finished=false;const finish=()=>{if(finished)return;finished=true;clearTimeout(timer);instance.dispose();panel.remove();resolve();};if(panel.classList.contains('show')||panel.classList.contains('showing')){panel.addEventListener('hidden.bs.offcanvas',finish,{once:true});instance.hide();timer=setTimeout(finish,600);}else finish();});
window.PageLifecycle?.onDispose(destroy);
return {show(html,trigger){if(disposed)return;panel.querySelector('.offcanvas-body').innerHTML=html;instance.show(trigger);},destroy};
}
function field(esc,label,value){return '<div class="record-detail-field"><dt>'+esc(label)+'</dt><dd>'+esc(value||'—')+'</dd></div>';}
function pager(container,{page,pageSize,total,change}){const count=container.querySelector('[data-record-count]'),previous=container.querySelector('[data-record-prev]'),next=container.querySelector('[data-record-next]');count.textContent=total?'共 '+total+' 条 · 第 '+page+' / '+Math.ceil(total/pageSize)+' 页':'共 0 条';previous.disabled=page<=1;next.disabled=page*pageSize>=total;previous.onclick=()=>change(page-1);next.onclick=()=>change(page+1);}
const footer='<div class="card-footer d-flex align-items-center gap-2"><span class="text-secondary small" data-record-count></span><div class="btn-list ms-auto"><button type="button" class="btn btn-sm" data-record-prev>上一页</button><button type="button" class="btn btn-sm" data-record-next>下一页</button></div></div>';
return {details,field,pager,footer};
})();