diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 9e0a744..12bdd2f 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -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连接归属。 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index c5424fb..4b5aca9 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -14,6 +14,8 @@ 表单离开保护提供保存并继续/放弃/留下;密码、新建账号等敏感或不可自动提交表单只允许放弃或留下。刷新受浏览器原生 beforeunload 保护,不可能自定义其三个按钮。提交禁重、错误保留输入;持久保存与刷新失败分别提示;旧页/旧登录响应不得覆盖当前页面。 +全局同步设置在BPM连接页独立维护,管理员保存、其他角色只读,沿用既有全局开关与完整对账间隔。两页记录通过显式查询应用筛选,hash和按账号的sessionStorage保留已应用条件/页码/条数/位置,退出及认证失效清理;不缓存业务记录或凭据。分页成功才提交数据和地址,失败可重试;后台更新仅提示,不重画阅读中的列表或详情。详见[导航与同步设置验收](records-navigation-verification-2026-10-20.md)。 + ## 唯一业务分类与窗口 Excel 的15类规则是唯一业务分类。流程名称、版本、配置节点必须精确对应;知会/待阅状态不能代替通知书节点。通知与更改分开,收件人和附件要求取对应分类规则。每个有效时段同类别汇总一封;空类不发,受阻类别不漏单发送。 diff --git a/docs/records-navigation-verification-2026-10-20.md b/docs/records-navigation-verification-2026-10-20.md new file mode 100644 index 0000000..c96fc4c --- /dev/null +++ b/docs/records-navigation-verification-2026-10-20.md @@ -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`。 + +完整测试已通过,接下来恢复原实例,核对原身份、密钥、规则、采样、草稿、订单、批次、设置、双端口和页面。同步配置沿用既有值,不通过实际设置改写制造验收数据。 diff --git a/docs/superpowers/plans/2026-10-20-records-navigation.md b/docs/superpowers/plans/2026-10-20-records-navigation.md new file mode 100644 index 0000000..586db59 --- /dev/null +++ b/docs/superpowers/plans/2026-10-20-records-navigation.md @@ -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、不操作服务机、不推送合并。 diff --git a/docs/superpowers/specs/2026-10-20-records-ledger-design.md b/docs/superpowers/specs/2026-10-20-records-ledger-design.md index 7b16d39..24f2a77 100644 --- a/docs/superpowers/specs/2026-10-20-records-ledger-design.md +++ b/docs/superpowers/specs/2026-10-20-records-ledger-design.md @@ -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连接后记录自动转历史、默认只看订单相关流程。此确认授权本轮实施及原本机测试服务更新,不另行请求同项批准。 ## 页面 diff --git a/docs/web-action-inventory.md b/docs/web-action-inventory.md index d1407e3..3b8e776 100644 --- a/docs/web-action-inventory.md +++ b/docs/web-action-inventory.md @@ -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-* | 已验证可用 | diff --git a/src/app/assets.cjs b/src/app/assets.cjs index d1537ea..83b4793 100644 --- a/src/app/assets.cjs +++ b/src/app/assets.cjs @@ -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'}, diff --git a/src/modules/bpm/scan-store.cjs b/src/modules/bpm/scan-store.cjs index af76d1c..a545a32 100644 --- a/src/modules/bpm/scan-store.cjs +++ b/src/modules/bpm/scan-store.cjs @@ -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}; } diff --git a/src/modules/dashboard/job-records.cjs b/src/modules/dashboard/job-records.cjs index cfe68bb..2590bf4 100644 --- a/src/modules/dashboard/job-records.cjs +++ b/src/modules/dashboard/job-records.cjs @@ -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}; diff --git a/tests/app/job-records.test.cjs b/tests/app/job-records.test.cjs index 57f8914..2ee84de 100644 --- a/tests/app/job-records.test.cjs +++ b/tests/app/job-records.test.cjs @@ -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);}); diff --git a/tests/app/records-navigation.test.cjs b/tests/app/records-navigation.test.cjs new file mode 100644 index 0000000..5068df9 --- /dev/null +++ b/tests/app/records-navigation.test.cjs @@ -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;}); diff --git a/tests/bpm/bpm-scan-http-ui.test.cjs b/tests/bpm/bpm-scan-http-ui.test.cjs index 529f1fa..5e08d1c 100644 --- a/tests/bpm/bpm-scan-http-ui.test.cjs +++ b/tests/bpm/bpm-scan-http-ui.test.cjs @@ -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); diff --git a/tests/bpm/bpm-ui.test.cjs b/tests/bpm/bpm-ui.test.cjs index 4025ef3..5c0d898 100644 --- a/tests/bpm/bpm-ui.test.cjs +++ b/tests/bpm/bpm-ui.test.cjs @@ -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; diff --git a/tests/bpm/records-ledger.test.cjs b/tests/bpm/records-ledger.test.cjs index 56feeaa..c5f7936 100644 --- a/tests/bpm/records-ledger.test.cjs +++ b/tests/bpm/records-ledger.test.cjs @@ -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,[]);}); diff --git a/tests/fixtures/records-app.cjs b/tests/fixtures/records-app.cjs new file mode 100644 index 0000000..40b8e4b --- /dev/null +++ b/tests/fixtures/records-app.cjs @@ -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}; diff --git a/web/app.css b/web/app.css index 34c8b57..a8bc246 100644 --- a/web/app.css +++ b/web/app.css @@ -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}} diff --git a/web/app.js b/web/app.js index c061e26..7edf6a0 100644 --- a/web/app.js +++ b/web/app.js @@ -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&¤tUser===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&¤tUser&&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&¤tUser&&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 `${label}`;} -function navItem(id,symbol){return `
${text}