feat(records): move sync settings and preserve paginated navigation

This commit is contained in:
abaishu0730 committed 2026-10-20 18:35:41 +08:00
1 parent de30cb5706
commit c215e6ec6c
26 files changed
+201 -34

No files matched your search

+6
View File
@@ -1,5 +1,11 @@
# 开发交接(2026-10-20)
## 本轮同步设置与记录导航
用户明确要求实施[同步设置迁移与页签/分页优化](superpowers/plans/2026-10-20-records-navigation.md)。全局同步设置已迁入BPM连接页独立卡片,管理员保存、其他角色只读;记录页只保留摘要与手工同步。两页白名单状态写入hash和按账号隔离的sessionStorage,退出及认证失效清理;支持25/50/100条、数字页码、实际末页修正、加载禁重和失败重试。后台更新只提示,详情和列表不自动重画;显式查询不会把未应用输入混入翻页。
专项已验证页签/刷新/前后退/滚动位置、账号隔离、配置失败与保存离页、慢响应及详情清理;新鲜完整527项中526通过、0失败、1可选ZCode CLI跳过,254文件语法/6份文档36条本地链接/差异检查通过。已停止并保护备份原本机实例,恢复核验随后补记;账号/密钥/31份采样和草稿/规则及业务数据保留,自动发信false、version:1。最终验收与服务恢复见[本轮记录](records-navigation-verification-2026-10-20.md)。不发送真实邮件、不办理BPM、不操作服务机、不推送合并。
## 本轮订单与导出记录台账
用户选择A台账方案,确认删除连接后记录自动进入历史归档、默认聚焦订单相关流程。已实现统一Tabler分段导航(`#records`/`#records-pdf`)、分页台账、来源与日期筛选、详情侧栏和窄屏布局。Workspace删除事务保留安全来源档案;旧孤立来源不猜账号。PDF导出状态、文件可用性和存储归档回执独立,缺失或越界文件不显示下载;不按订单号猜BPM连接归属。
+2
View File
@@ -14,6 +14,8 @@
表单离开保护提供保存并继续/放弃/留下;密码、新建账号等敏感或不可自动提交表单只允许放弃或留下。刷新受浏览器原生 beforeunload 保护,不可能自定义其三个按钮。提交禁重、错误保留输入;持久保存与刷新失败分别提示;旧页/旧登录响应不得覆盖当前页面。
全局同步设置在BPM连接页独立维护,管理员保存、其他角色只读,沿用既有全局开关与完整对账间隔。两页记录通过显式查询应用筛选,hash和按账号的sessionStorage保留已应用条件/页码/条数/位置,退出及认证失效清理;不缓存业务记录或凭据。分页成功才提交数据和地址,失败可重试;后台更新仅提示,不重画阅读中的列表或详情。详见[导航与同步设置验收](records-navigation-verification-2026-10-20.md)。
## 唯一业务分类与窗口
Excel 的15类规则是唯一业务分类。流程名称、版本、配置节点必须精确对应;知会/待阅状态不能代替通知书节点。通知与更改分开,收件人和附件要求取对应分类规则。每个有效时段同类别汇总一封;空类不发,受阻类别不漏单发送。
@@ -0,0 +1,30 @@
# 同步设置与记录页导航验收
日期:2026-10-20(北京时间)。基线`de30cb5`。工作树`C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支`codex/modular-refactor`。本轮按用户明确授权的[实施计划](superpowers/plans/2026-10-20-records-navigation.md)完成;仅更新原本机测试实例,自动发信保持暂停,不发真实邮件、不办理BPM、不操作服务机、不推送合并。
## 交付行为
- 全局同步设置迁到BPM连接页独立卡片,对所有启用连接生效。管理员保存,其他角色只读;加载失败明确报错并允许重试,保存接入既有禁重和离页保护。记录页保留监听摘要与连接设置/立即同步入口。
- 两页的已应用筛选、实际页码和每页条数写入hash;sessionStorage按工作台账号只存白名单查询条件和滚动位置,不存记录或凭据。刷新、前后退及切回页签恢复,当前页签点击不重复查询。退出/认证失效清理缓存与旧URL条件。
- 查询统一由按钮/回车应用,未应用输入不混入翻页;查询和更换每页条数回第1页。Tabler分页展示条目范围、总数、数字页码和25/50/100条选项,窄屏紧凑显示。
- 两个接口保持原字段,合法越界页码修正到实际末页,空结果第1页。翻页加载禁重,成功才提交表格/页码/地址;失败保留上一成功结果并支持重试。
- 后台查询只提示更新,详情与正在阅读的列表保持稳定。明确刷新保留已应用筛选和有效页码;离页取消在途查询、定时器和详情。公共导航外壳保留。
## 已完成验证
- 使用105条真实临时SQLite到达记录及105个隔离导出任务验证超过三页的分页。专项26项通过(`output-record-nav-focused2.log`),另有配置读取失败/重试及离页慢请求专项2项通过(`output-record-nav-cleanup.log`)。
- 新增回归先复现:请求页99错误保持99;旧URL无法直达页3;加载时分页仍可点击;后退到裸地址误用缓存页码;退出后URL带入下个账号。上述缺口均修正并验证。
- 扩展页面回归8项通过(`output-record-nav-expanded.log`),覆盖独立页签、前后退、重新加载、重复点击、失败重试、末页缩减、未应用输入、每页条数、更新提示/详情稳定、滚动恢复、账号隔离和保存离页保护。旧页面测试已按“显式查询/更新提示”的已确认行为调整,没有取消原安全与数据断言。
- 桌面与390px隔离视觉复查已完成,截图在`output/verification/records-navigation-pagination-desktop.png`、`records-navigation-pagination-mobile.png`和`records-navigation-sync-settings.png`,仅为隔离样例。
- 本地复核检查URL白名单、身份清理、history索引、请求归属、失败保留与设置保存路径。业务监听、订单执行、归档和发送引擎未替换。
- 追加回归发现当前页签快捷处理曾扩大到其他页面,已限定为两个记录页;原工作总览同链接刷新保持,专项先失败后通过。最终完整套件重新从该源码启动,前次中止结果不作为全量验收依据。
锁定依赖`npm ci`成功,未新增依赖。最终254个JS/CJS文件语法检查通过,6份相关文档36条本地链接存在,差异检查通过。
新鲜完整`npm test`共527项,526通过、0失败、0取消、1项可选ZCode CLI跳过,退出码0;耗时810,179.2583毫秒(约13分30秒)。最终日志`output-record-navigation-full-test-final.log`。该完整套件启动后没有修改业务源码。
## 数据和服务
更新前只读快照:自动通知false、version:1,用户1个、采样31份、字段草稿31份、批次0个。原实例已停止,受当前用户ACL保护的备份为`%LOCALAPPDATA%/OrderNotificationAutomationBackups/records-navigation-20261020-180347`,7511文件摘要匹配、12份SQLite quick_check通过;未读取或复制account-recovery。证据`output/records-navigation-backup.json`。
完整测试已通过,接下来恢复原实例,核对原身份、密钥、规则、采样、草稿、订单、批次、设置、双端口和页面。同步配置沿用既有值,不通过实际设置改写制造验收数据。
@@ -0,0 +1,32 @@
# 同步设置迁移与记录页切换优化 Implementation Plan
> **For agentic workers:** 用户已明确要求实施本计划。使用 executing-plans 在当前工作树顺序实施,不自动分派子代理,不重复请求批准。
**Goal:** 同步设置归入BPM连接,两页台账具备可恢复、稳定的页签和分页。
**Architecture:** 独立记录状态模块只保存当前账号的已应用筛选和浏览位置;统一查询控制器管理请求、分页、失败回退和后台更新提示。路由保留hash参数和历史索引,连接页独立挂载同步设置,现有业务引擎保持。
**Tech Stack:** 现有原生JS、Tabler、Node/SQLite、Playwright,不增加依赖。
**Spec:** 用户本轮粘贴并授权实施的完整计划。默认每页25,支持25/50/100;同步设置对全部启用连接生效,管理员可保存,其他角色只读。已应用筛选写入hash,按账号存sessionStorage,退出清除;保存条件不保存记录或凭据。两个台账接口将超过末页的合法页码修正为实际末页,零记录第1页。
## Task 1:回归与后端分页
- [x] 写失败测试,验证超过三页数据、实际末页、空结果、同步设置归属与权限。
- [x] 修正两个台账查询的实际页码,保持原API结构与非法参数拒绝。
- [x] 迁移全局同步设置,独立加载失败/重试,管理员保存接入原禁重与离页保护。
## Task 2:记录状态和统一加载
- [x] 写失败浏览器测试:查询与未应用输入隔离、页码/条数/位置恢复、刷新/后退、重复点击和慢请求。
- [x] 新增按账号白名单状态模块,URL、sessionStorage和history索引一致;退出/失效清理,不保存数据/凭据。
- [x] 统一台账控制器管理待加载与已成功状态;翻页禁重、失败保留原页可重试,成功原子提交表格/页码/URL。统一显式查询,变更条件回第1页。
- [x] Tabler分页加入条目范围、数字页码和每页条数;按断点紧凑显示。
- [x] 后台查询仅提示更新,详情不重画;离页取消请求、定时器和详情。页签恢复各自状态,当前页签不重复加载,保留公共外壳。
## Task 3:完整验收和交付
- [ ] 专项验证失败/慢响应/空态/末页缩减/连续点击/状态隔离/历史保护/窄屏与滚动恢复。
- [ ] 同步文档、运行npm ci、新鲜完整npm test、全部JS/CJS语法与链接/差异检查并本地评审。
- [ ] 提交代码,保护备份后更新原本机实例,核对双端口、账号/密钥/规则/31份采样和草稿/业务数据与自动通知false/version1。
- [ ] 只读验收实际页面,提交记录并保留分支工作树;不发真实邮件、不办理BPM、不操作服务机、不推送合并。
@@ -1,5 +1,7 @@
# 订单与导出记录:台账式设计
后续同步设置位置、显式查询和导航状态按用户另行确认的[2026-10-20同步设置与导航计划](../plans/2026-10-20-records-navigation.md)更新;下文保留首轮台账设计记录。同步设置当前归入BPM连接页。
用户已选择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连接后记录自动转历史、默认只看订单相关流程。此确认授权本轮实施及原本机测试服务更新,不另行请求同项批准。
## 页面
+2
View File
@@ -80,6 +80,8 @@
| 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 | 本轮验收 |
| B07 全局同步设置、读取重试和保存 | BPM连接页;管理员保存,其他角色只读 | 所有启用连接共用,不改变现有值;禁重和离页保护 | 加载失败不造默认、失败留输入、保存继续;records-navigation | 本轮验收 |
| N03 记录页签、显式查询、分页与浏览位置 | 已登录;只存按账号隔离的白名单状态 | hash直达、前后退、25/50/100条、末页修正、更新提示 | 三页以上真实临时数据、失败/慢响应、旧页取消、退出清理、窄屏;records-navigation | 本轮验收 |
| M01 添加/编辑邮箱、保留空密码、保存/取消 | 管理员;本机/HTTPS、有效参数 | 加密SMTP/IMAP配置与版本 | 错误保留输入;mail-ui/mail-http | 已验证可用 |
| M02 检查邮箱、收取模板、自发测试 | 管理员;已托管非只读邮箱 | 验证状态、收件记录、自身测试记录 | SMTP/IMAP异常明确;未知结果先核验;mail-service | 已验证可用 |
| M03 只读邮箱、文件夹、日期/主题查询、正文/返回 | 管理员;IMAP;最多31天 | 只读Sent历史、To/Cc/附件名 | UID变化重查;不标读删移;history-* | 已验证可用 |
+3
View File
@@ -9,10 +9,13 @@ function createAssets(){
'/page-lifecycle.js':{path:path.join(webRoot,'modules/navigation/lifecycle.js'),type:'text/javascript'},
'/navigation.js':{path:path.join(webRoot,'modules/navigation/view.js'),type:'text/javascript'},
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
'/bpm-sync-settings.js':{path:path.join(webRoot,'modules/bpm/sync-settings.js'),type:'text/javascript'},
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
'/mail-history.js':{path:path.join(webRoot,'modules/mail/history.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
'/record-state.js':{path:path.join(webRoot,'modules/records/state.js'),type:'text/javascript'},
'/record-table.js':{path:path.join(webRoot,'modules/records/controller.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'},
+1
View File
@@ -41,6 +41,7 @@ class BpmScanStore{
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;
page=Math.min(page,Math.max(1,Math.ceil(total/pageSize)));
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};
}
+2 -1
View File
@@ -17,6 +17,7 @@ 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};
const actualPage=Math.min(page,Math.max(1,Math.ceil(filtered.length/pageSize)));
return {jobs:await publicJobs(filtered.slice((actualPage-1)*pageSize,actualPage*pageSize),outputDir,archiveStore),total:filtered.length,page:actualPage,pageSize};
}
module.exports={queryJobs,publicJobs,jobFile};
+1
View File
@@ -5,3 +5,4 @@ function fixture(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'job-records-
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');});
test('PDF ledger clamps to the actual last page including an empty filtered dataset',async t=>{const f=fixture(t),jobs=Array.from({length:101},(_,i)=>({jobId:'job-'+i,status:'error'}));const last=await queryJobs({jobs,outputDir:f.outputDir},{page:99});assert.equal(last.page,5);assert.equal(last.jobs.length,1);const empty=await queryJobs({jobs,outputDir:f.outputDir},{status:'success',page:99});assert.equal(empty.page,1);assert.equal(empty.total,0);});
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),{setup}=require('../fixtures/records-app.cjs');
test('global sync settings live only in BPM, keep stored values and expose read-only roles',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.getByRole('heading',{name:'全局同步设置',exact:true}).waitFor({timeout:3000});assert.equal(await page.getByLabel('自动到达同步',{exact:true}).isChecked(),false);assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'9');await page.goto(f.base+'/#records');await page.locator('[data-arrival-row]').first().waitFor();assert.equal(await page.locator('#scan-config').count(),0);await page.close();const reader=await f.page('#bpm','viewer');await reader.getByRole('heading',{name:'全局同步设置',exact:true}).waitFor();assert.equal(await reader.locator('#scan-config').count(),0);await reader.getByText('9 分钟',{exact:true}).waitFor();assert.deepEqual(f.scan.config(),{enabled:false,intervalMinutes:9});});
test('record pages retain independent applied queries across tabs, reload and history',async t=>{const f=await setup(t),page=await f.page('#records?page=3');await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);let calls=0;page.on('request',r=>{if(new URL(r.url()).pathname==='/api/arrivals')calls++;});await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.waitForTimeout(100);assert.equal(calls,0);await page.getByLabel('搜索流程记录',{exact:true}).fill('未应用条件');await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 4'));assert.equal(new URLSearchParams(page.url().split('?')[1]).has('q'),false);assert.equal(await page.locator('[data-arrival-row]').count(),25);await page.getByRole('button',{name:'上一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 3'));await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('[data-pdf-row]').first().waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));await page.getByRole('link',{name:'流程到达记录',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);await page.reload();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 3/);await page.goBack();await page.locator('[data-pdf-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 2/);});
test('pagination keeps the successful page on a failed request, supports retry and clamps a shrinking last page',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let held,requests=0,fail=true;await page.route('**/api/arrivals?*',async route=>{if(new URL(route.request().url()).searchParams.get('page')==='2'){requests++;if(fail){held=route;return;}}await route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-next]').disabled);assert.equal(await page.getByRole('button',{name:'下一页',exact:true}).isDisabled(),true);await page.waitForTimeout(50);await held.fulfill({status:503,json:{error:'隔离分页失败'}});await page.getByRole('button',{name:'重试加载',exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1/);assert.equal(page.url().includes('page=2'),false);fail=false;await page.getByRole('button',{name:'重试加载',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));assert.equal(requests,2);await page.getByRole('button',{name:'第 5 页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 5'));f.scan.db.exec("DELETE FROM arrivals WHERE task_id>'030'");await page.getByRole('button',{name:'刷新记录',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));assert.equal(await page.locator('[data-arrival-row]').count(),6);});
test('browser back to a bare record URL restores page one rather than the most recently cached page',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 2'));await page.goBack();await page.waitForFunction(()=>document.querySelector('[data-record-count]').textContent.includes('第 1'),null,{timeout:2500});assert.equal(new URL(page.url()).hash,'#records');});
test('logout clears saved record filters and the next account starts with its own defaults',async t=>{const f=await setup(t),page=await f.page('#records?page=3');await page.locator('[data-arrival-row]').first().waitFor();await page.getByRole('button',{name:'退出',exact:true}).click();await page.locator('#login-form').waitFor();assert.equal(await page.evaluate(()=>Object.keys(sessionStorage).filter(k=>k.startsWith('ona-record-navigation:')).length),0);await page.locator('#username').fill('viewer');await page.locator('#password').fill(f.password);await page.locator('#login-form button').click();await page.locator('[data-arrival-row]').first().waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/第 1/);});
test('background updates preserve open details and drafts until explicit refresh, and page size uses applied filters',async t=>{const f=await setup(t),page=await f.page('#records','admin',true);await page.locator('[data-arrival-row]').first().waitFor();await page.getByLabel('搜索流程记录',{exact:true}).fill('未应用的关键字');await page.getByRole('button',{name:'查看详情',exact:true}).first().click();await page.getByRole('dialog',{name:'流程到达详情'}).waitFor();f.scan.complete(f.scan.begin(f.connection.id,'admin'),f.connection.id,[{taskId:'NEW',serialNum:'NEW',source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'后台新增记录',arrivalDay:'2026-10-21',arrivedAt:'2026-10-21T01:00:00Z'}]);await page.clock.fastForward(11000);await page.getByText('记录有更新。',{exact:true}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/105/);assert.equal(await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).count(),0);await page.getByRole('dialog').getByText('订单样例 000',{exact:true}).waitFor();await page.getByRole('button',{name:'关闭详情',exact:true}).click();await page.clock.fastForward(400);await page.locator('.card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.locator('[data-arrival-row]').filter({hasText:'后台新增记录'}).waitFor();assert.match(await page.locator('[data-record-count]').innerText(),/106/);assert.equal(await page.getByLabel('搜索流程记录',{exact:true}).inputValue(),'未应用的关键字');await page.getByLabel('每页条数',{exact:true}).selectOption('50');await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-row]').length===50);assert.equal(new URLSearchParams(page.url().split('?')[1]).has('q'),false);assert.equal(await page.evaluate(()=>JSON.stringify(sessionStorage).includes('后台新增记录')),false);});
test('record scroll positions survive page changes, tab return and reload without widening the mobile viewport',async t=>{const f=await setup(t),page=await f.page('#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,850));await page.waitForTimeout(250);await page.goto(f.base+'/#records-pdf');await page.locator('[data-pdf-row]').first().waitFor();await page.evaluate(()=>window.scrollTo(0,600));await page.waitForTimeout(250);await page.goto(f.base+'/#records?page=2');await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.reload();await page.locator('[data-arrival-row]').first().waitFor();await page.waitForFunction(()=>Math.abs(window.scrollY-850)<80);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);});
test('sync configuration failures retain input and use the shared save-and-leave guard',async t=>{const f=await setup(t),page=await f.page('#bpm');await page.locator('#scan-config').waitFor();let reject=true;await page.route('**/api/bpm-scan/config',route=>reject?route.fulfill({status:503,json:{error:'隔离保存失败'}}):route.continue());await page.getByLabel('完整对账间隔(分钟)',{exact:true}).fill('11');await page.getByRole('button',{name:'保存同步设置',exact:true}).click();await page.locator('#scan-config').getByText('隔离保存失败',{exact:true}).waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'11');assert.equal(f.scan.config().intervalMinutes,9);await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.getByRole('dialog',{name:'未保存的修改'}).waitFor();reject=false;await page.getByRole('button',{name:'保存并继续',exact:true}).click();await page.locator('[data-arrival-row]').first().waitFor();assert.equal(f.scan.config().intervalMinutes,11);});
test('missing sync configuration shows an error and retry without replacing the connection page or inventing defaults',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let fail=true;await page.route('**/api/bpm-scan',route=>fail?route.fulfill({status:503,json:{error:'配置暂不可用'}}):route.continue());await page.goto(f.base+'/#bpm');await page.getByRole('button',{name:'重试读取同步设置',exact:true}).waitFor();assert.equal(await page.locator('#scan-config').count(),0);await page.getByRole('heading',{name:'隔离测试来源',exact:true}).waitFor();fail=false;await page.getByRole('button',{name:'重试读取同步设置',exact:true}).click();await page.locator('#scan-config').waitFor();assert.equal(await page.getByLabel('完整对账间隔(分钟)',{exact:true}).inputValue(),'9');});
test('leaving a slow record page cancels its request and late data cannot replace the PDF tab',async t=>{const f=await setup(t),page=await f.page('#records');await page.locator('[data-arrival-row]').first().waitFor();let release;const received=new Promise(resolve=>release=resolve);await page.route('**/api/arrivals?*',route=>{if(new URL(route.request().url()).searchParams.get('page')==='2')release(route);else void route.continue();});await page.getByRole('button',{name:'下一页',exact:true}).click();const held=await received;await page.getByRole('link',{name:'PDF 导出记录',exact:true}).click();await page.locator('[data-pdf-row]').first().waitFor();await held.fulfill({json:{items:[],total:0,page:2,pageSize:25,sources:[]}}).catch(()=>{});assert.equal(await page.locator('[data-arrival-row]').count(),0);assert.equal(await page.locator('[data-pdf-row]').count(),25);assert.equal(new URL(page.url()).hash,'#records-pdf');});
test('the record same-tab shortcut does not suppress the existing refresh behavior of other pages',async t=>{const f=await setup(t),page=await f.page('#overview');await page.locator('#workspace-automation').waitFor();const read=page.waitForRequest(r=>new URL(r.url()).pathname==='/api/overview',{timeout:2000});await page.getByRole('link',{name:'工作总览',exact:true}).click();await read;});
+4 -4
View File
@@ -26,15 +26,15 @@ test('ledger browser keeps filtering, details and addressable PDF navigation ind
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.getByText('记录有更新。',{exact:true}).waitFor({timeout:20000});await page.locator('.card-header').getByRole('button',{name:'刷新记录',exact:true}).click();await page.getByText('后台扫描新增',{exact:true}).filter({visible:true}).waitFor();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.waitForFunction(()=>!document.querySelector('[data-record-query]').disabled);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'));
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.getByRole('button',{name:'查询',exact:true}).click();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.getByRole('button',{name:'查询',exact:true}).click();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=>{
@@ -44,7 +44,7 @@ test('todo arrival queries stay separate from inform history and cannot invoke a
});
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('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;await page.locator('#record-search').fill('UNMATCHED');await held.continue();await page.waitForFunction(()=>!document.querySelector('[data-record-query]').disabled);assert.equal(await page.locator('#record-search').inputValue(),'UNMATCHED');const searched=page.waitForRequest(request=>new URL(request.url()).pathname==='/api/jobs'&&new URL(request.url()).searchParams.get('q')==='UNMATCHED',{timeout:3000});await page.getByRole('button',{name:'查询',exact:true}).click();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);
+1
View File
@@ -261,6 +261,7 @@ test('refresh and logout release BPM control before rendering or dropping authen
const element=id=>{if(!elements.has(id))elements.set(id,{innerHTML:'',textContent:'',classList:{remove(){}},querySelector(){return {disabled:false};}});return elements.get(id);};
const context=vm.createContext({Intl,setTimeout,clearInterval,location:{hash:'#overview'},history:{replaceState(){}},document:{querySelector:element,querySelectorAll:()=>[],addEventListener(){}},window:{addEventListener(){},PageLifecycle:{guard:fn=>fn(),dispose:async()=>{},attach(){},bind(){}},AppNavigation:{primary:[],resolve:id=>id,sectionFor:()=>null,renderTabs(){},isConfiguration:()=>false},BpmLogin:{dispose:async()=>events.push('release')},WorkspaceViews:{overview:async()=>events.push('render')}}});
const source=fs.readFileSync(path.join(__dirname,'../../web/app.js'),'utf8').replace(/boot\(\)\.catch[\s\S]*$/,'');
vm.runInContext(fs.readFileSync(path.join(__dirname,'../../web/modules/records/state.js'),'utf8'),context);
vm.runInContext(source,context);
await vm.runInContext("currentUser={username:'alice',role:'admin'};renderView()",context);
assert.deepEqual(events,['release','render']);events.length=0;
+1
View File
@@ -9,3 +9,4 @@ test('deletion preserves a safe source archive across restart, while pause stays
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,'原账号');});
test('ledger clamps a valid page beyond the last page and reports page one for empty results',t=>{const f=fixture(t);f.scan.complete(f.scan.begin(f.c.id,'admin'),f.c.id,Array.from({length:101},(_,i)=>row(String(i))));const last=query(f,{page:99});assert.equal(last.page,5);assert.equal(last.items.length,1);const empty=query(f,{q:'absent',page:99});assert.equal(empty.page,1);assert.equal(empty.total,0);assert.deepEqual(empty.items,[]);});
+6
View File
@@ -0,0 +1,6 @@
'use strict';
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Store}=require('../../src/modules/dashboard/store.cjs'),{WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs'),{loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
async function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'record-nav-')),store=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),scan=new BpmScanStore(path.join(dir,'scan')),password='Record-nav-test-123',actor={username:'admin',role:'admin'};store.bootstrap('admin',password);for(const role of ['viewer','operator'])store.addUser({username:role,password,role},'admin');const connection=workspace.createConnection({name:'隔离测试来源',owner:'admin'},actor,store.users());scan.saveConfig({enabled:false,intervalMinutes:9});scan.complete(scan.begin(connection.id,'admin'),connection.id,Array.from({length:105},(_,i)=>({taskId:String(i).padStart(3,'0'),serialNum:'TEST-'+String(i).padStart(3,'0'),source:'portal-v4',processName:'海外运营订单评审',activityName:'通知节点',subject:'订单样例 '+String(i).padStart(3,'0'),arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T01:00:00Z'})),connection);for(let i=0;i<105;i++)store.recordJob({jobId:'job-'+String(i).padStart(3,'0'),status:'error',metadata:{order:'PDF-'+String(i).padStart(3,'0')},error:'隔离导出失败'});const scanner=new BpmScanner({store:scan,workspace,manager:{scanArrivals:async()=>[]},settings:()=>store.settings()}),server=createDashboard({store,workspace,scanner,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions()),base='http://127.0.0.1:'+server.address().port;
t.after(async()=>{await browser.close();await scanner.stop();server.closeAllConnections();await new Promise(r=>server.close(r));scan.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {store,workspace,scan,connection,browser,base,password,async page(route='#records',username='admin',clock=false){const page=await browser.newPage({viewport:{width:1280,height:900}});if(clock)await page.clock.install();await page.goto(base+'/'+route);await page.locator('#username').fill(username);await page.locator('#password').fill(password);await page.locator('#login-form button').click();return page;}};}
module.exports={setup};
+2
View File
@@ -52,3 +52,5 @@
.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}}
.record-pagination{display:flex;flex-wrap:wrap;gap:12px;align-items:center}.record-pagination>nav{margin-left:auto}.record-pagination .form-select{width:75px}.record-page-gap{padding:0 4px}.record-pagination>label{margin-left:auto}@media(max-width:767px){.record-pagination>nav{margin-left:0;flex:1 0 100%;justify-content:center}.record-pagination [data-record-pages] button:not([aria-current]){display:none}.record-pagination .record-page-gap{display:none}.record-pagination [data-record-count]{font-size:.75rem}.card-header:has(#record-search){align-items:stretch}.card-header:has(#record-search)>div{flex-wrap:wrap}.card-header #record-search{min-width:160px}}
+12 -9
View File
@@ -11,7 +11,7 @@ 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;
const work=(async()=>{const controller=new AbortController(),timeout=setTimeout(()=>controller.abort(),30000);const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal;
try {const response=await fetch('/api'+route,{signal:combined,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:hasBody?'POST':'GET',headers:hasBody?{'Content-Type':'application/json'}:{},body:hasBody?JSON.stringify(body):undefined});const result=await response.json();
if(!response.ok){if(response.status===401&&currentUser&&originActive()&&(!ownerCheck||ownerCheck())){currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Object.assign(Error(result.error||'操作失败,请核对输入。'),{status:response.status,outcome:'rejected'});}if(write&&originActive())window.PageLifecycle?.succeeded(submission);return result;
if(!response.ok){if(response.status===401&&currentUser&&originActive()&&(!ownerCheck||ownerCheck())){window.RecordState?.clear();currentUser=null;++viewGeneration;await window.PageLifecycle?.dispose();window.BpmLogin?.dispose();await boot();}throw Object.assign(Error(result.error||'操作失败,请核对输入。'),{status:response.status,outcome:'rejected'});}if(write&&originActive())window.PageLifecycle?.succeeded(submission);return result;
}catch(error){if(write&&originActive())window.PageLifecycle?.failed(submission);if(write&&(error.name==='AbortError'||error instanceof TypeError)){if(originActive()&&!managedOutcome)void verifyUncertainWrite(route,originActive);throw Object.assign(Error('结果待核实:请求超时或连接中断,正在查询状态;不会自动重试。'),{outcome:'uncertain'});}throw error;
}finally{clearTimeout(timeout);}})();if(write)pendingWrites.set(key,{user:originUser,work});try{return await work;}finally{if(write&&pendingWrites.get(key)?.work===work)pendingWrites.delete(key);}
}
@@ -31,11 +31,11 @@ function notify(message,type='success') {
const flash=document.createElement('div');flash.id='flash';flash.className='alert alert-'+type+' shadow';flash.setAttribute('role','alert');flash.textContent=message;document.body.append(flash);setTimeout(()=>flash.remove(),6500);
}
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="#${id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${window.AppNavigation.icon(symbol)}</span><span class="nav-link-title">${id==='order-notifications'?'订单通知管理':views[id][0]}</span></a></li>`;}
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="${window.RecordState?.href(id)||'#'+id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${window.AppNavigation.icon(symbol)}</span><span class="nav-link-title">${id==='order-notifications'?'订单通知管理':views[id][0]}</span></a></li>`;}
function shell() {
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${window.AppNavigation.primary.map(([id,symbol])=>navItem(id,symbol)).join('')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><a class="badge bg-secondary-lt text-decoration-none" id="automation-status" href="#notification-settings" title="正在读取服务端通知状态" aria-live="polite">通知状态待确认</a></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><a class="btn btn-sm" href="#account">修改密码</a><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><nav id="view-breadcrumb" class="mb-2" aria-label="设置导航" hidden></nav><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl"><nav class="nav nav-segmented settings-tabs" id="settings-tabs" aria-label="页面导航" hidden></nav><div id="content"></div></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await window.PageLifecycle.dispose();await boot();});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>renderView()).catch(error=>notify(error.message,'danger'));
document.querySelector('#logout').onclick=()=>window.PageLifecycle.guard(async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});window.RecordState.clear();currentUser=null;clearInterval(refreshTimer);await window.PageLifecycle.dispose();await boot();});
document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>window.RecordTable?.active?window.RecordTable.active.refresh():renderView()).catch(error=>notify(error.message,'danger'));
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{const menu=document.querySelector('#sidebar-menu');menu.classList.remove('show');if(menu.classList.contains('collapsing'))menu.addEventListener('shown.bs.collapse',()=>menu.classList.remove('show'),{once:true});document.querySelector('.navbar-toggler').setAttribute('aria-expanded','false');});
}
function empty(title,text){return `<div class="empty-state"><div class="avatar avatar-lg bg-blue-lt mb-3">▤</div><h3>${title}</h3><p class="text-secondary">${text}</p></div>`;}
@@ -86,19 +86,22 @@ function configurationHost(container){
}
async function renderView() {
if(!currentUser)return;
const routeId=window.RecordState.route(location.hash)||'overview',resolved=window.AppNavigation.resolve(routeId);
if(window.RecordState.isRecord(location.hash)&&currentView===resolved&&window.RecordTable?.active?.view===resolved){historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;return window.RecordTable.active.navigate();}
const wasRecord=['records','records-pdf'].includes(currentView);
const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser;
await window.PageLifecycle?.dispose();
await window.BpmLogin?.dispose();if(!isActive())return;
const requested=window.AppNavigation.resolve(location.hash.slice(1) || 'overview');currentView=Object.hasOwn(views,requested)?requested:'overview';
const requested=resolved;currentView=Object.hasOwn(views,requested)?requested:'overview';
if(currentView==='users' && currentUser.role!=='admin')currentView='overview';
historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;history.replaceState({appIndex:historyIndex},'','#'+currentView);
historyIndex=Number.isInteger(history.state?.appIndex)?history.state.appIndex:historyIndex;history.replaceState({...history.state,appIndex:historyIndex},'',window.RecordState.isRecord(location.hash)?location.hash:'#'+currentView);
const section=window.AppNavigation.sectionFor(currentView);
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||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 container=document.querySelector('#content');if(!(wasRecord&&['records','records-pdf'].includes(currentView)))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,'records-pdf':viewPdfRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,users:window.AccountViews?.users,audit:viewAudit,rules:viewRules}[currentView];
@@ -112,11 +115,11 @@ 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.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);}
function enter(){window.RecordState.configure(currentUser,({hash,push})=>{if(push&&location.hash!==hash)history.pushState({appIndex:++historyIndex},'',hash);else history.replaceState({...history.state,appIndex:historyIndex},'',hash);});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});});
document.addEventListener('click',event=>{const link=event.target.closest('a[href^="#"]');if(!currentUser||!link||event.ctrlKey||event.metaKey)return;event.preventDefault();window.PageLifecycle.guard(()=>{if(location.hash!==link.hash){history.pushState({appIndex:++historyIndex},'',link.hash);}return renderView();});});
document.addEventListener('click',event=>{const link=event.target.closest('a[href^="#"]');if(!currentUser||!link||event.ctrlKey||event.metaKey)return;event.preventDefault();if(location.hash===link.hash&&window.RecordState.isRecord(link.hash))return;window.PageLifecycle.guard(()=>{if(location.hash!==link.hash){history.pushState({appIndex:++historyIndex},'',link.hash);}return renderView();});});
window.addEventListener('hashchange',()=>{
if(!currentUser)return;
if(historyTransition?.kind==='restore'){const target=historyTransition.target;historyTransition=null;window.PageLifecycle.guard(()=>{historyTransition={kind:'approved'};history.go(target-historyIndex);});return;}
+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="/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>
<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-sync-settings.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-state.js" defer></script><script src="/record-table.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>
+7 -9
View File
@@ -4,23 +4,21 @@ window.OrderViews=(()=>{
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();});
filters=window.RecordState.read('records');let disposed=false,status=null,timer,statusController;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id);
window.PageLifecycle?.onDispose(()=>{disposed=true;clearTimeout(timer);statusController?.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>';
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" data-record-query>查询</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>';
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);}}
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));sourceOptions(data.sources);monitor();}
const table=window.RecordTable.mount({view:'records',container,isActive:live,api,onCommit:next=>{filters=next;},render:draw,readDraft(){const scope=get('arrival-scope').value;return {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};},writeDraft(next){for(const [field,id]of Object.entries({q:'arrival-query',scope:'arrival-scope',business:'arrival-business',kind:'arrival-kind',connectionId:'arrival-connection',from:'arrival-from',to:'arrival-to'}))get(id).value=next[field];}});
async function refresh(){clearTimeout(timer);try{statusController?.abort();statusController=new AbortController();const next=await api('/bpm-scan',undefined,{signal:statusController.signal});if(!live())return;status=next;monitor();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,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('同步设置已保存。');}};}
await table.ready;if(!live())return;await refresh();
}
return {configure,records};
})();
+13
View File
@@ -0,0 +1,13 @@
'use strict';
window.BpmSyncSettings={async mount(host,{api,user,notify,isActive}){
let disposed=false;const controller=new AbortController(),live=()=>!disposed&&isActive();window.PageLifecycle?.onDispose(()=>{disposed=true;controller.abort();});
host.innerHTML='<section class="card mt-4"><div class="card-header"><h2 class="card-title">全局同步设置</h2></div><div class="card-body"><p class="text-secondary small">对所有启用的 BPM 连接生效。</p><div data-sync-settings>正在读取同步配置…</div></div></section>';
const panel=host.querySelector('[data-sync-settings]');
async function load(){panel.textContent='正在读取同步配置…';try{const {config}=await api('/bpm-scan',undefined,{signal:controller.signal});if(!live())return;
if(!config||typeof config.enabled!=='boolean'||!Number.isInteger(config.intervalMinutes))throw Error('同步配置响应无效');
if(user.role!=='admin'){panel.innerHTML='<dl class="datagrid"><div class="datagrid-item"><dt class="datagrid-title">自动到达同步</dt><dd class="datagrid-content">'+(config.enabled?'已开启':'已暂停')+'</dd></div><div class="datagrid-item"><dt class="datagrid-title">完整对账间隔</dt><dd class="datagrid-content">'+config.intervalMinutes+' 分钟</dd></div></dl><a href="#calendar" class="small">查看业务日历</a>';return;}
panel.innerHTML='<form id="scan-config"><div class="row g-3 align-items-end"><div class="col-md-5"><label class="form-check form-switch"><input type="checkbox" class="form-check-input" id="scan-enabled" '+(config.enabled?'checked':'')+'><span class="form-check-label">自动到达同步</span></label></div><div class="col-md-4"><label class="form-label" for="scan-interval">完整对账间隔(分钟)</label><input type="number" class="form-control" id="scan-interval" min="1" max="1440" required value="'+config.intervalMinutes+'"></div><div class="col-md-3"><button class="btn btn-primary" type="submit">保存同步设置</button></div></div><div class="small text-secondary mt-3">关闭后暂停自动监听与对账,仍可手工同步。运行日期在 <a href="#calendar">业务日历</a> 维护。</div><div class="small mt-2" data-sync-result role="status"></div></form>';
const form=panel.querySelector('form');form.onsubmit=async event=>{event.preventDefault();const input={enabled:form.querySelector('#scan-enabled').checked,intervalMinutes:Number(form.querySelector('#scan-interval').value)},result=form.querySelector('[data-sync-result]');try{await api('/bpm-scan/config',input);if(!live())return;result.textContent='同步设置已保存。';const ok=await window.PageLifecycle.afterSave(async()=>{const fresh=await api('/bpm-scan',undefined,{signal:controller.signal});if(!fresh.config||fresh.config.enabled!==input.enabled||fresh.config.intervalMinutes!==input.intervalMinutes)throw Error('配置已变化,请重新核对。');},'同步设置已保存。',notify,live);if(live()&&!ok)result.textContent='保存已生效,刷新失败,请核对最新状态,无需重复提交。';}catch(e){if(live()){result.textContent=e.message;throw e;}}};window.PageLifecycle?.bind();
}catch(e){if(live()){panel.innerHTML='<div class="text-danger" role="alert"></div><button class="btn btn-sm mt-2" type="button">重试读取同步设置</button>';panel.querySelector('[role="alert"]').textContent='读取失败:'+e.message;panel.querySelector('button').onclick=load;}}}
await load();
}};
+2 -1
View File
@@ -168,11 +168,12 @@ window.BpmLogin=(()=>{
}
try{
data=await api('/workspace');if(!live())return;connections=data.connections||[];
container.innerHTML=`<div data-bpm-feedback hidden role="alert"></div><div class="connection-layout bpm-layout"><div><div id="bpm-list"></div></div>${user.role==='admin'?`<form class="card" id="connection-create"><div class="card-header"><h2 class="card-title">添加 BPM 连接</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="connection-name">连接名称</label><input class="form-control" id="connection-name" required maxlength="100" placeholder="例如:业务团队 BPM"></div><div><label class="form-label required" for="connection-owner">负责人</label><select class="form-select" id="connection-owner" required><option value="">请选择负责人</option>${(data.members||[]).filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}">${esc(m.username)}</option>`).join('')}</select></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建连接</button></div></form>`:''}</div><div id="bpm-remote" aria-live="polite"></div>`;
container.innerHTML=`<div data-bpm-feedback hidden role="alert"></div><div class="connection-layout bpm-layout"><div><div id="bpm-list"></div></div>${user.role==='admin'?`<form class="card" id="connection-create"><div class="card-header"><h2 class="card-title">添加 BPM 连接</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="connection-name">连接名称</label><input class="form-control" id="connection-name" required maxlength="100" placeholder="例如:业务团队 BPM"></div><div><label class="form-label required" for="connection-owner">负责人</label><select class="form-select" id="connection-owner" required><option value="">请选择负责人</option>${(data.members||[]).filter(m=>m.role!=='viewer').map(m=>`<option value="${esc(m.username)}">${esc(m.username)}</option>`).join('')}</select></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建连接</button></div></form>`:''}</div><div id="bpm-remote" aria-live="polite"></div><div id="bpm-sync-settings"></div>`;
if(user.role==='admin')$('#connection-create').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type=submit]');button.disabled=true;try{const result=await api('/connections',{name:$('#connection-name').value.trim(),owner:$('#connection-owner').value});if(!live())return;++statusRevision;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}};
drawCards();
connections.filter(c=>c.status!=='disabled'&&authorized(c)).forEach(c=>loadAccount(c.id).then(refreshAccountSummary).catch(error=>feedback(error.message)));
statusTimer=setTimeout(refreshStatus,5000);
await window.BpmSyncSettings?.mount($('#bpm-sync-settings'),{api,user,notify,isActive:live});
}catch(error){if(live())throw error;}
}
return {mount,dispose};
+1 -1
View File
@@ -36,7 +36,7 @@ window.AppNavigation=(()=>{
if(item.left<box.left+5)container.scrollLeft-=box.left+5-item.left;
else if(item.right>box.right-5)container.scrollLeft+=item.right-box.right+5;
}
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 links(ids,active,{views,esc},labels={}){return ids.map(id=>`<a class="nav-link settings-tab ${active===id?'active':''}" href="${window.RecordState?.href(id)||'#'+id}" ${['records','records-pdf'].includes(id)?'data-record-route="'+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==='records'?'记录导航':section==='order-notifications'?'订单通知管理导航':section==='business-settings'?'业务设置导航':'系统设置导航');
+30
View File
@@ -0,0 +1,30 @@
'use strict';
window.RecordTable=(()=>{
function mount({view,container,isActive,api,readDraft,writeDraft,render,onCommit=()=>{}}){
let disposed=false,busy=false,requestId=0,controller,pollController,timer,scrollTimer,applied=window.RecordState.read(view),data=null,signature='',retry=null;
const live=()=>!disposed&&isActive(),get=selector=>container.querySelector(selector),list=get('[data-arrival-list],[data-pdf-list]'),error=get('[data-record-error]');
const notice=document.createElement('div');notice.className='alert alert-info mt-2';notice.hidden=true;notice.innerHTML='<span>记录有更新。</span> <button class="btn btn-sm" type="button">刷新记录</button>';list.before(notice);
const loading=document.createElement('div');loading.className='small text-secondary px-3 py-2';loading.setAttribute('role','status');loading.hidden=true;loading.textContent='正在加载记录…';list.before(loading);
const refresh=document.createElement('button');refresh.type='button';refresh.className='btn btn-sm';refresh.textContent='刷新记录';const actions=get('.card-header .btn-list');if(actions)actions.prepend(refresh);else get('.card-header').append(refresh);
const initialScroll=window.RecordState.position(view),snapshot=value=>JSON.stringify(value,(key,item)=>['fileCheckedAt','lastSeenAt'].includes(key)?undefined:item);
function controls(){list.setAttribute('aria-busy',String(busy));loading.hidden=!busy;container.querySelectorAll('[data-record-prev],[data-record-next],[data-record-page],[data-record-size],[data-record-query]').forEach(button=>{button.disabled=busy||button.dataset.boundary==='true';});refresh.disabled=busy;notice.querySelector('button').disabled=busy;}
function feedback(message){error.hidden=!message;error.replaceChildren();if(!message)return;const text=document.createElement('span');text.textContent=message;error.append(text);if(retry){const button=document.createElement('button');button.type='button';button.className='btn btn-sm ms-2';button.textContent='重试加载';button.onclick=()=>load(retry.filters,retry.options);error.append(button);}}
function pager(){if(!data)return;window.RecordUi.pager(container,{...data,change:page=>{if(!busy)void load({...applied,page},{push:true,scroll:'top'});},resize:pageSize=>{if(!busy)void load({...applied,page:1,pageSize},{push:true,scroll:'top'});}});controls();}
async function load(filters,options={}){
if(!live())return;const id=++requestId;controller?.abort();pollController?.abort();controller=new AbortController();if(data)window.RecordState.capture(view,applied);busy=true;retry=null;feedback('');controls();const next=window.RecordState.normalize(view,filters);
try{const result=await api((view==='records'?'/arrivals?':'/jobs?')+new URLSearchParams({view:'ledger',...next}),undefined,{signal:controller.signal});if(!live()||id!==requestId)return;
applied={...next,page:result.page,pageSize:result.pageSize};onCommit(applied);render(result);data=result;signature=snapshot(result);notice.hidden=true;window.RecordState.commit(view,applied,{push:!!options.push});if(options.draft)writeDraft(applied);busy=false;pager();
await new Promise(resolve=>requestAnimationFrame(resolve));if(!live()||id!==requestId)return;if(options.scroll==='restore')window.scrollTo(0,options.y??window.RecordState.position(view));else if(options.scroll==='top')list.scrollIntoView({block:'start'});window.RecordState.capture(view,applied);
}catch(e){if(!live()||id!==requestId)return;busy=false;retry={filters:next,options};if(data&&options.draft)window.RecordState.commit(view,applied);feedback('读取失败:'+e.message+(data?';仍显示上次成功的记录。':''));pager();controls();}
}
function apply(){if(busy)return;void load({...applied,...readDraft(),page:1},{push:true,scroll:'top'});}
container.querySelectorAll('[data-record-query]').forEach(button=>button.onclick=apply);
const inputs=container.querySelectorAll('.record-filters input,.record-filters select,#record-search,#record-status');for(const input of inputs)input.addEventListener('keydown',event=>{if(event.key==='Enter'){event.preventDefault();apply();}});
async function check(){if(!live())return;try{if(data&&!busy){pollController=new AbortController();const result=await api((view==='records'?'/arrivals?':'/jobs?')+new URLSearchParams({view:'ledger',...applied}),undefined,{signal:pollController.signal});if(live()&&!busy)notice.hidden=snapshot(result)===signature;}}catch{}finally{if(live())timer=setTimeout(check,10000);}}
refresh.onclick=notice.querySelector('button').onclick=()=>{if(!busy)void load(applied,{scroll:'keep'});};
const scroll=()=>{clearTimeout(scrollTimer);scrollTimer=setTimeout(()=>{if(live()&&data&&!busy)window.RecordState.capture(view,applied);},150);},pagehide=()=>{if(data)window.RecordState.capture(view,applied);};window.addEventListener('scroll',scroll,{passive:true});window.addEventListener('pagehide',pagehide);
const handle={view,refresh:()=>load(applied,{scroll:'keep'}),navigate(){return load(window.RecordState.read(view),{draft:true,scroll:'restore',y:window.RecordState.position(view)});},get busy(){return busy;},dispose(){if(disposed)return;disposed=true;controller?.abort();pollController?.abort();clearTimeout(timer);clearTimeout(scrollTimer);window.removeEventListener('scroll',scroll);window.removeEventListener('pagehide',pagehide);if(data)window.RecordState.capture(view,applied);if(window.RecordTable.active===handle)window.RecordTable.active=null;}};
window.RecordTable.active=handle;window.PageLifecycle?.onDispose(()=>handle.dispose());handle.ready=load(applied,{scroll:'restore',y:initialScroll}).finally(()=>{if(live())timer=setTimeout(check,10000);});return handle;
}
return {mount,active:null};
})();
+5 -6
View File
@@ -3,14 +3,13 @@ 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>';
filters=window.RecordState.read('records-pdf');let disposed=false;const live=()=>!disposed&&isActive(),get=id=>container.querySelector('#'+id),states={success:'已完成',running:'处理中',error:'失败',interrupted:'已中断'},files={available:'可下载',missing:'文件缺失',unavailable:'不可下载',pending:'等待导出'};
window.PageLifecycle?.onDispose(()=>{disposed=true;});
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><button class="btn" type="button" data-record-query>查询</button></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();
function draw(data){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));}
const table=window.RecordTable.mount({view:'records-pdf',container,isActive:live,api,onCommit:next=>{filters=next;},render:draw,readDraft:()=>({q:get('record-search').value.trim(),status:get('record-status').value}),writeDraft(next){get('record-search').value=next.q;get('record-status').value=next.status;}});await table.ready;
}
return {configure,records};
})();
+2 -2
View File
@@ -9,7 +9,7 @@ window.RecordUi=(()=>{
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>';
function pager(container,{page,pageSize,total,change,resize}){const count=container.querySelector('[data-record-count]'),previous=container.querySelector('[data-record-prev]'),next=container.querySelector('[data-record-next]'),pages=container.querySelector('[data-record-pages]'),size=container.querySelector('[data-record-size]'),last=Math.max(1,Math.ceil(total/pageSize));count.textContent=total?'第 '+((page-1)*pageSize+1)+'–'+Math.min(total,page*pageSize)+' 条,共 '+total+' 条 · 第 '+page+' / '+last+' 页':'共 0 条 · 第 1 / 1 页';for(const [button,boundary]of [[previous,page<=1],[next,page>=last]]){button.disabled=boundary;button.dataset.boundary=String(boundary);}previous.onclick=()=>change(page-1);next.onclick=()=>change(page+1);size.value=String(pageSize);size.onchange=()=>resize?.(Number(size.value));const shown=[...new Set([1,last,page-1,page,page+1].filter(n=>n>=1&&n<=last))].sort((a,b)=>a-b);pages.innerHTML=shown.map((n,i)=>(i&&n-shown[i-1]>1?'<span class="record-page-gap">…</span>':'')+'<button type="button" class="btn btn-sm '+(n===page?'btn-primary':'')+'" data-record-page="'+n+'" '+(n===page?'aria-current="page"':'')+' aria-label="第 '+n+' 页">'+n+'</button>').join('');pages.querySelectorAll('button').forEach(button=>button.onclick=()=>{if(Number(button.dataset.recordPage)!==page)change(Number(button.dataset.recordPage));});}
const footer='<div class="card-footer record-pagination"><span class="text-secondary small" data-record-count></span><label class="small d-flex gap-2 align-items-center">每页<select class="form-select form-select-sm" data-record-size aria-label="每页条数"><option value="25">25</option><option value="50">50</option><option value="100">100</option></select>条</label><nav class="d-flex gap-1 align-items-center" aria-label="记录分页"><button type="button" class="btn btn-sm" data-record-prev>上一页</button><span class="d-flex gap-1 align-items-center" data-record-pages></span><button type="button" class="btn btn-sm" data-record-next>下一页</button></nav></div>';
return {details,field,pager,footer};
})();
+20
View File
@@ -0,0 +1,20 @@
'use strict';
window.RecordState=(()=>{
const prefix='ona-record-navigation:',routes=['records','records-pdf'];let key=null,cache={},publish;
const route=hash=>String(hash||'').replace(/^#/,'').split('?')[0];
const isRecord=hash=>routes.includes(route(hash));
const defaults=view=>view==='records'?{scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1,pageSize:25}:{q:'',status:'',page:1,pageSize:25};
function normalize(view,input={}){const result=defaults(view);for(const field of Object.keys(result)){const value=input[field];if(value===undefined)continue;if(field==='page'){const n=Number(value);if(Number.isSafeInteger(n)&&n>0&&n<=1000000)result.page=n;}else if(field==='pageSize'){if([25,50,100].includes(Number(value)))result.pageSize=Number(value);}else if(field==='q'||field==='connectionId'){if(typeof value==='string')result[field]=value.slice(0,200);}else if(field==='from'||field==='to'){if(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)result[field]=value;}else if(({scope:['current','archived','all'],business:['orders','all'],kind:['all','todo','inform'],status:['','success','running','error','interrupted']})[field]?.includes(value))result[field]=value;}return result;}
function serialize(view,filters){const normal=normalize(view,filters),base=defaults(view),params=new URLSearchParams();for(const field of Object.keys(base))if(normal[field]!==base[field])params.set(field,normal[field]);return '#'+view+(params.size?'?'+params:'');}
function write(){if(!key)return;try{sessionStorage.setItem(key,JSON.stringify(cache));}catch{}}
function clear(){try{for(let i=sessionStorage.length-1;i>=0;i--){const name=sessionStorage.key(i);if(name?.startsWith(prefix))sessionStorage.removeItem(name);}}catch{}key=null;cache={};if(isRecord(location.hash))history.replaceState({appIndex:history.state?.appIndex},'','#'+route(location.hash));}
function configure(user,onPublish){const next=prefix+String(user.id||user.username);if(key&&key!==next)clear();key=next;publish=onPublish;cache={};try{const saved=JSON.parse(sessionStorage.getItem(key)||'{}');for(const view of routes)if(saved[view])cache[view]={filters:normalize(view,saved[view].filters),scroll:Number.isFinite(saved[view].scroll)?Math.max(0,saved[view].scroll):0};}catch{}}
function read(view,hash=location.hash){if(route(hash)===view)return normalize(view,Object.fromEntries(new URLSearchParams(hash.includes('?')?hash.slice(hash.indexOf('?')+1):'')));return normalize(view,cache[view]?.filters);}
function href(view){return routes.includes(view)?serialize(view,cache[view]?.filters):'#'+view;}
function links(){document.querySelectorAll('[data-record-route],[data-view="records"]').forEach(link=>{const view=link.dataset.recordRoute||'records';link.setAttribute('href',href(view));});}
function remember(view,filters,scroll=cache[view]?.scroll||0){cache[view]={filters:normalize(view,filters),scroll:Math.max(0,scroll)};write();links();}
function commit(view,filters,{push=false}={}){remember(view,filters);publish?.({hash:serialize(view,filters),push});}
function position(view){const saved=history.state?.recordScroll;return saved?.view===view&&Number.isFinite(saved.y)?saved.y:cache[view]?.scroll||0;}
function capture(view,filters){remember(view,filters,window.scrollY);if(route(location.hash)===view)history.replaceState({...history.state,recordScroll:{view,y:window.scrollY}},'',location.hash);}
return {route,isRecord,defaults,normalize,serialize,configure,clear,read,href,links,commit,capture,position};
})();