From f1613225321aaef272512d8c15eef760d6df0c7a Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Tue, 27 Oct 2026 14:27:10 +0800 Subject: [PATCH] feat: show application version and check Gitea releases --- README.md | 2 + docs/system-updates.md | 26 +++++++ package.json | 2 +- src/app/application.cjs | 4 +- src/app/bridge.cjs | 2 +- src/app/dashboard.cjs | 6 +- src/modules/system-update/checker.cjs | 81 ++++++++++++++++++++++ tests/system-update/checker.test.cjs | 67 ++++++++++++++++++ tests/system-update/system-update.test.cjs | 50 +++++++++++++ web/app.css | 2 + web/app.js | 38 +++++++++- 11 files changed, 273 insertions(+), 7 deletions(-) create mode 100644 docs/system-updates.md create mode 100644 src/modules/system-update/checker.cjs create mode 100644 tests/system-update/checker.test.cjs create mode 100644 tests/system-update/system-update.test.cjs diff --git a/README.md b/README.md index d891698..633e38e 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ ## 服务守护与系统健康 +左侧菜单底部显示当前版本,登录后自动检查一次更新,也可点击“检查更新”。有新版本时显示更新标记,并可查看发布日期、说明及远端发行页面。尚无 Release、已是最新版本和检查暂不可用会分别显示;检查失败不会阻塞业务。当前功能提供更新提示,由部署管理员根据发行说明安排更新。发行流程见[版本发布与更新检查](docs/system-updates.md)。 + 双击 **启动工具.cmd** 或运行 `npm start`,工作台由独立守护程序在后台运行;启动窗口关闭后服务继续运行,重复启动会复用现有实例。打开 **系统健康**(`/#health`)查看本次启动时间、连续运行时长、守护心跳、恢复次数、最近事件及 Windows 登录自启状态。 守护通过两个本机端口的私有心跳确认业务进程身份。启动宽限 120 秒,之后每 10 秒检查,连续 4 次失败才终止本工具启动的进程树并恢复。退出重试采用 2/5/10/30/60 秒退避,15 分钟内达到 8 次恢复尝试后冷却 5 分钟,避免反复启动。人工停止不会触发恢复,不会结束未知的占用端口进程。自动恢复仍遵守原有任务规则,邮件结果不明时保留待核实状态。 diff --git a/docs/system-updates.md b/docs/system-updates.md new file mode 100644 index 0000000..ba9110d --- /dev/null +++ b/docs/system-updates.md @@ -0,0 +1,26 @@ +# 版本发布与更新检查 + +当前版本来自 `package.json.version`,工作台侧栏与扩展健康接口使用同一个来源。 + +登录后自动检查一次,用户可在菜单底部手动检查。检查只读访问本仓库 Gitea 的 `GET /api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest`;浏览器通过已登录的同源 `GET /api/update` 读取结果,不直接访问远端,不传递工作台账号、Cookie 或业务数据。 + +| 结果 | 界面显示 | +| --- | --- | +| 远端没有发行版本(404) | 暂无可用发行版本 | +| 最新稳定版本高于当前版本 | 更新标记、发行日期、说明及发行页面入口 | +| 当前版本等于或高于远端版本 | 已是最新版本 | +| 网络、超时、响应格式错误 | 暂时无法检查更新;当前版本仍可见 | + +检查总超时为 5 秒,读取响应最多 256 KiB,不跟随重定向。版本按 SemVer 比较,支持 `v` 前缀与 build metadata,跳过草稿和预发行版。发行说明按纯文本显示,链接只允许本仓库的 HTTPS 发行页面。没有安装器、自动下载、源码覆盖或服务重启行为。 + +## 发布步骤 + +1. 在准备发行的提交中同步更新 `package.json` 与 `package-lock.json` 根包版本,例如 `0.2.0`。 +2. 执行 `npm ci`、`npm test` 与 `npm run test:full`,检查结果后合并对应变更。 +3. 给确切的发行提交创建一致的版本标签,例如 `v0.2.0`,推送标签。 +4. 在 Gitea 基于该标签发布正式 Release,填写变更说明、更新与备份要求;仅推送标签不会触发提示,草稿或预发行版也不会作为稳定更新。 +5. 部署管理员按说明备份本地状态、停服、更新发行源码和依赖、重新启动并核对版本及健康状态。 + +远端仓库目前公开可读。若以后改为私有仓库,应另行设计服务端只读认证;本功能不读取 Git 凭据,也不要求前端填写 token。私有仓库返回 404 时与“未发行”无法区分。 + +本次功能提交不创建首个 Release;首发版本应对应经过确认的发行提交。 diff --git a/package.json b/package.json index 20892e4..05d923e 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", "test": "npm run test:business", - "test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs", + "test:business": "node --test --test-concurrency=1 tests/app/business-home-ui.test.cjs tests/order-rules/home-summary.test.cjs tests/order-rules/carry-forward-core.test.cjs tests/order-rules/carry-forward-integration.test.cjs tests/order-rules/dispatch-unsent-proof.test.cjs tests/order-rules/dismiss-task.test.cjs tests/app/carry-dismiss-ui.test.cjs tests/workspace/business-issues.test.cjs tests/mail/unified-account.test.cjs tests/mail/unified-account-ui.test.cjs tests/assistant/assistant.test.cjs tests/assistant/assistant-http-ui.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/dsh-runtime-installer.test.cjs tests/assistant/repair-runner.test.cjs tests/app/automatic-pdf-ledger.test.cjs tests/app/job-records.test.cjs tests/order-rules/version-compatibility.test.cjs tests/bpm-display-policy.test.cjs tests/bpm-dynamicarea.test.cjs tests/bpm-readonly-form.test.cjs tests/bpm-form-contracts.test.cjs tests/bpm-obsolete-display-fields.test.cjs tests/order-rules/snapshot-read-context.test.cjs tests/order-rules/summary.test.cjs tests/order-rules/execution-single-flight.test.cjs tests/order-rules/execution-responsiveness.test.cjs tests/order-rules/readiness-pending-ui.test.cjs tests/dependency-compatibility.test.cjs tests/order-rules/slow-cutoff.test.cjs tests/order-rules/removed-discovery-barrier.test.cjs tests/mail/sample-send.test.cjs tests/mail/template-editing.test.cjs tests/mail/template-editor-ui.test.cjs tests/order-rules/scope-catalog.test.cjs tests/order-rules/field-mapping-ui.test.cjs tests/order-rules/scope-search-ui.test.cjs tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/collecting-batches.test.cjs tests/order-rules/collecting-batches-ui.test.cjs tests/order-rules/query.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs tests/system-update/checker.test.cjs tests/system-update/system-update.test.cjs", "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" }, "engines": { diff --git a/src/app/application.cjs b/src/app/application.cjs index d1ab998..ee94bdf 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -28,6 +28,8 @@ const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs') const { BpmOrderProvider } = require('../modules/bpm/order-provider.cjs'); const { OrderArchiveProvider } = require('../modules/storage/order-archive.cjs'); const { OrderExecutionCoordinator } = require('../modules/order-execution/coordinator.cjs'); +const { createUpdateChecker } = require('../modules/system-update/checker.cjs'); +const appVersion=require('../../package.json').version; async function closeServer(server){ if(!server)return; @@ -104,7 +106,7 @@ async function main(options = {}) { await bpmSessions.migrateAccounts(workspace.snapshot().connections); workspace.markSessionChecksPending(); server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot}); - dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); + dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true,updateChecker:createUpdateChecker({currentVersion:appVersion})}); await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();bpmMonitor.start(); health.start(); orderExecution.start(); diff --git a/src/app/bridge.cjs b/src/app/bridge.cjs index 9dc797c..5797aef 100644 --- a/src/app/bridge.cjs +++ b/src/app/bridge.cjs @@ -27,7 +27,7 @@ function createServer(options) { const supplied = Buffer.from(String(request.headers['x-order-token'] || '')); const expected = Buffer.from(options.token); if (supplied.length !== expected.length || !crypto.timingSafeEqual(supplied, expected)) return reply(401, {error:'配对失效,请重新加载扩展。'}); - if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:'0.1.0',busy}); + if (request.method === 'GET' && request.url === '/health') return reply(200, {ok:true,version:require('../../package.json').version,busy}); const jobRoute = /^\/jobs\/([a-f0-9]{32})$/.exec(request.url); if (request.method === 'GET' && jobRoute) return jobs.has(jobRoute[1]) ? reply(200,jobs.get(jobRoute[1])) : reply(404,{error:'任务已过期,请检查输出目录后重试。'}); if (request.method !== 'POST' || request.url !== '/export') return reply(404, {error:'未知操作。'}); diff --git a/src/app/dashboard.cjs b/src/app/dashboard.cjs index bdfffeb..1fb4694 100644 --- a/src/app/dashboard.cjs +++ b/src/app/dashboard.cjs @@ -16,7 +16,7 @@ const {createAuth}=require('../modules/dashboard/auth.cjs'); const {prepareRequest,readBody}=require('./request.cjs'); const {BpmConnectionLifecycle}=require('../modules/bpm/connection-lifecycle.cjs'); -function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false}) { +function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy=false,updateChecker}) { const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null; const auth=createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}); let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;} @@ -36,6 +36,10 @@ function createDashboard({store,outputDir,workspace,bpmSessions,bpmMonitor,mail, const authResult=await auth.authenticate({request,response,route,body,reply,fail,encryptedTransport}); if(authResult.handled)return; const {user,token}=authResult; + if(route==='/api/update' && request.method==='GET') { + const result=await (updateChecker|| (async()=>({status:'unavailable',currentVersion:require('../../package.json').version,latest:null})))(); + return reply(200,result); + } if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));} if(await require('../modules/dashboard/maintenance.cjs').maintenanceApi({store,outputDir,user,route,method:request.method,reply,response}))return; if(route==='/api/order-rules'&&request.method==='GET'&&url.searchParams.get('view')==='summary')workspace?.syncBusinessIssues?.(orderRules?.all('business-issues')||[],store.users()); diff --git a/src/modules/system-update/checker.cjs b/src/modules/system-update/checker.cjs new file mode 100644 index 0000000..43be271 --- /dev/null +++ b/src/modules/system-update/checker.cjs @@ -0,0 +1,81 @@ +'use strict'; + +const REPOSITORY_URL='https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation'; +const RELEASES_API_URL='https://git.simgreek.com/api/v1/repos/Skyworth_Digital_Hardware/order-notification-automation/releases/latest'; +const VERSION_PATTERN=/^[vV]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/; +const MAX_RESPONSE_BYTES=256*1024; + +function versionParts(value){ + const match=typeof value==='string'&&value.length<=200&&VERSION_PATTERN.exec(value.trim()); + if(!match)return null; + const pre=match[4]?match[4].split('.'):[]; + if(pre.some(part=>/^0\d+$/.test(part)))return null; + return {major:BigInt(match[1]),minor:BigInt(match[2]),patch:BigInt(match[3]),pre}; +} +function compareIdentifiers(a,b){ + const an=/^\d+$/.test(a),bn=/^\d+$/.test(b); + if(an&&bn)return BigInt(a)>BigInt(b)?1:BigInt(a)b?1:ab[key]?1:-1; + if(!a.pre.length&&!b.pre.length)return 0; + if(!a.pre.length)return 1; + if(!b.pre.length)return -1; + for(let i=0;i=a.pre.length)return -1; + if(i>=b.pre.length)return 1; + const result=compareIdentifiers(a.pre[i],b.pre[i]); + if(result)return result>0?1:-1; + } + return 0; +} +function safeReleaseUrl(value,repositoryUrl=REPOSITORY_URL){ + try{ + const url=new URL(value),base=new URL(repositoryUrl); + if(url.username||url.password||url.origin!==base.origin||!url.pathname.startsWith(base.pathname+'/releases/'))return ''; + return url.href; + }catch{return '';} +} +function parseRelease(release,currentVersion,{repositoryUrl=REPOSITORY_URL}={}){ + const base={currentVersion,latest:null}; + if(!release||typeof release!=='object'||Array.isArray(release)||typeof release.tag_name!=='string')return {...base,status:'unavailable'}; + const version=release.tag_name.trim().replace(/^v/i,''),parts=versionParts(version); + if(!parts)return {...base,status:'unavailable'}; + if(release.draft===true||release.prerelease===true||parts.pre.length)return {...base,status:'none'}; + if(compareVersions(version,currentVersion)<=0)return {...base,status:'current'}; + const publishedAt=release.published_at?new Date(release.published_at):null; + return {status:'update-available',currentVersion,latest:{version,name:String(release.name||release.tag_name||version).slice(0,200),notes:String(release.body||'').slice(0,20000),url:safeReleaseUrl(release.html_url,repositoryUrl),publishedAt:publishedAt&&!Number.isNaN(publishedAt.getTime())?publishedAt.toISOString():null}}; +} +async function readRelease(response){ + const reader=response.body?.getReader(); + if(!reader)throw Error('发行版本响应为空。'); + const chunks=[];let bytes=0; + try{ + while(true){ + const {value,done}=await reader.read();if(done)break; + bytes+=value.byteLength;if(bytes>MAX_RESPONSE_BYTES)throw Error('发行版本响应过大。'); + chunks.push(Buffer.from(value)); + } + return JSON.parse(Buffer.concat(chunks,bytes).toString('utf8')); + }catch(error){await reader.cancel().catch(()=>{});throw error;} + finally{reader.releaseLock();} +} +function createUpdateChecker({currentVersion,fetchImpl=globalThis.fetch,apiUrl=RELEASES_API_URL,repositoryUrl=REPOSITORY_URL,timeoutMs=5000}={}){ + if(!versionParts(currentVersion))throw new Error('当前版本必须是 x.y.z 格式。'); + return async function checkForUpdate(){ + const base={currentVersion,latest:null}; + if(typeof fetchImpl!=='function')return {...base,status:'unavailable'}; + const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),timeoutMs); + try{ + const response=await fetchImpl(apiUrl,{headers:{Accept:'application/json'},redirect:'error',credentials:'omit',signal:controller.signal}); + if(!response.ok){await response.body?.cancel();return {...base,status:response.status===404?'none':'unavailable'};} + return parseRelease(await readRelease(response),currentVersion,{repositoryUrl}); + }catch{return {...base,status:'unavailable'};} + finally{clearTimeout(timer);} + }; +} +module.exports={REPOSITORY_URL,RELEASES_API_URL,compareVersions,parseRelease,createUpdateChecker}; diff --git a/tests/system-update/checker.test.cjs b/tests/system-update/checker.test.cjs new file mode 100644 index 0000000..47f42fd --- /dev/null +++ b/tests/system-update/checker.test.cjs @@ -0,0 +1,67 @@ +'use strict'; +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const {compareVersions,parseRelease,createUpdateChecker}=require('../../src/modules/system-update/checker.cjs'); + +test('compares semantic versions with an optional v prefix and prerelease ordering',()=>{ + assert.equal(compareVersions('v0.2.0','0.1.9'),1); + assert.equal(compareVersions('0.1.0','v0.1.0'),0); + assert.equal(compareVersions('0.1.0-beta.1','0.1.0'),-1); +}); + +test('parses a Gitea release into a safe update descriptor',()=>{ + assert.deepEqual(parseRelease({tag_name:'v0.2.0',name:'第二版',body:'修复问题',html_url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',published_at:'2026-10-27T00:00:00Z'},'0.1.0'),{ + status:'update-available',currentVersion:'0.1.0',latest:{version:'0.2.0',name:'第二版',notes:'修复问题',url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',publishedAt:'2026-10-27T00:00:00.000Z'} + }); +}); + +test('returns no-release and unavailable states without throwing',async()=>{ + const none=await createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>new Response('',{status:404})})(); + assert.deepEqual(none,{status:'none',currentVersion:'0.1.0',latest:null}); + const unavailable=await createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>{throw new Error('offline');}})(); + assert.deepEqual(unavailable,{status:'unavailable',currentVersion:'0.1.0',latest:null}); +}); + +test('reports only a newer valid release',async()=>{ + const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async()=>new Response(JSON.stringify({tag_name:'v0.2.0',name:'Release',body:'Notes',html_url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',published_at:null}),{status:200,headers:{'content-type':'application/json'}})}); + const result=await checker(); + assert.equal(result.status,'update-available'); + assert.equal(result.latest.version,'0.2.0'); +}); + +test('marks an equal release as current',()=>{ + assert.deepEqual(parseRelease({tag_name:'v0.1.0',name:'首版'},'0.1.0'),{status:'current',currentVersion:'0.1.0',latest:null}); +}); + +test('supports build metadata and follows ASCII semver prerelease ordering',()=>{ + assert.equal(compareVersions('v1.2.3+build.7','1.2.3'),0); + assert.equal(compareVersions('1.0.0-Z','1.0.0-a'),-1); + assert.equal(compareVersions('1.0.0-99999999999999999999','1.0.0-99999999999999999998'),1); + assert.throws(()=>compareVersions('1.0.0-01','1.0.0')); +}); + +test('malformed and unstable release responses never claim a valid stable update',()=>{ + for(const data of [null,{},[],{tag_name:'banana'}])assert.equal(parseRelease(data,'0.1.0').status,'unavailable'); + for(const data of [{tag_name:'v0.2.0',draft:true},{tag_name:'v0.2.0',prerelease:true},{tag_name:'v0.2.0-beta.1'}])assert.equal(parseRelease(data,'0.1.0').status,'none'); +}); + +test('release links never include credentials or leave the selected repository',()=>{ + for(const url of ['https://user:password@git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0','javascript:alert(1)','https://example.org/releases/tag/v0.2.0','https://git.simgreek.com/other/repo/releases/tag/v0.2.0']){ + assert.equal(parseRelease({tag_name:'v0.2.0',html_url:url},'0.1.0').latest.url,''); + } +}); + +test('checker bounds a streamed response before reading all chunks and disables redirects',async()=>{ + let cancelled=false; + const checker=createUpdateChecker({currentVersion:'0.1.0',fetchImpl:async(url,options)=>{ + if(options.redirect!=='error')throw Error('redirects are allowed'); + return new Response(new ReadableStream({pull(controller){controller.enqueue(new Uint8Array(200000));},cancel(){cancelled=true;}}),{status:200}); + }}); + assert.equal((await checker()).status,'unavailable'); + assert.equal(cancelled,true); +}); + +test('network timeout returns unavailable and preserves the current version',async()=>{ + const checker=createUpdateChecker({currentVersion:'0.1.0',timeoutMs:25,fetchImpl:async(url,{signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}))}); + assert.deepEqual(await checker(),{status:'unavailable',currentVersion:'0.1.0',latest:null}); +}); diff --git a/tests/system-update/system-update.test.cjs b/tests/system-update/system-update.test.cjs new file mode 100644 index 0000000..6151d7d --- /dev/null +++ b/tests/system-update/system-update.test.cjs @@ -0,0 +1,50 @@ +'use strict'; +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const os=require('node:os'); +const path=require('node:path'); +const {Store}=require('../../src/modules/dashboard/store.cjs'); +const {createDashboard}=require('../../src/app/dashboard.cjs'); +const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); + +function fixture(updateChecker){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'system-update-')); + const store=new Store(dir);store.bootstrap('admin','Update-test-123'); + const server=createDashboard({store,outputDir:dir,updateChecker}); + return {dir,store,server}; +} + +test('authenticated update endpoint returns the checker result',async t=>{ + const fixtureData=fixture(async()=>({status:'none',currentVersion:'0.1.0',latest:null})); + const {server,dir}=fixtureData;await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});}); + const base='http://127.0.0.1:'+server.address().port; + const call=(route,body,cookie)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body?{'Content-Type':'application/json','Origin':base}:{}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}); + const login=await call('/api/login',{username:'admin',password:'Update-test-123'});const cookie=login.headers.get('set-cookie').split(';')[0]; + const response=await call('/api/update',undefined,cookie);assert.equal(response.status,200);assert.deepEqual(await response.json(),{status:'none',currentVersion:'0.1.0',latest:null}); +}); + +test('sidebar displays the current version and a newer release after checking',async t=>{ + let state={status:'none',currentVersion:'0.1.0',latest:null}; + const fixtureData=fixture(async()=>state); + const {server,dir}=fixtureData;await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + t.after(async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});}); + const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close()); + const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(10000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#overview'); + await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Update-test-123');await page.getByRole('button',{name:'登录',exact:true}).click(); + await page.locator('#app-version').waitFor();assert.match(await page.locator('#app-version').textContent(),/v0\.1\.0/);assert.equal(await page.locator('#update-status').count(),1); + await page.locator('#update-status').getByText('暂无可用发行版本',{exact:true}).waitFor(); + state={status:'update-available',currentVersion:'0.1.0',latest:{version:'0.2.0',name:'第二版',notes:'修复问题\n',url:'https://git.simgreek.com/Skyworth_Digital_Hardware/order-notification-automation/releases/tag/v0.2.0',publishedAt:'2026-10-27T00:00:00Z'}}; + await page.getByRole('button',{name:'检查更新',exact:true}).click(); + const dialog=page.getByRole('dialog',{name:'系统更新',exact:true});await dialog.waitFor(); + await dialog.getByText('发现新版本 v0.2.0',{exact:true}).waitFor(); + assert.equal(await dialog.locator('img').count(),0);assert.match(await dialog.locator('pre').textContent(),/document.documentElement.scrollWidth<=innerWidth),true); + assert.deepEqual(errors,[]); +}); diff --git a/web/app.css b/web/app.css index 364c3e9..04963d1 100644 --- a/web/app.css +++ b/web/app.css @@ -60,3 +60,5 @@ .rule-scope-row .ts-wrapper{--bs-body-bg:var(--tblr-bg-surface,#fff);--bs-body-color:var(--tblr-body-color,#182433);--bs-border-radius:var(--tblr-border-radius,6px)} .bpm-account-status{display:inline-flex;align-items:center;gap:7px;font-size:.8rem;font-weight:600;white-space:nowrap}.bpm-status-light{width:9px;height:9px;border-radius:50%;background:currentColor;flex-shrink:0}.bpm-status-green{color:#23834b}.bpm-status-yellow{color:#996600}.bpm-status-red{color:#c53030}.bpm-status-details>summary{cursor:pointer;font-size:.8rem;color:#657b81}.bpm-status-details>div{display:flex;gap:.75rem;flex-wrap:wrap;align-items:center;margin-top:.65rem} .bpm-sync-summary{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap} +.sidebar-system-update{line-height:1.6}.sidebar-version{margin-top:9px;color:#52655d;font-variant-numeric:tabular-nums}.sidebar-update-button{margin-top:8px;padding:.25rem .55rem;font-size:.68rem}.sidebar-update-status{margin-top:6px;font-size:.68rem;color:#87958e;overflow-wrap:anywhere}.sidebar-update-status.is-update{color:#a35d1b;font-weight:600}.sidebar-update-status a{color:inherit;text-decoration:underline;font-weight:500}@media(max-width:991px){.sidebar-system-update{margin-top:1rem;padding:1rem!important}.sidebar-update-status{max-width:320px}} +.sidebar-release-details{border:0;background:none;padding:4px 0;color:inherit;text-decoration:underline;font-size:inherit;display:block}.system-update-dialog{width:min(580px,calc(100vw - 32px));max-height:85vh;overflow:auto;border:1px solid var(--tblr-border-color);border-radius:12px;padding:24px;color:var(--tblr-body-color);background:#fff}.system-update-dialog::backdrop{background:#18243366}.system-update-notes{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:.85rem;max-height:40vh;overflow:auto;background:#f5f7f8;padding:12px;border-radius:8px} diff --git a/web/app.js b/web/app.js index 35980b2..01635f9 100644 --- a/web/app.js +++ b/web/app.js @@ -4,7 +4,8 @@ const esc=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'< const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(date.getTime())?new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',dateStyle:'short',timeStyle:'medium',hour12:false}).format(date):'—';}; const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'}; const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']}; -let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0; +let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0,historyIndex=0,historyTransition=null,automationRevision=0,overviewRevision=0,updateRevision=0; +let updateState={status:'unavailable',currentVersion:'—',latest:null}; const views={tools:['工具','手工导出、文件查看与助手'],'records-pdf':['订单与导出记录','查询PDF导出结果、文件可用性与存储归档记录'],'order-notifications':['通知总览','查看当前发送时段、待发订单及接入阻塞'],'notification-execution':['订单执行','扫描真实待办,查看归档进度与受控恢复'],'notification-orders':['订单中心','查看订单分类、归档证据及所属邮件批次'],'notification-batches':['邮件批次','按发送时段检查分类汇总和冻结内容'],'notification-history':['发送记录','核对发送结果、冻结内容和人工恢复记录'],'notification-settings':['发送设置','维护发件邮箱、邮件限制与自动通知开关'],'rule-fields':['字段映射','采集BPM流程和节点,供分类规则选择匹配项'],'assistant-settings':['助手设置','配置 DSH 运行包、模型与受控操作权限'],'business-settings':['业务设置','维护Excel分类规则、收件人和BPM流程节点目录'],'system-settings':['系统设置','集中管理服务连接、运行维护和团队权限'],account:['个人账号','维护自己的登录密码与访问安全'],'order-rules':['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['DSH 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['兼容业务通知','原来源映射、产业接口人与通知队列'],overview:['业务首页','订单处理、邮件窗口、业务阻塞与待核验'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['分类通知规则','按 Excel 类别维护匹配、归档、收件人与通知正文'],schedule:['发送计划','设置每日两个发送时间及周末安排'],templates:['邮件模板','管理模板及 Excel 类别关联;收件名单在分类规则维护'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; const pendingWrites=new Map(); async function api(route,body,{signal,ownerCheck,managedOutcome=false}={}) { @@ -32,9 +33,40 @@ function notify(message,type='success') { } function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `${label}`;} function navItem(id,symbol){return ``;} +function renderUpdateStatus(data){ + updateState=data||updateState; + const version=document.querySelector('#app-version');if(version)version.textContent='版本 v'+(updateState.currentVersion||'—'); + const status=document.querySelector('#update-status');if(!status)return; + status.className='sidebar-update-status';status.removeAttribute('title'); + if(updateState.status==='update-available'&&updateState.latest){ + status.classList.add('is-update');status.innerHTML=`发现新版本 v${esc(updateState.latest.version)}`; + status.querySelector('button').onclick=()=>showUpdateDetails(); + }else if(updateState.status==='current'){status.textContent='已是最新版本';} + else if(updateState.status==='none'){status.textContent='暂无可用发行版本';} + else if(updateState.status==='unavailable'){status.textContent='暂时无法检查更新';} + else status.textContent='更新状态未知'; +} +function showUpdateDetails(loading=false){ + let dialog=document.querySelector('#system-update-dialog'); + if(!dialog){dialog=document.createElement('dialog');dialog.id='system-update-dialog';dialog.className='system-update-dialog';dialog.setAttribute('aria-labelledby','system-update-title');root.append(dialog);} + const release=updateState.latest; + const message=loading?'正在检查更新…':updateState.status==='update-available'&&release?'发现新版本 v'+release.version:({none:'暂无可用发行版本',current:'已是最新版本',unavailable:'暂时无法检查更新'}[updateState.status]||'更新状态未知'); + dialog.innerHTML=`

系统更新

当前版本 v${esc(updateState.currentVersion)}

${esc(message)}

${!loading&&release?`

${esc(release.name)}

${release.publishedAt?`

发布时间(北京时间):${esc(formatDate(release.publishedAt))}

`:''}
${esc(release.notes||'此版本未填写更新说明。')}
${release.url?`前往发行页面`:''}

由部署管理员根据发行说明安排更新。

`:''}
`; + if(!dialog.open)dialog.showModal(); +} +async function checkSystemUpdate(isActive=()=>!!currentUser,{manual=false}={}){ + const user=currentUser,request=++updateRevision,button=document.querySelector('#check-updates'),ownsResponse=()=>currentUser===user&&!!user&&button?.isConnected&&isActive();if(button)button.disabled=true; + const status=document.querySelector('#update-status');if(status&&manual)status.textContent='正在检查更新…'; + if(manual)showUpdateDetails(true); + try{const result=await api('/update',undefined,{ownerCheck:ownsResponse});if(!ownsResponse()||request!==updateRevision)return;renderUpdateStatus(result);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();} + catch(error){if(ownsResponse()&&request===updateRevision){updateState={...updateState,status:'unavailable',latest:null};renderUpdateStatus(updateState);if(manual&&document.querySelector('#system-update-dialog')?.open)showUpdateDetails();}} + finally{if(button&&request===updateRevision)button.disabled=false;} +} function shell() { - root.innerHTML=`
`; + root.innerHTML=`
`; + renderUpdateStatus(updateState); 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('#check-updates').onclick=()=>checkSystemUpdate(()=>!!currentUser,{manual:true}); document.querySelector('#refresh').onclick=()=>window.PageLifecycle.guard(()=>{const generation=viewGeneration;void updateAutomationStatus(()=>generation===viewGeneration&&!!currentUser);return 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');}); } @@ -124,7 +156,7 @@ async function authScreen() { } async function passwordChanged(actorId){if(currentUser&¤tUser.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.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,user:currentUser});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);}},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,user:currentUser});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();void checkSystemUpdate(()=>!!currentUser);clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser&&!document.hidden){const statusGeneration=viewGeneration,statusUser=currentUser;void updateAutomationStatus(()=>statusGeneration===viewGeneration&&statusUser===currentUser);}},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});});