diff --git a/mobile-app/.env.example b/mobile-app/.env.example
index 975d4a7..25a5316 100644
--- a/mobile-app/.env.example
+++ b/mobile-app/.env.example
@@ -1,8 +1,9 @@
# Build-time settings; never put credentials in APP_* or EXPO_PUBLIC_*.
APP_ENV=dev
-# For a phone, replace this with the development PC's LAN IP (not the phone's localhost).
-APP_API_URL=http://127.0.0.1:8080
-APP_UPDATE_ORIGIN=http://127.0.0.1:8090
+# Defaults are in config/development.json. These optional overrides must match
+# the installed APK when exporting updates. Never point a phone at loopback.
+APP_API_URL=http://192.168.0.222:8080
+APP_UPDATE_ORIGIN=http://192.168.0.222:8090
EXPO_NO_TELEMETRY=1
# OTA server: defaults to loopback behind an internal reverse proxy.
OTA_HOST=127.0.0.1
diff --git a/mobile-app/app.config.js b/mobile-app/app.config.js
index d0ec83d..836b98e 100644
--- a/mobile-app/app.config.js
+++ b/mobile-app/app.config.js
@@ -6,7 +6,7 @@ module.exports = () => {
name: env.variant === 'prod' ? 'CMVR 物资管理' : 'CMVR 物资管理·开发',
slug: 'cmvr-wms', version: '1.0.0', orientation: 'portrait', userInterfaceStyle: 'automatic',
platforms: ['android', 'web'],
- android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: 1,
+ android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 2 : 1,
permissions: [], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
plugins: ['expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }],
...(env.variant === 'prod' ? ['./plugins/with-release-signing.cjs'] : [])],
diff --git a/mobile-app/config/development.json b/mobile-app/config/development.json
new file mode 100644
index 0000000..7b1a106
--- /dev/null
+++ b/mobile-app/config/development.json
@@ -0,0 +1,4 @@
+{
+ "apiUrl": "http://192.168.0.222:8080",
+ "updateOrigin": "http://192.168.0.222:8090"
+}
diff --git a/mobile-app/config/environment.cjs b/mobile-app/config/environment.cjs
index e7664f3..e40e471 100644
--- a/mobile-app/config/environment.cjs
+++ b/mobile-app/config/environment.cjs
@@ -1,5 +1,6 @@
const fs = require('node:fs');
const path = require('node:path');
+const development = require('./development.json');
function internal(value, dev) {
const url = new URL(value);
const p = url.hostname.split('.').map(Number);
@@ -13,8 +14,10 @@ function environment(env = process.env) {
const variant = env.APP_ENV || 'dev';
if (!['dev', 'prod'].includes(variant)) throw Error('APP_ENV 只能是 dev 或 prod');
const dev = variant === 'dev';
- const apiUrl = internal(env.APP_API_URL || (dev ? 'http://127.0.0.1:8080' : ''), dev);
- const updateOrigin = internal(env.APP_UPDATE_ORIGIN || (dev ? 'http://127.0.0.1:8090' : ''), dev);
+ const apiUrl = internal(env.APP_API_URL || (dev ? development.apiUrl : ''), dev);
+ // Installed development apps reach the development PC, not the phone or production server.
+ // API selection remains independent and editable from the development app.
+ const updateOrigin = internal(env.APP_UPDATE_ORIGIN || (dev ? development.updateOrigin : ''), dev);
if (new URL(updateOrigin).pathname !== '/') throw Error('APP_UPDATE_ORIGIN 只能包含协议、内网地址和端口。');
const certificate = path.resolve(__dirname, '../certs', `${variant}.pem`);
if (!dev && !fs.existsSync(certificate)) throw Error('正式构建必须先配置 certs/prod.pem 更新签名证书。');
diff --git a/mobile-app/deploy/DEVELOPMENT.html b/mobile-app/deploy/DEVELOPMENT.html
new file mode 100644
index 0000000..6135176
--- /dev/null
+++ b/mobile-app/deploy/DEVELOPMENT.html
@@ -0,0 +1,20 @@
+
+
开发 App 与内网热更新
+开发 App 与内网热更新 2026-10-20。开发业务和更新均放开发电脑,不登录或修改正式环境 192.168.28.10。
+地址统一保存在 mobile-app/config/development.json:业务 http://192.168.0.222:8080,更新 http://192.168.0.222:8090/updates/dev。开发 App 的业务地址仍可在登录页、设置中修改;更新地址独立固定,不跟随业务地址跳转。
+首次安装与后续更新 旧开发包内置更新地址为手机自己的 127.0.0.1,需覆盖安装本次新包一次,保留同一包名和 Android 开发签名。之后页面和业务 JS 修复使用签名热更新;不需要 Expo Go 或重新安装。新增原生模块、修改 SDK、证书、原生网络设置等改变兼容指纹时仍需新包。
+手机须能访问开发电脑,电脑及开发更新服务须保持运行。App 启动后后台检查并下载;在“我的→设置”看到更新已备妥后,完全退出并重新打开生效,不强制中断编辑。断网继续使用内置或已下载版本。
+开发电脑启动服务 powershell -File mobile-app/scripts/Start-DevelopmentUpdates.ps1
+服务只绑定配置中的本机内网 IP,允许 dev 通道,不服务 prod 通道。更新与安装包公开资源在 .codex-tmp/app-dev-ota,签名私钥不放在服务目录,不通过 HTTP 提供。当前进程信息、日志保存在该目录;重启电脑后重新运行启动脚本。不会停止其他未知进程。
+下次发布页面更新 cd mobile-app
+# 保持与安装包相同的开发配置,不设置为 prod。
+$env:APP_ENV='dev'
+npm run typecheck
+npm test
+npm run ota:export
+powershell -File scripts/Stage-DevelopmentUpdate.ps1
+node scripts/verify-development-ota.mjs
+暂存脚本会核对导出与最近 APK 的原生指纹,使用 dev 私钥签名,并把新版本及不可变资源写到开发服务目录;服务不必重启。发布前必须先通过测试。若要完整打包,使用 scripts/Build-Development.ps1;所有 APK 构建都会拒绝 loopback 更新地址或未签名配置。
+正式环境、正式签名、正式更新通道均保持不变。开发电脑 IP 最好固定或做 DHCP 地址保留;如果 IP 改变,现有包的固定更新地址也会失效。不要关闭防火墙来排障,只按组织网络策略允许手机访问开发服务。
+本机开发更新签名私钥长期保存在被 Git 忽略且限制访问的 mobile-app/keys/development/ota-private-key.pem,服务只挂公开资源,不提供私钥。保留并备份同一私钥和 certs/dev.pem;不要重新生成来替换,否则已安装客户端不会接受新签名。旧临时副本仅作保留备份,后续发布不依赖临时目录中的密钥。
+服务端签名、资源哈希和协议验证不等于真机已完成下载与重启生效验收,须在手机上另行核对。
diff --git a/mobile-app/scripts/Build-Android.ps1 b/mobile-app/scripts/Build-Android.ps1
index 416e1b1..f1dcd2e 100644
--- a/mobile-app/scripts/Build-Android.ps1
+++ b/mobile-app/scripts/Build-Android.ps1
@@ -21,6 +21,9 @@ New-Item -ItemType Directory -Path $taskTmp -Force | Out-Null
$env:JAVA_TOOL_OPTIONS = "$env:JAVA_TOOL_OPTIONS -Dfile.encoding=UTF-8 -Djava.io.tmpdir=$taskTmp -Djdk.net.unixdomain.tmpdir=$taskTmp"
Push-Location $taskApp
try {
+ # Run for every installable APK, not only the development convenience wrapper.
+ & node.exe (Join-Path $PSScriptRoot 'check-installable-config.cjs')
+ if ($LASTEXITCODE) { throw 'Installable App update configuration is invalid' }
& npm.cmd run typecheck
if ($LASTEXITCODE) { throw 'Type checking failed' }
& npm.cmd test
diff --git a/mobile-app/scripts/Build-Development.ps1 b/mobile-app/scripts/Build-Development.ps1
new file mode 100644
index 0000000..37516da
--- /dev/null
+++ b/mobile-app/scripts/Build-Development.ps1
@@ -0,0 +1,10 @@
+param([string]$ApiUrl = '', [string]$UpdateOrigin = '')
+$ErrorActionPreference = 'Stop'
+$taskApp = Split-Path $PSScriptRoot -Parent
+$taskRepo = Split-Path $taskApp -Parent
+$taskDevelopment = Get-Content -LiteralPath (Join-Path $taskApp 'config/development.json') -Raw | ConvertFrom-Json
+if (!$ApiUrl) { $ApiUrl = $taskDevelopment.apiUrl }
+if (!$UpdateOrigin) { $UpdateOrigin = $taskDevelopment.updateOrigin }
+$env:APP_API_URL = $ApiUrl
+$env:APP_UPDATE_ORIGIN = $UpdateOrigin
+& (Join-Path $PSScriptRoot 'Build-Android.ps1') -Environment dev -GradlePath (Join-Path $taskRepo '.codex-tmp/expo-tools/gradle-9.4.1/bin/gradle.bat')
diff --git a/mobile-app/scripts/Stage-DevelopmentUpdate.ps1 b/mobile-app/scripts/Stage-DevelopmentUpdate.ps1
new file mode 100644
index 0000000..5058af4
--- /dev/null
+++ b/mobile-app/scripts/Stage-DevelopmentUpdate.ps1
@@ -0,0 +1,24 @@
+param([string]$OutputDirectory = '', [string]$UpdateOrigin = '')
+$ErrorActionPreference = 'Stop'
+$taskApp = Split-Path $PSScriptRoot -Parent
+$taskRepo = Split-Path $taskApp -Parent
+if (!$OutputDirectory) { $OutputDirectory = Join-Path $taskRepo '.codex-tmp/app-dev-ota/data' }
+if (!$UpdateOrigin) { $UpdateOrigin = (Get-Content -LiteralPath (Join-Path $taskApp 'config/development.json') -Encoding UTF8 -Raw | ConvertFrom-Json).updateOrigin }
+try {
+ $env:APP_ENV = 'dev'
+ $env:APP_UPDATE_ORIGIN = $UpdateOrigin
+ $env:OTA_PRIVATE_KEY = Join-Path $taskApp 'keys/development/ota-private-key.pem'
+ $env:OTA_CERTIFICATE = Join-Path $taskApp 'certs/dev.pem'
+ $env:OTA_DATA_DIR = $OutputDirectory
+ $taskRuntime = (Get-Content -LiteralPath (Join-Path $taskApp 'dist/runtime-version.txt') -Raw).Trim()
+ $taskApkRuntime = (Get-Content -LiteralPath (Join-Path $taskApp 'android/app/build/generated/assets/createReleaseUpdatesResources/fingerprint') -Raw).Trim()
+ if ($taskRuntime -ne $taskApkRuntime) { throw 'Export fingerprint differs from built APK; rebuild before staging' }
+ $taskExportConfig = Get-Content -LiteralPath (Join-Path $taskApp 'dist/resolved-config.json') -Encoding UTF8 -Raw | ConvertFrom-Json
+ if ($taskExportConfig.extra.environment -ne 'dev' -or $taskExportConfig.updates.url -ne ($UpdateOrigin.TrimEnd('/') + '/updates/dev')) {
+ throw 'Exported App update URL differs from the development feed; export with matching development config first'
+ }
+ & node.exe (Join-Path $PSScriptRoot 'publish-update.mjs') (Join-Path $taskApp 'dist') (Join-Path $taskApp 'dist/resolved-config.json') $taskRuntime
+ if ($LASTEXITCODE) { throw 'Local signed development update staging failed' }
+} finally {
+ foreach ($taskName in @('OTA_PRIVATE_KEY','OTA_CERTIFICATE')) { Remove-Item -LiteralPath "Env:$taskName" -ErrorAction SilentlyContinue }
+}
diff --git a/mobile-app/scripts/Start-DevelopmentUpdates.ps1 b/mobile-app/scripts/Start-DevelopmentUpdates.ps1
new file mode 100644
index 0000000..26e39a4
--- /dev/null
+++ b/mobile-app/scripts/Start-DevelopmentUpdates.ps1
@@ -0,0 +1,36 @@
+$ErrorActionPreference = 'Stop'
+$taskApp = Split-Path $PSScriptRoot -Parent
+$taskRepo = Split-Path $taskApp -Parent
+$taskDir = Join-Path $taskRepo '.codex-tmp/app-dev-ota'
+$taskServer = Join-Path $PSScriptRoot 'serve-development.mjs'
+$taskConfig = Get-Content -LiteralPath (Join-Path $taskApp 'config/development.json') -Raw | ConvertFrom-Json
+$taskOrigin = $taskConfig.updateOrigin
+New-Item -ItemType Directory -Path $taskDir -Force | Out-Null
+$taskRecord = Join-Path $taskDir 'server.json'
+if (Test-Path -LiteralPath $taskRecord) {
+ $taskPrevious = Get-Content -LiteralPath $taskRecord -Raw | ConvertFrom-Json
+ $taskExisting = Get-CimInstance Win32_Process -Filter "ProcessId=$($taskPrevious.pid)"
+ if ($taskExisting -and $taskExisting.Name -eq 'node.exe' -and $taskExisting.CommandLine.Contains($taskServer) -and $taskPrevious.origin -eq $taskOrigin) {
+ if ((Invoke-WebRequest -Uri ($taskOrigin + '/health') -TimeoutSec 5 -UseBasicParsing).Content.Trim() -eq 'ok') {
+ Write-Output ('Development updates already running: ' + $taskOrigin)
+ exit 0
+ }
+ }
+ if ($taskExisting) { throw 'Recorded process does not match a healthy development update server; no process stopped.' }
+}
+$taskNode = (Get-Command node.exe).Source
+$taskProcess = Start-Process -FilePath $taskNode -ArgumentList ('"' + $taskServer + '"') -WorkingDirectory $taskApp -WindowStyle Hidden -PassThru `
+ -RedirectStandardOutput (Join-Path $taskDir 'server.out.log') -RedirectStandardError (Join-Path $taskDir 'server.err.log')
+for ($taskAttempt = 0; $taskAttempt -lt 20; $taskAttempt++) {
+ Start-Sleep -Milliseconds 250
+ $taskProcess.Refresh()
+ if ($taskProcess.HasExited) { throw (Get-Content -LiteralPath (Join-Path $taskDir 'server.err.log') -Raw) }
+ try {
+ if ((Invoke-WebRequest -Uri ($taskOrigin + '/health') -TimeoutSec 2 -UseBasicParsing).Content.Trim() -eq 'ok') {
+ [IO.File]::WriteAllText($taskRecord, (@{pid=$taskProcess.Id;origin=$taskOrigin;script=$taskServer} | ConvertTo-Json))
+ Write-Output ('Development updates running: ' + $taskOrigin)
+ exit 0
+ }
+ } catch { }
+}
+throw 'Development update service did not become ready; inspect .codex-tmp/app-dev-ota/server.err.log'
diff --git a/mobile-app/scripts/check-installable-config.cjs b/mobile-app/scripts/check-installable-config.cjs
new file mode 100644
index 0000000..ca3de47
--- /dev/null
+++ b/mobile-app/scripts/check-installable-config.cjs
@@ -0,0 +1,19 @@
+const { internal } = require('../config/environment.cjs');
+
+function assertInstallableConfig(config) {
+ const variant = config.extra?.environment;
+ if (!['dev', 'prod'].includes(variant)) throw Error('Explicit App environment required');
+ if (!config.updates?.enabled || !config.updates.codeSigningCertificate) throw Error('Installable App requires signed updates');
+ const url = new URL(config.updates.url);
+ // Loopback is valid for local preview, never for an APK delivered to phones.
+ internal(url.origin, false);
+ if (url.pathname !== `/updates/${variant}` || url.search || url.hash) throw Error('Update channel must match App environment');
+ if (config.updates.codeSigningMetadata?.keyid !== variant) throw Error('Update signing key must match App environment');
+ if (config.android?.package !== (variant === 'dev' ? 'cn.cmvr.wms.dev' : 'cn.cmvr.wms')) throw Error('App package/environment mismatch');
+ return url.toString();
+}
+module.exports = { assertInstallableConfig };
+if (require.main === module) {
+ const config = require('../app.config.js')();
+ console.log(`Installable ${config.extra.environment} App: ${assertInstallableConfig(config)}`);
+}
diff --git a/mobile-app/scripts/ota-server.mjs b/mobile-app/scripts/ota-server.mjs
index 750c498..398bbea 100644
--- a/mobile-app/scripts/ota-server.mjs
+++ b/mobile-app/scripts/ota-server.mjs
@@ -3,8 +3,10 @@ import { readFile, realpath } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-export function createOtaServer({ root, environments = ['dev', 'prod'] }) {
+export function createOtaServer({ root, environments = ['dev', 'prod'], downloadDirectory }) {
if (!environments.length || environments.some(value => !['dev', 'prod'].includes(value))) throw Error('Invalid OTA environment allowlist');
+ if (downloadDirectory && (environments.length !== 1 || environments[0] !== 'dev')) throw Error('APK downloads are development-only');
+ if (downloadDirectory) downloadDirectory = path.resolve(downloadDirectory);
root = path.resolve(root);
const server = http.createServer(async (req, res) => {
const common = { 'expo-protocol-version': '1', 'expo-sfv-version': '0',
@@ -13,6 +15,14 @@ export function createOtaServer({ root, environments = ['dev', 'prod'] }) {
if (!['GET', 'HEAD'].includes(req.method)) return send(405, 'Method not allowed');
try {
const url = new URL(req.url, 'http://localhost');
+ const download = /^\/downloads\/(cmvr-wms-dev-[a-zA-Z0-9-]+\.apk)$/.exec(url.pathname);
+ if (download && downloadDirectory) {
+ const dir = await realpath(downloadDirectory);
+ const file = await realpath(path.join(dir, download[1]));
+ if (path.dirname(file) !== dir) throw Error('Invalid download path');
+ return send(200, await readFile(file), { 'content-type': 'application/vnd.android.package-archive',
+ 'content-disposition': `attachment; filename="${download[1]}"` });
+ }
const update = /^\/updates\/(dev|prod)$/.exec(url.pathname);
if (update) {
if (!environments.includes(update[1])) return send(404, 'Not found');
diff --git a/mobile-app/scripts/serve-development.mjs b/mobile-app/scripts/serve-development.mjs
new file mode 100644
index 0000000..b16e2d5
--- /dev/null
+++ b/mobile-app/scripts/serve-development.mjs
@@ -0,0 +1,17 @@
+import path from 'node:path';
+import os from 'node:os';
+import {fileURLToPath} from 'node:url';
+import {createRequire} from 'node:module';
+import {createOtaServer} from './ota-server.mjs';
+const require=createRequire(import.meta.url);
+const {internal}=require('../config/environment.cjs');
+const development=require('../config/development.json');
+const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'../..');
+const origin=new URL(internal(development.updateOrigin,false));
+if(origin.protocol!=='http:'||origin.pathname!=='/')throw Error('Development listener requires a direct local HTTP origin');
+const addresses=Object.values(os.networkInterfaces()).flat().filter(Boolean).map(item=>item.address);
+if(!addresses.includes(origin.hostname))throw Error('Development update IP is not assigned to this computer; check config/development.json');
+const server=createOtaServer({root:path.join(root,'.codex-tmp/app-dev-ota/data'),environments:['dev'],
+ downloadDirectory:path.join(root,'.codex-tmp/app-dev-ota/downloads')});
+server.listen(Number(origin.port||80),origin.hostname,()=>console.log(`Development-only updates ready: ${origin.origin}/updates/dev`));
+server.on('error',error=>{console.error(error.message);process.exitCode=1;});
diff --git a/mobile-app/scripts/verify-development-ota.mjs b/mobile-app/scripts/verify-development-ota.mjs
new file mode 100644
index 0000000..fa43332
--- /dev/null
+++ b/mobile-app/scripts/verify-development-ota.mjs
@@ -0,0 +1,53 @@
+import assert from 'node:assert/strict';
+import {readFile,writeFile} from 'node:fs/promises';
+import {createHash,verify,X509Certificate} from 'node:crypto';
+import {createRequire} from 'node:module';
+const require=createRequire(import.meta.url),config=require('../config/development.json');
+const runtime=(await readFile(new URL('../dist/runtime-version.txt',import.meta.url),'utf8')).trim();
+const origin=config.updateOrigin,headers={'expo-platform':'android','expo-runtime-version':runtime,'expo-protocol-version':'1',
+ 'expo-expect-signature':'sig, keyid="dev", alg="rsa-v1_5-sha256"'};
+const request=route=>fetch(origin+route,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});
+const response=await request('/updates/dev');assert.equal(response.status,200);
+assert.match(response.headers.get('content-type'),/application\/expo\+json/);
+const bytes=Buffer.from(await response.arrayBuffer()),manifest=JSON.parse(bytes);
+const signatureHeader=response.headers.get('expo-signature');assert.match(signatureHeader,/keyid="dev"/);
+const signature=Buffer.from(/sig="([^"]+)"/.exec(signatureHeader)[1],'base64');
+const cert=new X509Certificate(await readFile(new URL('../certs/dev.pem',import.meta.url)));
+assert.equal(verify('RSA-SHA256',bytes,cert.publicKey,signature),true);
+assert.equal(verify('RSA-SHA256',Buffer.concat([bytes,Buffer.from('tampered')]),cert.publicKey,signature),false);
+const prod=new X509Certificate(await readFile(new URL('../certs/prod.pem',import.meta.url)));
+assert.equal(verify('RSA-SHA256',bytes,prod.publicKey,signature),false);
+assert.equal(manifest.runtimeVersion,runtime);assert.equal(manifest.metadata.environment,'dev');
+assert.equal(manifest.extra.expoClient.extra.apiUrl,config.apiUrl);
+assert.equal(manifest.extra.expoClient.updates.url,origin+'/updates/dev');
+const assets=[];
+for(const asset of [manifest.launchAsset,...manifest.assets]){
+ const url=new URL(asset.url);assert.equal(url.origin,origin);assert.match(url.pathname,/^\/assets\/[a-f0-9]{64}$/);
+ const result=await request(url.pathname);assert.equal(result.status,200);assert.match(result.headers.get('cache-control'),/immutable/);
+ const content=Buffer.from(await result.arrayBuffer());
+ assert.equal(createHash('sha256').update(content).digest('base64url'),asset.hash);
+ assets.push({hash:asset.hash,bytes:content.length});
+}
+assert.equal((await request('/updates/prod')).status,404);
+const incompatible=await fetch(origin+'/updates/dev',{headers:{...headers,'expo-runtime-version':'wrong-native-runtime'}});
+assert.equal(incompatible.status,200);assert.match(incompatible.headers.get('content-type'),/multipart\/mixed/);
+assert.equal((await request('/keys/private-key.pem')).status,404);
+assert.equal((await request('/downloads/private-key.pem')).status,404);
+const api=await fetch(config.apiUrl+'/captchaImage',{signal:AbortSignal.timeout(10000)});
+assert.equal(api.status,200);assert.equal((await api.json()).code,200);
+let downloadedApk;
+try {
+ const info=JSON.parse(await readFile(new URL('../../.codex-tmp/app-dev-ota/apk-verification.json',import.meta.url),'utf8'));
+ assert.equal(info.runtime,runtime);assert.equal(new URL(info.url).origin,origin);
+ const response=await request(new URL(info.url).pathname);assert.equal(response.status,200);
+ assert.match(response.headers.get('content-type'),/android.package-archive/);
+ const apk=Buffer.from(await response.arrayBuffer());assert.equal(apk.length,info.bytes);
+ assert.equal(createHash('sha256').update(apk).digest('hex'),info.sha256);
+ downloadedApk={url:info.url,bytes:apk.length,sha256:info.sha256,downloadHashMatched:true};
+} catch(error) {if(error.code!=='ENOENT')throw error;}
+const result={checkedAt:new Date().toISOString(),environment:'dev',updateUrl:origin+'/updates/dev',apiUrl:config.apiUrl,
+ runtime,updateId:manifest.id,signatureVerified:true,tamperedManifestRejected:true,productionKeyRejected:true,
+ productionChannelBlocked:true,incompatibleRuntimeIsolated:true,privatePathsBlocked:true,assets,
+ developmentApiReachable:true,downloadedApk,productionEnvironmentModified:false,physicalDeviceAcceptance:'pending'};
+if(process.argv[2])await writeFile(process.argv[2],JSON.stringify(result,null,2));
+console.log(JSON.stringify(result,null,2));
diff --git a/mobile-app/src/App.tsx b/mobile-app/src/App.tsx
index ed73b14..d607622 100644
--- a/mobile-app/src/App.tsx
+++ b/mobile-app/src/App.tsx
@@ -13,6 +13,7 @@ import { modules, display, recordDisplay, routeComponents, validDate, type Modul
import { AppearanceContext, Button, Card, Choice, Field, Heading, Icon, Note, s, useTheme, type Appearance, type IconName } from './ui';
import { Assistant } from './screens/Assistant';
import { ArrivalOperation } from './screens/ArrivalOperation';
+import { ArrivalActions } from './screens/ArrivalActions';
import { Workspace, BusinessHub, Me, Settings } from './screens/Workspace';
import { Account, type LeaveGuard } from './screens/Account';
import { Feedback } from './screens/Feedback';
@@ -149,15 +150,13 @@ function BusinessList({api,module,permissions}:{api:ApiClient;module:Module;perm
void load(1,query)}/>{setQuery('');void load(1,'');}}/>
{!!error&&{error} }{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}
`${row.id||row.loanNo||'row'}-${index}`} contentContainerStyle={[s.page,{paddingTop:0}]}
- refreshing={busy} onRefresh={()=>void load(page,query)} ListEmptyComponent={!busy?{error?'请重试查询。':'当前条件下暂无记录。'} :undefined}
+ refreshing={busy} onRefresh={()=>void load(page,query)} ListEmptyComponent={!busy?{error?'请重试查询。':module.key==='arrival'&&arrivalQueue==='accept'?'暂无待验收记录。先在「待登记到货」中登记实际到货,再回到这里验收。':'当前条件下暂无记录。'} :undefined}
renderItem={({item})=>
{['move','use'].includes(module.key)&&stockWrite&&setOperation({row:item,kind:module.key})}/>}
{module.key==='count'&&allows(permissions,['warehouse:check:add'])&&setOperation({row:item,kind:'check'})}/>}
{module.key==='check'&&Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm'])&&confirmCheck(item)}/>}
- {module.key==='arrival'&&allows(permissions,['warehouse:purchase:edit','warehouse:purchase:manage'])&&!item.historical&&Number(item.purchaseStatus)!==5&&
- {!!item.priceLocked&&Number(item.remainingQuantity)>0&&setOperation({row:item,kind:'arrival'})}/>}
- {Number(item.pendingArrivalQuantity)>0&&setOperation({row:item,kind:'accept'})}/>}
- }
+ {module.key==='arrival'&&setOperation({row:item,kind})}/>}
{module.key==='pending'&&allows(permissions,['warehouse:in:confirm'])&&(item.receiptRoot||allows(permissions,['warehouse:in:edit']))&&setOperation({row:item,kind:'receive'})}/>}
}/>
void load(page-1,query)}/>=total} onPress={()=>void load(page+1,query)}/>
diff --git a/mobile-app/src/core/arrival-actions.ts b/mobile-app/src/core/arrival-actions.ts
new file mode 100644
index 0000000..87d6ca9
--- /dev/null
+++ b/mobile-app/src/core/arrival-actions.ts
@@ -0,0 +1,32 @@
+import {allows} from './network.ts';
+import type {Row} from './modules';
+
+export type ArrivalKind = 'arrival' | 'accept';
+export type ArrivalAction = {kind: ArrivalKind; title: string; enabled: boolean; reason: string};
+const flag = (value: unknown) => value === true || value === 1 || value === '1' || value === 'true';
+const number = (value: unknown) => value == null || String(value).trim() === '' ? NaN : Number(value);
+const positiveId = (value: unknown) => Number.isSafeInteger(number(value)) && number(value) > 0;
+
+// These are presentation checks only; the server revalidates permission, price and quantity on submit.
+export function arrivalActions(row: Row, permissions: string[], queue: ArrivalKind): ArrivalAction[] {
+ const canOperate = allows(permissions, ['warehouse:purchase:list', 'warehouse:purchase:manage'],
+ ['warehouse:purchase:edit', 'warehouse:purchase:manage']);
+ const pending = number(row.pendingArrivalQuantity), remaining = number(row.remainingQuantity);
+ const common = !canOperate ? '当前账号可查看这条记录;需要办理时,请联系采购负责人协助。'
+ : !positiveId(row.id) ? '记录信息不完整,请刷新后重试。'
+ : flag(row.historical) ? '这是历史已入库记录,不重复登记到货或验收。'
+ : number(row.purchaseStatus) === 5 ? '这条采购已取消,不再办理到货或验收。'
+ : !flag(row.priceLocked) || !Number.isFinite(number(row.finalUnitPrice)) || number(row.finalUnitPrice) < 0
+ ? '请先在 Web 采购明细中确认采购、锁定报价,再回到这里刷新办理。' : '';
+ const registration = common || (!positiveId(row.purchaseBatchId) || !positiveId(row.supplierId)
+ ? '请先在 Web 端选择采购批次和供应商,再回到这里刷新办理。'
+ : !Number.isFinite(remaining) ? '可登记到货数量尚未获取完整,请刷新后重试。'
+ : remaining <= 0 ? pending > 0 ? '本次采购已登记到货,请办理验收。' : '没有剩余可登记数量。' : '');
+ const acceptance = common || (!Number.isFinite(pending) ? '待验收数量尚未获取完整,请刷新后重试。'
+ : pending <= 0 ? '还没有待验收的到货记录,请先登记到货。' : '');
+ const action = (kind: ArrivalKind, reason: string): ArrivalAction => ({kind,
+ title: kind === 'arrival' ? '登记到货' : '验收到货', enabled: !reason, reason});
+ return queue === 'arrival'
+ ? [action('arrival', registration), ...(pending > 0 ? [action('accept', acceptance)] : [])]
+ : [action('accept', acceptance), ...(remaining > 0 ? [action('arrival', registration)] : [])];
+}
diff --git a/mobile-app/src/core/modules.ts b/mobile-app/src/core/modules.ts
index 55afd00..0129543 100644
--- a/mobile-app/src/core/modules.ts
+++ b/mobile-app/src/core/modules.ts
@@ -2,7 +2,7 @@ export type Row = Record;
export type Module = { key: string; title: string; path: string; permissions: string[][];
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[]; guide?: string };
export const modules: Module[] = [
- { key:'arrival',title:'到货验收',path:'/warehouse/purchase/list',permissions:[['warehouse:purchase:list','warehouse:purchase:manage'],['warehouse:purchase:edit','warehouse:purchase:manage']],search:'materialName',titleKey:'materialName',guide:'先登记实际到货,再逐次验收合格/不合格数量;合格后进入待入库,不会直接增加库存。',fields:[['purchaseBatchNo','采购批次'],['projectName','所属项目'],['materialParams','规格型号'],['quantity','采购数量'],['remainingQuantity','可登记到货'],['pendingArrivalQuantity','待验收'],['unit','单位']] },
+ { key:'arrival',title:'到货验收',path:'/warehouse/purchase/list',permissions:[['warehouse:purchase:list','warehouse:purchase:manage'],['warehouse:purchase:edit','warehouse:purchase:manage']],search:'materialName',titleKey:'materialName',guide:'先确认采购、锁定报价,再登记实际到货,逐次验收合格/不合格数量;合格后进入待入库,不会直接增加库存。',fields:[['purchaseBatchNo','采购批次'],['projectName','所属项目'],['materialParams','规格型号'],['quantity','采购数量'],['remainingQuantity','未登记到货'],['pendingArrivalQuantity','待验收'],['unit','单位']] },
{ key:'use',title:'出库领用',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'选择本项目库存,核对数量后领用;跨项目使用仍须先办理借用。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'move',title:'移库',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'同项目更换存放库区,物品所属项目和总库存数量不变。',fields:[['projectName','所属项目'],['areaName','来源库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'count',title:'现场盘点',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:check:add']],search:'productName',titleKey:'productName',guide:'填写实际清点数量;登记后生成待确认记录,确认盘点后才调整库存。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','账面数量'],['unit','单位'],['spec','规格型号']] },
diff --git a/mobile-app/src/screens/ArrivalActions.tsx b/mobile-app/src/screens/ArrivalActions.tsx
new file mode 100644
index 0000000..b8c14a1
--- /dev/null
+++ b/mobile-app/src/screens/ArrivalActions.tsx
@@ -0,0 +1,16 @@
+import React from 'react';
+import {View} from 'react-native';
+import {Button, Note, s} from '../ui';
+import {arrivalActions, type ArrivalKind} from '../core/arrival-actions';
+import type {Row} from '../core/modules';
+
+export function ArrivalActions({row, permissions, queue, onOpen}: {
+ row: Row; permissions: string[]; queue: ArrivalKind; onOpen: (kind: ArrivalKind) => void;
+}) {
+ const actions = arrivalActions(row, permissions, queue);
+ return
+ {actions.map(action => {if(action.enabled) onOpen(action.kind);}}/>)}
+ {[...new Set(actions.map(action => action.reason).filter(Boolean))].map(reason => {reason} )}
+ ;
+}
diff --git a/mobile-app/tests/arrival-actions.test.mjs b/mobile-app/tests/arrival-actions.test.mjs
new file mode 100644
index 0000000..2710859
--- /dev/null
+++ b/mobile-app/tests/arrival-actions.test.mjs
@@ -0,0 +1,88 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {readFileSync} from 'node:fs';
+import {createRequire} from 'node:module';
+import vm from 'node:vm';
+import {arrivalActions} from '../src/core/arrival-actions.ts';
+
+const admin=['*:*:*'];
+const ready={id:10,historical:false,purchaseStatus:1,priceLocked:true,finalUnitPrice:12,
+ purchaseBatchId:2,supplierId:3,remainingQuantity:5,pendingArrivalQuantity:0};
+const actions=(changes={},queue='arrival',permissions=admin)=>arrivalActions({...ready,...changes},permissions,queue);
+
+test('a ready purchase exposes registration; zero is a valid locked quote',()=>{
+ for(const price of [0,'0',12,'12.50']){
+ const [a]=actions({finalUnitPrice:price});assert.equal(a.enabled,true);assert.equal(a.title,'登记到货');
+ }
+});
+test('unconfirmed purchases retain a disabled button and an actionable explanation',()=>{
+ for(const priceLocked of [false,0,'0','false',null,undefined]){
+ const [a]=actions({priceLocked});assert.equal(a.enabled,false);assert.equal(a.kind,'arrival');
+ assert.match(a.reason,/Web.*确认采购.*锁定报价/);
+ }
+});
+test('a locked flag alone cannot permit missing or invalid quotes',()=>{
+ for(const finalUnitPrice of [null,undefined,'',NaN,-1])assert.equal(actions({finalUnitPrice})[0].enabled,false);
+});
+test('registration requires the batch and its supplier, with a clear explanation',()=>{
+ for(const changes of [{purchaseBatchId:null},{supplierId:null},{supplierId:''},{purchaseBatchId:0}]){
+ assert.equal(actions(changes)[0].enabled,false);assert.match(actions(changes)[0].reason,/采购批次和供应商/);
+ }
+});
+test('pending arrivals expose acceptance even when all ordered quantity is registered',()=>{
+ const a=actions({remainingQuantity:0,pendingArrivalQuantity:5});
+ assert.equal(a[0].enabled,false);assert.match(a[0].reason,/办理验收/);
+ assert.equal(a[1].kind,'accept');assert.equal(a[1].enabled,true);
+ assert.equal(actions({remainingQuantity:0,pendingArrivalQuantity:5},'accept')[0].enabled,true);
+ // Acceptance does not invent a supplier requirement absent from the acceptance service.
+ assert.equal(actions({supplierId:null,pendingArrivalQuantity:2},'accept')[0].enabled,true);
+});
+test('pending records still require locked quotes and missing quantities fail safely',()=>{
+ assert.equal(actions({pendingArrivalQuantity:3,priceLocked:false},'accept')[0].enabled,false);
+ assert.equal(actions({pendingArrivalQuantity:undefined},'accept')[0].enabled,false);
+ assert.match(actions({pendingArrivalQuantity:0},'accept')[0].reason,/先登记到货/);
+ assert.match(actions({remainingQuantity:undefined})[0].reason,/刷新/);
+});
+test('historical and cancelled purchases can never enter either operation',()=>{
+ for(const changes of [{historical:true},{historical:1},{historical:'1'},{historical:'true'},{purchaseStatus:5},{purchaseStatus:'5'}]){
+ for(const a of actions({...changes,pendingArrivalQuantity:2}))assert.equal(a.enabled,false);
+ }
+ for(const historical of [false,0,'0','false'])assert.equal(actions({historical})[0].enabled,true);
+});
+test('both read and write permission are required; read-only accounts cannot operate',()=>{
+ for(const permissions of [[],['warehouse:purchase:list'],['warehouse:purchase:edit']]){
+ for(const a of actions({pendingArrivalQuantity:2},'accept',permissions)){
+ assert.equal(a.enabled,false);assert.match(a.reason,/采购负责人协助/);
+ }
+ }
+ for(const permissions of [['warehouse:purchase:manage'],['warehouse:purchase:list','warehouse:purchase:edit']]){
+ assert.equal(actions({},'arrival',permissions)[0].enabled,true);
+ }
+});
+
+const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
+const compiled=ts.transpileModule(readFileSync(new URL('../src/screens/ArrivalActions.tsx',import.meta.url),'utf8'),
+ {compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
+const imports={react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View'},
+ '../ui':{Button:'Button',Note:'Note',s:{row:{}}},'../core/arrival-actions':{arrivalActions}};
+const component={exports:{}};
+vm.runInNewContext(compiled,{module:component,exports:component.exports,require:name=>imports[name]||require(name)});
+function render(changes={},queue='arrival'){
+ const opened=[];
+ const tree=component.exports.ArrivalActions({row:{...ready,...changes},permissions:admin,queue,onOpen:kind=>opened.push(kind)});
+ const nodes=[];
+ function walk(node){if(!node||typeof node!=='object')return;nodes.push(node);React.Children.toArray(node.props?.children).forEach(walk);}
+ walk(tree);return {opened,buttons:nodes.filter(n=>n.type==='Button'),notes:nodes.filter(n=>n.type==='Note')};
+}
+test('real rendered controls remain visible when unavailable; even direct handler calls cannot open them',()=>{
+ const s=render({priceLocked:false,pendingArrivalQuantity:3});assert.equal(s.buttons.length,2);
+ for(const b of s.buttons){assert.equal(b.props.disabled,true);b.props.onPress();}
+ assert.deepEqual(s.opened,[]);assert.equal(s.notes.length,1);assert.match(s.notes[0].props.children,/确认采购/);
+});
+test('real rendered controls open the correct form only; they never submit a request',()=>{
+ const s=render({pendingArrivalQuantity:2});assert.deepEqual(s.buttons.map(b=>b.props.title),['登记到货','验收到货']);
+ s.buttons.forEach(b=>{assert.equal(b.props.disabled,false);b.props.onPress();});
+ assert.deepEqual(s.opened,['arrival','accept']);assert.equal(s.notes.length,0);
+ const accept=render({remainingQuantity:0,pendingArrivalQuantity:2},'accept');
+ assert.equal(accept.buttons.length,1);assert.equal(accept.buttons[0].props.title,'验收到货');
+});
diff --git a/mobile-app/tests/installable-config.test.mjs b/mobile-app/tests/installable-config.test.mjs
new file mode 100644
index 0000000..e96c784
--- /dev/null
+++ b/mobile-app/tests/installable-config.test.mjs
@@ -0,0 +1,36 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {createRequire} from 'node:module';
+import {readFileSync} from 'node:fs';
+const require=createRequire(import.meta.url);
+const {environment}=require('../config/environment.cjs');
+const {assertInstallableConfig}=require('../scripts/check-installable-config.cjs');
+const development=require('../config/development.json');
+const config=()=>({extra:{environment:'dev'},android:{package:'cn.cmvr.wms.dev'},updates:{enabled:true,
+ url:'http://192.168.28.10/updates/dev',codeSigningCertificate:'./certs/dev.pem',codeSigningMetadata:{keyid:'dev'}}});
+
+test('development default update service is reachable from phones, independent from the selected API',()=>{
+ const dev=environment({APP_ENV:'dev'});
+ assert.equal(dev.updateOrigin,development.updateOrigin);assert.equal(dev.updatesEnabled,true);
+ assert.equal(dev.apiUrl,development.apiUrl);assert.notEqual(new URL(dev.updateOrigin).hostname,'192.168.28.10');
+ assert.equal(environment({APP_ENV:'dev',APP_API_URL:'http://192.168.28.20:8080'}).updateOrigin,dev.updateOrigin);
+ // Local OTA testing remains available, but installable configuration rejects it.
+ assert.equal(environment({APP_ENV:'dev',APP_UPDATE_ORIGIN:'http://127.0.0.1:8090'}).updateOrigin,'http://127.0.0.1:8090');
+ assert.equal(assertInstallableConfig(config()),'http://192.168.28.10/updates/dev');
+});
+test('phone builds reject loopback, unsigned, public and wrong-channel update endpoints',()=>{
+ for(const url of ['http://127.0.0.1:8090/updates/dev','http://localhost:8090/updates/dev','http://8.8.8.8/updates/dev',
+ 'http://192.168.28.10/updates/prod','http://192.168.28.10/updates/dev?token=x']){
+ const c=config();c.updates.url=url;assert.throws(()=>assertInstallableConfig(c));
+ }
+ for(const changes of [{enabled:false},{codeSigningCertificate:null},{codeSigningMetadata:{keyid:'prod'}}]){
+ const c=config();Object.assign(c.updates,changes);assert.throws(()=>assertInstallableConfig(c));
+ }
+ const c=config();c.android.package='cn.cmvr.wms';assert.throws(()=>assertInstallableConfig(c));
+});
+test('every installable build checks the feed; development updates cannot be routed to the production feed',()=>{
+ const build=readFileSync(new URL('../scripts/Build-Android.ps1',import.meta.url),'utf8');
+ assert.match(build,/check-installable-config\.cjs/);
+ const stage=readFileSync(new URL('../scripts/Stage-DevelopmentUpdate.ps1',import.meta.url),'utf8');
+ assert.match(stage,/taskRuntime -ne \$taskApkRuntime/);assert.match(stage,/APP_ENV = 'dev'/);
+});
diff --git a/mobile-app/tests/ota.test.mjs b/mobile-app/tests/ota.test.mjs
index b125066..410d15c 100644
--- a/mobile-app/tests/ota.test.mjs
+++ b/mobile-app/tests/ota.test.mjs
@@ -39,3 +39,31 @@ test('production service rejects the developer channel, unsupported protocol and
assert.equal(await empty.text(),'--empty--\r\n');
assert.equal((await fetch(base+'/health')).status,200);
});
+test('development update service never serves production manifests, even when public assets are shared',async t=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'cmvr-dev-ota-')),runtime='native-dev',id=randomUUID();
+ const dir=path.join(root,'releases',id);await mkdir(dir,{recursive:true});
+ await mkdir(path.join(root,'dev/android',runtime),{recursive:true});
+ await writeFile(path.join(root,'dev/android',runtime,'current.json'),JSON.stringify({id}));
+ await writeFile(path.join(dir,'manifest.json'),JSON.stringify({id,runtimeVersion:runtime,metadata:{environment:'dev'}}));
+ await writeFile(path.join(dir,'signature.txt'),'dev-test-signature');
+ const server=createOtaServer({root,environments:['dev']});await new Promise(r=>server.listen(0,'127.0.0.1',r));
+ t.after(()=>new Promise(r=>server.close(r)));
+ const base=`http://127.0.0.1:${server.address().port}`,headers={'expo-platform':'android','expo-runtime-version':runtime};
+ const dev=await fetch(base+'/updates/dev',{headers});assert.equal(dev.status,200);assert.equal((await dev.json()).metadata.environment,'dev');
+ assert.equal((await fetch(base+'/updates/prod',{headers})).status,404);
+ const incompatible=await fetch(base+'/updates/dev',{headers:{...headers,'expo-runtime-version':'native-prod'}});
+ assert.match(incompatible.headers.get('content-type'),/multipart\/mixed/);
+});
+test('optional development APK downloads serve only named APKs; secrets and production downloads stay unavailable',async t=>{
+ const root=await mkdtemp(path.join(os.tmpdir(),'cmvr-dev-download-')),downloads=path.join(root,'downloads');
+ await mkdir(downloads);await writeFile(path.join(downloads,'cmvr-wms-dev-test-1.apk'),'test APK');
+ await writeFile(path.join(downloads,'private-key.pem'),'must not be served');
+ assert.throws(()=>createOtaServer({root,environments:['prod'],downloadDirectory:downloads}),/development-only/);
+ const server=createOtaServer({root,environments:['dev'],downloadDirectory:downloads});
+ await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));
+ const base=`http://127.0.0.1:${server.address().port}`;
+ const apk=await fetch(base+'/downloads/cmvr-wms-dev-test-1.apk');assert.equal(await apk.text(),'test APK');
+ assert.match(apk.headers.get('content-type'),/android.package-archive/);assert.equal(apk.headers.get('cache-control'),'no-store');
+ for(const route of ['/downloads/private-key.pem','/downloads/cmvr-wms-prod-test.apk','/downloads/cmvr-wms-dev-missing.apk','/downloads/../private-key.pem'])assert.equal((await fetch(base+route)).status,404);
+ assert.equal((await fetch(base+'/downloads/cmvr-wms-dev-test-1.apk',{method:'POST'})).status,405);
+});
diff --git a/mobile-app/tests/ui-contract.test.mjs b/mobile-app/tests/ui-contract.test.mjs
index def4f4c..d97d0e8 100644
--- a/mobile-app/tests/ui-contract.test.mjs
+++ b/mobile-app/tests/ui-contract.test.mjs
@@ -4,7 +4,7 @@ import {readFileSync} from 'node:fs';
import ts from 'typescript';
const source=name=>readFileSync(new URL(`../src/${name}`,import.meta.url),'utf8');
test('mobile JSX has no unexpected literal text below a native View',()=>{
- for(const file of ['App.tsx','ui.tsx','files.tsx','dialogs.tsx','screens/Account.tsx','screens/Feedback.tsx','screens/Workspace.tsx','screens/Assistant.tsx','screens/ArrivalOperation.tsx','screens/ServerConnection.tsx']){
+ for(const file of ['App.tsx','ui.tsx','files.tsx','dialogs.tsx','screens/Account.tsx','screens/Feedback.tsx','screens/Workspace.tsx','screens/Assistant.tsx','screens/ArrivalOperation.tsx','screens/ArrivalActions.tsx','screens/ServerConnection.tsx']){
const parsed=ts.createSourceFile(file,source(file),ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
function walk(node){if(ts.isJsxElement(node)&&['View','ScrollView','Pressable','KeyboardAvoidingView','SafeAreaView'].includes(node.openingElement.tagName.getText(parsed)))for(const child of node.children)if(ts.isJsxText(child))assert.equal(child.text.trim(),'',`${file} has bare native text`);ts.forEachChild(node,walk);}walk(parsed);
}
diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/AssistantConversationSafetyTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/AssistantConversationSafetyTest.java
index 3acd46d..e5f1234 100644
--- a/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/AssistantConversationSafetyTest.java
+++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/AssistantConversationSafetyTest.java
@@ -134,6 +134,28 @@ class AssistantConversationSafetyTest {
verify(mapper, never()).updateAssistantCommand(any());
}
+ @Test void unexecutedRowsCanBeRemovedAndRestoredThroughPreviewWithoutBusinessWrites() {
+ var source=row(rowTwo,2);source.put("_sourceRow",24);source.put("_sourceText","原Excel第24项");
+ stored.set(command(List.of(row(rowOne,1),source)));
+ var reduced=service.preview(1L,1,List.of(row(rowOne,1)));
+ assertEquals(2,reduced.get("version"));
+ assertEquals(List.of(rowOne),AssistantConversationService.maps(reduced.get("rows")).stream().map(r->r.get("_rowId")).toList());
+ assertThrows(ServiceException.class,()->service.execute(1L,1));
+ var restored=service.preview(1L,2,List.of(row(rowOne,1),source));
+ assertEquals(3,restored.get("version"));
+ var rows=AssistantConversationService.maps(restored.get("rows"));assertEquals(2,rows.size());
+ assertEquals("24",Objects.toString(rows.get(1).get("_sourceRow")));assertEquals("原Excel第24项",rows.get(1).get("_sourceText"));
+ verify(actions,never()).execute(anyString(),anyMap());
+ }
+
+ @Test void previewCannotRemoveAnAlreadySucceededRow() {
+ stored.set(command(List.of(row(rowOne,1),row(rowTwo,2))));
+ when(actions.execute(eq("arrival.register"),argThat(r->rowTwo.equals(r.get("_rowId"))))).thenThrow(new ServiceException("模拟待补充"));
+ assertEquals("PARTIAL",service.execute(1L,1).get("status"));
+ assertThrows(ServiceException.class,()->service.preview(1L,1,List.of(row(rowTwo,2))));
+ verify(actions,times(1)).execute(eq("arrival.register"),argThat(r->rowOne.equals(r.get("_rowId"))));
+ }
+
@Test void withdrawnBusinessPermissionHidesPersistedBusinessDetails() {
doThrow(new ServiceException("当前账号暂无登记到货权限")).when(actions).requireActionPermission("arrival.register");
Map cancelled = service.cancel(1L, 1);
diff --git a/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/BusinessActionRegistryTest.java b/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/BusinessActionRegistryTest.java
index c5ced47..cc30982 100644
--- a/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/BusinessActionRegistryTest.java
+++ b/ruoyi-admin/src/test/java/com/ruoyi/web/service/assistant/BusinessActionRegistryTest.java
@@ -53,6 +53,30 @@ class BusinessActionRegistryTest {
var row=AssistantConversationService.maps(result.get("rows")).get(0);assertTrue(((List>)row.get("_errors")).isEmpty());
verifyNoInteractions(database,purchasing);
}
+ @Test void unmatchedPdfLineCanBeExplicitlySkippedWithoutBlockingMatchedQuotesOrBecomingABusinessWrite() {
+ var corrections=mock(com.ruoyi.warehouse.service.impl.PurchasePriceCorrectionService.class);
+ var adapter=new AssistantExtendedActions();org.springframework.test.util.ReflectionTestUtils.setField(adapter,"priceCorrections",corrections);
+ when(context.getBean(AssistantExtendedActions.class)).thenReturn(adapter);
+ when(context.getBean(com.ruoyi.warehouse.service.impl.PurchasePriceCorrectionService.class)).thenReturn(corrections);
+ when(context.getBean(com.ruoyi.warehouse.service.impl.InventoryCostJournal.class)).thenReturn(mock(com.ruoyi.warehouse.service.impl.InventoryCostJournal.class));
+ var accessible=new LinkedHashMap<>(purchase(7));accessible.put("projectId",1500L);
+ when(context.getBean(com.ruoyi.project.service.IProjectInfoService.class)).thenReturn(mock(com.ruoyi.project.service.IProjectInfoService.class));
+ when(database.queryForList(anyString(),eq(7L))).thenReturn(List.of(accessible));
+ when(corrections.preview(eq(7L),any())).thenReturn(Map.of("version","v1","materialName","螺丝","oldPrice",new BigDecimal("2.50"),"newPrice",12,"archiveOnlyCount",0,"notice","模拟金额核对"));
+ var matched=Map.of("_rowId","matched","id",7L,"finalUnitPrice",12,"reason","PDF报价核对");
+ var skipped=Map.of("_rowId","missing","id",Map.of("keyword","水冷一体管","spec","白色带线1.5米"),"finalUnitPrice",29.2,"skipCorrection",true,"_sourceRow",24,"_sourceText","PDF第24项 4×29.2");
+ var prepared=registry.prepare("purchase.correctPrice",List.of(matched,skipped));
+ assertEquals(true,prepared.get("ready"),()->prepared.get("errors").toString());
+ var rows=AssistantConversationService.maps(prepared.get("rows"));assertEquals(2,rows.size());
+ assertEquals(24,rows.get(1).get("_sourceRow"));assertEquals("PDF第24项 4×29.2",rows.get(1).get("_sourceText"));
+ verify(corrections,never()).correctBatch(anyList());verifyNoInteractions(purchasing);
+ // Native persistence is mocked: prove only the matched target would reach it.
+ when(corrections.correctBatch(anyList())).thenReturn(List.of(Map.of("id",7L,"changed",true)));
+ var results=registry.executeAtomic("purchase.correctPrice",rows,"TEST-PDF-SKIP-24");
+ assertEquals(true,results.get("missing").get("skipped"));assertEquals(7L,results.get("matched").get("id"));
+ verify(corrections).correctBatch(argThat(entries->entries.size()==1&&entries.get(0).id().equals(7L)));
+ verifyNoInteractions(purchasing);
+ }
@Test void priceMatchingDoesNotExposeARecordOutsideTheCallersProjectScope() {
var access=mock(com.ruoyi.project.service.IProjectInfoService.class);when(context.getBean(com.ruoyi.project.service.IProjectInfoService.class)).thenReturn(access);
doThrow(new ServiceException("项目资料暂不可办理",403)).when(access).requireProjectAccess(1500L);
diff --git a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantConversationCard.vue b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantConversationCard.vue
index be1521f..17e8195 100644
--- a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantConversationCard.vue
+++ b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantConversationCard.vue
@@ -9,7 +9,7 @@
-
active && $emit('change', event)" @expand="$emit('expand')" />
+ active && $emit('change', event)" @remove="ids => active && $emit('remove', ids)" @restore="id => active && $emit('restore', id)" @expand="$emit('expand')" />
业务已处理,可刷新当前页面查看最新数据。 刷新当前页面
@@ -23,8 +23,8 @@ import { assistantDraftCounts, assistantDraftStatus, assistantSkippedResults } f
import AssistantDraft from './AssistantDraft.vue'
import AssistantResults from './AssistantResults.vue'
-const props = defineProps({ draft: { type: Object, required: true }, action: Object, rows: { type: Array, default: () => [] }, active: Boolean, busy: Boolean, wide: Boolean })
-defineEmits(['change', 'refresh-page', 'expand'])
+const props = defineProps({ draft: { type: Object, required: true }, action: Object, rows: { type: Array, default: () => [] }, excludedRows: { type: Array, default: () => [] }, active: Boolean, busy: Boolean, wide: Boolean })
+defineEmits(['change', 'refresh-page', 'expand', 'remove', 'restore'])
const expanded = ref(false)
const status = computed(() => assistantDraftStatus(props.draft))
const counts = computed(() => assistantDraftCounts(props.draft))
diff --git a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantDraft.vue b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantDraft.vue
index 9f9cb3c..9ddedac 100644
--- a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantDraft.vue
+++ b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantDraft.vue
@@ -1,11 +1,11 @@
- {{ draft.label || action?.label || '业务确认单' }} {{ statusLabel }} 第 {{ draft.version }} 版 · {{ counts.total }} 项
+ {{ draft.label || action?.label || '业务确认单' }} {{ statusLabel }} 第 {{ draft.version }} 版 · {{ readOnly ? counts.total : rows.length }} 项
{{ draft.description || action.description }}
{{ showAllErrors ? '收起提示' : `查看其余 ${draftErrors.length - 3} 条提示` }}
-
+
本确认单存在多个项目或采购批次,保留逐行项目供核对,不会自动合并归属。
@@ -13,7 +13,7 @@
选择已有物品可带入档案信息;新物品确认后建档。单位、类别须选用业务字典。更正已有物品类别会同步修改物品档案,确认后才保存。
{{ draft.action === 'purchase.update' ? '已有采购的所属批次保持不变;调整批次请使用采购界面的转批次功能。' : '选择已有批次,或填写新批次名称;两者均不填则保存为未组批明细。采购日期以校验预览为准,供应商可稍后补充。' }}
-
+
{{ row._sourceRow || rows.indexOf(row) + 1 }}
@@ -36,8 +36,10 @@
{{ assistantPendingRowLabel(draft) }}
+
移出本次
-
+
已移出本次 {{ excludedRows.length }} 项,未删除业务记录 恢复或继续调整后,请重新校验预览。 {{ entry.row._sourceRow ? `原表第${entry.row._sourceRow}项` : `第${entry.index + 1}项` }} · {{ excludedLabel(entry.row) }} 恢复处理
+
emit('change', event)" />
changeRow(row, { key: field.key, value })" />
@@ -63,8 +65,10 @@ import { assistantComparedFields } from '@/utils/assistant-authorization-changes
import { assistantDisplayValue, assistantDraftCounts, assistantDraftStatus, assistantPendingRowLabel, assistantReferenceConditions, assistantTextFieldOptions, isAssistantPending } from '@/utils/business-assistant'
import { isAssistantPurchase, assistantPurchaseGroups, assistantFieldLocked, assistantItemResolution } from '@/utils/assistant-draft-edit'
import { assistantOrderedColumns, assistantTableLayout, assistantTableMaxHeight } from '@/utils/assistant-table-layout'
-const props = defineProps({ draft: { type: Object, required: true }, action: Object, rows: { type: Array, default: () => [] }, busy: Boolean, wide: Boolean, readOnly: Boolean })
-const emit = defineEmits(['change', 'expand'])
+import { assistantQuotationReviewRows } from '@/utils/assistant-quotation-review'
+import { assistantCanExcludeDraftRows, assistantExcludedRowLabel } from '@/utils/assistant-draft-exclusions'
+const props = defineProps({ draft: { type: Object, required: true }, action: Object, rows: { type: Array, default: () => [] }, excludedRows: { type: Array, default: () => [] }, busy: Boolean, wide: Boolean, readOnly: Boolean })
+const emit = defineEmits(['change', 'expand', 'remove', 'restore'])
const onlyFailed = ref(false), showAllErrors = ref(false), page = ref(1), pageSize = 10
const showBulk = ref(false), selectedIds = ref([]), fieldGroup = ref('items'), draftTable = ref()
const container = ref()
@@ -91,10 +95,12 @@ const visibleFields = computed(() => {
const tableFields = computed(() => (props.draft.fields || props.action?.fields || []).filter(field => !field.hidden && field.type === 'table'))
const counts = computed(() => assistantDraftCounts(props.draft))
const editable = computed(() => !props.readOnly && !props.draft.readOnly && isAssistantPending(props.draft) && !props.draft.permissionDenied && props.action?.allowed !== false)
+const canExclude = computed(() => editable.value && assistantCanExcludeDraftRows(props.draft, props.action))
+const excludedLabel = assistantExcludedRowLabel
const tableLayout = computed(() => assistantTableLayout(
(purchase.value && nameField.value ? [nameField.value, ...visibleFields.value] : visibleFields.value)
.map(field => ({ ...field, multiline: assistantTextFieldOptions(field, props.draft.action).multiline })),
- { width: width.value - 30, editing: true, leadingWidth: 50 + (editable.value && bulkFields.value.length && props.rows.length > 1 ? 42 : 0) }
+ { width: width.value - 30, editing: true, leadingWidth: 50 + (canExclude.value ? 116 : 0) + (editable.value && (bulkFields.value.length || canExclude.value) && props.rows.length > 1 ? 42 : 0) }
))
const identityColumn = computed(() => tableLayout.value.columns.find(field => field.key === nameField.value?.key) || {})
const displayFields = computed(() => tableLayout.value.columns.filter(field => !(purchase.value && nameField.value && field.key === nameField.value.key)))
@@ -103,7 +109,7 @@ const statusType = computed(() => assistantDraftStatus(props.draft).type)
const draftErrors = computed(() => messages(props.draft.errors))
const filteredRows = computed(() => onlyFailed.value ? props.rows.filter(row => !isSucceeded(row)) : props.rows)
const pageRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize, page.value * pageSize))
-const quoteRows = computed(() => pageRows.value.flatMap(row => row._quotePreview || []))
+const quoteRows = computed(() => assistantQuotationReviewRows(pageRows.value, { draft: props.draft, fields: fields.value, editable: editable.value }))
const referencePriceRows = computed(() => pageRows.value.flatMap(row => row._referencePricePreview || []))
const historyRows = computed(() => pageRows.value.flatMap(row => row._historyPreview ? [row._historyPreview] : []))
function messages(errors) { return Array.isArray(errors) ? errors.map(String) : errors && typeof errors === 'object' ? Object.values(errors).flat().map(String) : errors ? [String(errors)] : [] }
@@ -124,8 +130,10 @@ function fieldValue(row, field) {
return option?.label || assistantDisplayValue(row[field.key])
}
function changeRow(row, event) { emit('change', { rowId: row._rowId, ...event }) }
+function removeRows(ids) { if (!props.busy && canExclude.value) emit('remove', ids) }
watch(() => props.draft.id, () => { page.value = 1; onlyFailed.value = false; showAllErrors.value = false; selectedIds.value = []; showBulk.value = false; fieldGroup.value = 'items' })
watch(() => [props.draft.id, props.draft.version], () => { selectedIds.value = []; nextTick(() => draftTable.value?.clearSelection()) })
+watch(() => props.rows.map(row => row._rowId).join(','), () => { selectedIds.value = []; nextTick(() => draftTable.value?.clearSelection()) })
watch([onlyFailed, () => filteredRows.value.length], () => { page.value = Math.min(page.value, Math.max(1, Math.ceil(filteredRows.value.length / pageSize))) })
@@ -152,4 +160,6 @@ watch([onlyFailed, () => filteredRows.value.length], () => { page.value = Math.m
.assistant-data-table :deep(.el-input__wrapper), .assistant-data-table :deep(.el-select__wrapper) { min-height: 32px; }
.assistant-data-table :deep(.el-table__cell) { padding: 0 !important; }
.assistant-data-table :deep(.assistant-row-complete) { --el-table-tr-bg-color: var(--el-color-success-light-9); }
+.assistant-excluded-rows { margin-top: 12px; padding: 12px; display: flex; flex-direction: column; gap: 6px; background: var(--el-fill-color-light); color: var(--el-text-color-regular); font-size: 12px; }
+.assistant-excluded-rows>div { display: flex; justify-content: space-between; align-items: center; gap: 12px; }.assistant-excluded-rows>div>span { overflow-wrap: anywhere; }
diff --git a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantQuotePreview.vue b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantQuotePreview.vue
index 91f534d..13b79c9 100644
--- a/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantQuotePreview.vue
+++ b/ruoyi-ui-vue3/src/components/BusinessAssistant/AssistantQuotePreview.vue
@@ -1,6 +1,7 @@
报价匹配明细 · {{ rows.length }} 项 {{ correction ? '人工确认后同步采购金额及可追溯成本;不改变数量、状态或实际金额。' : '留空报价保持原值;本次保存不会确认采购或锁价。' }}
+ 报价单中有、采购里没有的项目,可选“本次跳过”,保留原文、不新增采购。选择后请点击“校验预览”。
@@ -9,24 +10,32 @@
{{ row.previousPrice ?? '未报价' }}
- {{ row.skipped ? (correction ? '本项不更正' : '留空不变') : row.unitPrice }}
+ {{ row.skipped || row._skipSelected ? (correction ? '本次跳过' : '留空不变') : row.unitPrice }}
- {{ row.newAmount }}
+ {{ row.skipped || row._skipSelected ? '不修改' : row.newAmount }}
{{ row.notice }}
- {{ row.error || (row.skipped ? '保留原值,不更正' : '匹配成功,待人工确认') }}
+ {{ correction ? reviewState(row).text : row.error || (row.skipped ? '保留原值,不更正' : '匹配成功,待人工确认') }}
+ {{ row._skipSelected ? '恢复处理' : '本次跳过' }}
diff --git a/ruoyi-ui-vue3/src/components/BusinessAssistant/index.vue b/ruoyi-ui-vue3/src/components/BusinessAssistant/index.vue
index 5e46ef1..6ae6786 100644
--- a/ruoyi-ui-vue3/src/components/BusinessAssistant/index.vue
+++ b/ruoyi-ui-vue3/src/components/BusinessAssistant/index.vue
@@ -32,7 +32,7 @@
上一条消息仍在处理中,本条尚未发送。请使用输入区上方的“获取最新结果”,再发送补充信息。
重新识别
识别未完成,尚未执行业务。{{ retrySource(entry.message.retryMessageId)?.attachments?.length ? '可使用原消息下方的“重新识别”。' : '' }} 重新识别
-
+
正在理解需求并查询业务信息,业务数据尚未变更…
@@ -82,6 +82,7 @@ import useLockStore from '@/store/modules/lock'
import useBusinessAssistantStore from '@/store/modules/businessAssistant'
import { assistantFileError, assistantAttachmentSource, assistantResponseText, assistantRowsSignature, assistantCanKeepDraftEdits, assistantDraftCounts, assistantTimeline, assistantHasUnlinkedPendingDraft, assistantFollowScroll, assistantDuration, assistantQueryPrompt, canConfirmAssistantDraft, isAssistantExpired, isAssistantPending, isAssistantQuery } from '@/utils/business-assistant'
import { assistantApplyDraftChanges } from '@/utils/assistant-draft-edit'
+import { assistantExcludeDraftRows, assistantRestoreDraftRow } from '@/utils/assistant-draft-exclusions'
import { assistantFloatingRect, assistantMoveWindow } from '@/utils/assistant-window'
import assistantAvatar from '@/assets/images/business-assistant-avatar.png'
import defaultAvatar from '@/assets/images/profile.jpg'
@@ -96,6 +97,8 @@ import { assistantPrivateRows } from '@/utils/assistant-private-input'
const assistant = useBusinessAssistantStore(), user = useUserStore(), lock = useLockStore(), route = useRoute()
const panel = ref(), conversation = ref(), messageInput = ref(), fileInput = ref(), productFileInput = ref(), draftRows = ref([])
+const excludedDraftRows = ref([])
+watch(() => [user.id, assistant.draft?.id], () => { excludedDraftRows.value = [] })
const privateValues = ref(null), privateInputVersion = ref(0)
const newSessionPrompt = ref(false), resumePrompt = ref(false), reloadRequested = ref(false), now = ref(Date.now())
const followLatest = ref(true), lastScrollTop = ref(0)
@@ -234,6 +237,21 @@ function changeDraftRow(event) {
if (assistant.busy || assistant.needsRefresh || resumePrompt.value || !canOperateDraft.value) return
draftRows.value = assistantApplyDraftChanges(draftRows.value, event, { action: assistant.draft.action, fields: assistant.draft.fields || currentAction.value?.fields || [], draft: assistant.draft })
}
+function excludeDraftRows(ids) {
+ if (assistant.busy || assistant.uncertain || assistant.needsRefresh || resumePrompt.value || !canOperateDraft.value) return
+ const result = assistantExcludeDraftRows(draftRows.value, ids, { draft: assistant.draft, action: currentAction.value })
+ if (result.error) return ElMessage.warning(result.error)
+ draftRows.value = result.rows
+ excludedDraftRows.value.push(...result.removed)
+}
+function restoreDraftRow(id) {
+ if (assistant.busy || assistant.uncertain || assistant.needsRefresh || resumePrompt.value || !canOperateDraft.value) return
+ const entry = excludedDraftRows.value.find(item => String(item.row._rowId) === String(id))
+ const restored = assistantRestoreDraftRow(draftRows.value, entry, { draft: assistant.draft, action: currentAction.value })
+ if (restored === draftRows.value) return
+ draftRows.value = restored
+ excludedDraftRows.value = excludedDraftRows.value.filter(item => item !== entry)
+}
async function refreshPreview() { await assistant.preview(draftRows.value); now.value = Date.now() }
async function refreshState() {
if (!hasEntryPermission.value) return
diff --git a/ruoyi-ui-vue3/src/utils/assistant-draft-exclusions.js b/ruoyi-ui-vue3/src/utils/assistant-draft-exclusions.js
new file mode 100644
index 0000000..c329a34
--- /dev/null
+++ b/ruoyi-ui-vue3/src/utils/assistant-draft-exclusions.js
@@ -0,0 +1,27 @@
+import { isAssistantPending, isAssistantQuery } from './business-assistant.js'
+import { assistantRowSucceeded } from './assistant-draft-edit.js'
+
+export function assistantCanExcludeDraftRows(draft, action) {
+ return !!(isAssistantPending(draft) && action && action.allowed !== false && !isAssistantQuery(draft, action) &&
+ !draft.readOnly && !draft.permissionDenied && draft.action !== 'purchase.correctPrice')
+}
+export function assistantExcludeDraftRows(rows, ids, { draft, action } = {}) {
+ if (!assistantCanExcludeDraftRows(draft, action)) return { rows, removed: [], error: '当前确认单不能调整处理范围。' }
+ const selected = new Set((ids || []).map(String))
+ const targets = rows.filter(row => selected.has(String(row._rowId)))
+ if (!targets.length || targets.length !== selected.size || targets.some(row => row._rowId == null || assistantRowSucceeded(draft, row)))
+ return { rows, removed: [], error: '只能移出尚未执行的条目;已成功项需保留。' }
+ if (targets.length === rows.length) return { rows, removed: [], error: '请至少保留一项;整单都不办理时,请使用“取消操作”。' }
+ return { rows: rows.filter(row => !selected.has(String(row._rowId))),
+ removed: rows.flatMap((row, index) => selected.has(String(row._rowId)) ? [{ row, index, nextId: rows[index + 1]?._rowId, previousId: rows[index - 1]?._rowId }] : []) }
+}
+export function assistantRestoreDraftRow(rows, entry, { draft, action } = {}) {
+ if (!assistantCanExcludeDraftRows(draft, action) || !entry?.row?._rowId || assistantRowSucceeded(draft, entry.row) || rows.some(row => String(row._rowId) === String(entry.row._rowId))) return rows
+ const restored = [...rows], next = rows.findIndex(row => String(row._rowId) === String(entry.nextId)), previous = rows.findIndex(row => String(row._rowId) === String(entry.previousId))
+ const index = next >= 0 ? next : previous >= 0 ? previous + 1 : Math.min(entry.index, rows.length)
+ restored.splice(index, 0, entry.row)
+ return restored
+}
+export function assistantExcludedRowLabel(row) {
+ return row._labels?.id || row.materialName || row.productName || row.itemName || row.userName || row.roleName || row.name || '待处理条目'
+}
diff --git a/ruoyi-ui-vue3/src/utils/assistant-quotation-review.js b/ruoyi-ui-vue3/src/utils/assistant-quotation-review.js
new file mode 100644
index 0000000..9c00344
--- /dev/null
+++ b/ruoyi-ui-vue3/src/utils/assistant-quotation-review.js
@@ -0,0 +1,25 @@
+import { assistantRowSucceeded } from './assistant-draft-edit.js'
+
+// Keep the PDF line and its draft identity together. Skipping is an explicit
+// editable field, never removal of the source line or an automatic price write.
+export function assistantQuotationReviewRows(rows, { draft, fields = [], editable = false } = {}) {
+ const supportsSkip = draft?.action === 'purchase.correctPrice' && fields.some(field => field.key === 'skipCorrection' && !field.hidden && !field.readonly)
+ return rows.flatMap(row => (row._quotePreview || []).map(quote => ({
+ ...quote,
+ _draftRowId: row._rowId,
+ _skipSelected: row.skipCorrection === true,
+ _canSkip: supportsSkip && editable && row._rowId != null && !assistantRowSucceeded(draft, row)
+ })))
+}
+
+export function assistantQuotationSkipChange(row) {
+ if (!row?._canSkip || row._draftRowId == null) return null
+ return { rowId: row._draftRowId, key: 'skipCorrection', value: !row._skipSelected }
+}
+
+export function assistantQuotationReviewState(row) {
+ if (row._skipSelected) return { skipped: true, pending: !row.skipped, error: false,
+ text: row.skipped ? '本次跳过,不修改采购' : '已选择跳过,请重新校验预览' }
+ if (row.skipped) return { skipped: false, pending: true, error: false, text: '已恢复处理,请重新校验预览' }
+ return { skipped: false, pending: false, error: !!row.error, text: row.error || '匹配成功,待人工确认' }
+}
diff --git a/ruoyi-ui-vue3/tests/runtime/assistant-quotation-review.spec.js b/ruoyi-ui-vue3/tests/runtime/assistant-quotation-review.spec.js
new file mode 100644
index 0000000..075fc2a
--- /dev/null
+++ b/ruoyi-ui-vue3/tests/runtime/assistant-quotation-review.spec.js
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi } from 'vitest'
+import { mount, flushPromises } from '@vue/test-utils'
+import ElementPlus from 'element-plus'
+vi.mock('../../src/components/BusinessAssistant/AssistantField.vue', () => ({ default: { template: ' ' } }))
+import Preview from '../../src/components/BusinessAssistant/AssistantQuotePreview.vue'
+import Draft from '../../src/components/BusinessAssistant/AssistantDraft.vue'
+import { assistantApplyDraftChanges } from '../../src/utils/assistant-draft-edit.js'
+import { assistantExcludeDraftRows } from '../../src/utils/assistant-draft-exclusions.js'
+
+const missing = () => ({ _rowId: 'pdf-line-24', id: { keyword: '水冷一体管', spec: '白色带线1.5米' }, finalUnitPrice: 29.2,
+ _sourceRow: 24, _sourceText: '报价第24项:水冷一体管;4×29.2', _errors: ['采购明细未匹配,请选择已有记录'],
+ _quotePreview: [{ line: 24, name: '水冷一体管', previousPrice: null, unitPrice: 29.2, newAmount: null, sourceText: '报价第24项:水冷一体管;4×29.2', error: '采购明细未匹配,请选择已有记录' }] })
+const fields = [{ key: 'id', label: '采购明细', ref: 'purchase' }, { key: 'finalUnitPrice', label: '新报价', type: 'decimal' }, { key: 'skipCorrection', label: '本项暂不更正', type: 'boolean' }]
+const draft = () => ({ id: 1, action: 'purchase.correctPrice', status: 'WAIT_CONFIRM', ready: false, version: 1, fields, rows: [], results: [] })
+
+describe('unmatched PDF quotations have a visible escape without deleting source records', () => {
+ it('real draft forwards skip and restore events by original row identity, preserving the PDF data', async () => {
+ const row = missing(), confirmation = draft()
+ const wrapper = mount(Draft, { props: { draft: confirmation, action: { allowed: true }, rows: [row] },
+ global: { plugins: [ElementPlus], stubs: { AssistantField: true } } })
+ try {
+ await flushPromises()
+ const button = wrapper.find('button[aria-label="第24项本次跳过"]')
+ expect(button.exists()).toBe(true)
+ expect(wrapper.findComponent(Preview).findAllComponents({ name: 'ElTableColumn' }).some(column => column.props('label') === '本次处理' && column.props('fixed') === 'right')).toBe(true)
+ await button.trigger('click')
+ const event = wrapper.emitted('change')[0][0]
+ expect(event).toEqual({ rowId: 'pdf-line-24', key: 'skipCorrection', value: true })
+ const changed = assistantApplyDraftChanges([row], event, { action: confirmation.action, fields, draft: confirmation })
+ await wrapper.setProps({ rows: changed })
+ expect(wrapper.text()).toContain('已选择跳过,请重新校验预览')
+ expect(wrapper.text()).toContain('报价第24项:水冷一体管;4×29.2')
+ expect(changed[0].finalUnitPrice).toBe(29.2)
+ await wrapper.find('button[aria-label="第24项恢复处理"]').trigger('click')
+ expect(wrapper.emitted('change')[1][0]).toEqual({ rowId: 'pdf-line-24', key: 'skipCorrection', value: false })
+ await wrapper.setProps({ readOnly: true })
+ expect(wrapper.find('button[aria-label="第24项恢复处理"]').exists()).toBe(false)
+ } finally { wrapper.unmount() }
+ })
+ it('busy state cannot emit a skip; previewed skips are not displayed as a green successful correction', async () => {
+ const wrapper = mount(Preview, { props: { busy: true, rows: [{ ...missing()._quotePreview[0], _draftRowId: 'pdf-line-24', _canSkip: true, _skipSelected: true, skipped: true }] }, global: { plugins: [ElementPlus] } })
+ try {
+ await flushPromises()
+ expect(wrapper.text()).toContain('本次跳过,不修改采购')
+ expect(wrapper.findAll('.assistant-quote-new').length).toBe(0)
+ expect(wrapper.find('button[aria-label="第24项恢复处理"]').element.disabled).toBe(true)
+ await wrapper.find('button[aria-label="第24项恢复处理"]').trigger('click')
+ expect(wrapper.emitted('skip')).toBeUndefined()
+ } finally { wrapper.unmount() }
+ })
+ it('purchase import drafts expose removal and restoration without editing or deleting business records', async () => {
+ const confirmation = { ...draft(), action: 'purchase.create', fields: [{ key: 'materialName', label: '物品名称' }] }
+ const rows = [{ _rowId: 'good', materialName: '水泵' }, { ...missing(), materialName: '表格中不存在的物品' }]
+ const action = { allowed: true, query: false }, wrapper = mount(Draft, { props: { draft: confirmation, action, rows }, global: { plugins: [ElementPlus], stubs: { AssistantField: true } } })
+ try {
+ await flushPromises(); await wrapper.find('button[aria-label="移出第24项"]').trigger('click')
+ expect(wrapper.emitted('remove')[0][0]).toEqual(['pdf-line-24'])
+ const result = assistantExcludeDraftRows(rows, wrapper.emitted('remove')[0][0], { draft: confirmation, action })
+ await wrapper.setProps({ rows: result.rows, excludedRows: result.removed })
+ expect(wrapper.find('[aria-label="已移出本次确认单的条目"]').text()).toContain('未删除业务记录')
+ await wrapper.find('button[aria-label="恢复表格中不存在的物品"]').trigger('click')
+ expect(wrapper.emitted('restore')[0][0]).toBe('pdf-line-24')
+ await wrapper.setProps({ readOnly: true })
+ expect(wrapper.find('button[aria-label="移出第1项"]').exists()).toBe(false)
+ } finally { wrapper.unmount() }
+ })
+})
diff --git a/ruoyi-ui-vue3/tests/ui/assistant-draft-review.html b/ruoyi-ui-vue3/tests/ui/assistant-draft-review.html
new file mode 100644
index 0000000..205d368
--- /dev/null
+++ b/ruoyi-ui-vue3/tests/ui/assistant-draft-review.html
@@ -0,0 +1,26 @@
+助手确认单范围调整 · 隔离 UI 测试
+
diff --git a/ruoyi-ui-vue3/tests/unit/assistant-draft-exclusions.test.mjs b/ruoyi-ui-vue3/tests/unit/assistant-draft-exclusions.test.mjs
new file mode 100644
index 0000000..7e0ce6e
--- /dev/null
+++ b/ruoyi-ui-vue3/tests/unit/assistant-draft-exclusions.test.mjs
@@ -0,0 +1,37 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { assistantCanExcludeDraftRows, assistantExcludeDraftRows, assistantRestoreDraftRow } from '../../src/utils/assistant-draft-exclusions.js'
+import { assistantRowsSignature, canConfirmAssistantDraft } from '../../src/utils/business-assistant.js'
+const draft = { id: 1, action: 'purchase.create', status: 'WAIT_CONFIRM', version: 1, ready: true, results: [] }
+const action = { allowed: true, query: false }
+const context = { draft, action }
+const rows = [{ _rowId: 'a', materialName: '水泵', quantity: 2 }, { _rowId: 'b', materialName: '未匹配项目', _sourceRow: 24, _sourceText: '原表第24行', _errors: ['待补充'] }, { _rowId: 'c', materialName: '管件', quantity: 4 }]
+test('removing draft rows preserves data for undo and forces re-preview instead of calling business deletion', () => {
+ const original = structuredClone(rows), result = assistantExcludeDraftRows(rows, ['b'], context)
+ assert.deepEqual(result.rows.map(row => row._rowId), ['a', 'c']); assert.deepEqual(result.removed[0].row, rows[1]); assert.deepEqual(rows, original)
+ const dirty = assistantRowsSignature(result.rows) !== assistantRowsSignature(rows)
+ assert.equal(canConfirmAssistantDraft(draft, { dirty }), false)
+ assert.deepEqual(assistantRestoreDraftRow(result.rows, result.removed[0], context), rows)
+})
+test('bulk removals restore in either order without replacing other row edits', () => {
+ const result = assistantExcludeDraftRows(rows, ['a', 'b'], context)
+ for (const order of [result.removed, [...result.removed].reverse()]) {
+ let restored = result.rows.map(row => ({ ...row, quantity: 8 }))
+ for (const entry of order) restored = assistantRestoreDraftRow(restored, entry, context)
+ assert.deepEqual(restored.map(row => row._rowId), ['a', 'b', 'c']); assert.equal(restored[2].quantity, 8)
+ }
+})
+test('this applies to pending imports, master data and other writes, never queries, permissions-denied, completed or price-ledger drafts', () => {
+ for (const key of ['purchase.create', 'item.save', 'user.create', 'stock.move', 'purchase.importQuote']) assert.equal(assistantCanExcludeDraftRows({ ...draft, action: key }, action), true)
+ for (const options of [{ draft: { ...draft, readOnly: true }, action }, { draft, action: { allowed: false } }, { draft, action: { query: true } },
+ { draft: { ...draft, status: 'SUCCEEDED' }, action }, { draft: { ...draft, permissionDenied: true }, action }, { draft: { ...draft, action: 'purchase.correctPrice' }, action }]) {
+ assert.equal(assistantExcludeDraftRows(rows, ['b'], options).rows, rows)
+ }
+})
+test('successful and last remaining rows are protected; duplicate restores and unknown removals do not change the draft', () => {
+ const completed = { ...draft, results: [{ rowId: 'a', status: 'SUCCEEDED' }] }
+ assert.equal(assistantExcludeDraftRows(rows, ['a', 'b'], { draft: completed, action }).rows, rows)
+ assert.match(assistantExcludeDraftRows(rows, ['a', 'b', 'c'], context).error, /取消操作/)
+ assert.equal(assistantExcludeDraftRows(rows, ['missing'], context).rows, rows)
+ assert.equal(assistantRestoreDraftRow(rows, { row: rows[1], index: 1 }, context), rows)
+})
diff --git a/ruoyi-ui-vue3/tests/unit/assistant-quotation-review.test.mjs b/ruoyi-ui-vue3/tests/unit/assistant-quotation-review.test.mjs
new file mode 100644
index 0000000..29b6de6
--- /dev/null
+++ b/ruoyi-ui-vue3/tests/unit/assistant-quotation-review.test.mjs
@@ -0,0 +1,37 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { assistantQuotationReviewRows, assistantQuotationReviewState, assistantQuotationSkipChange } from '../../src/utils/assistant-quotation-review.js'
+import { assistantApplyDraftChanges } from '../../src/utils/assistant-draft-edit.js'
+import { assistantRowsSignature } from '../../src/utils/business-assistant.js'
+const fields = [{ key: 'id', ref: 'purchase' }, { key: 'finalUnitPrice', type: 'decimal' }, { key: 'skipCorrection', type: 'boolean' }]
+const draft = { action: 'purchase.correctPrice', status: 'WAIT_CONFIRM', version: 1, ready: false, results: [] }
+const source = () => [{ _rowId: 'matched', id: 10, finalUnitPrice: 88, _quotePreview: [{ line: 1, name: '水泵', unitPrice: 88, newAmount: 176 }] },
+ { _rowId: 'missing', id: { keyword: '水冷一体管', spec: '白色带线1.5米' }, finalUnitPrice: 29.2, _sourceRow: 24, _sourceText: '原PDF第24项 4×29.2', _errors: ['采购明细未匹配'], _quotePreview: [{ line: 24, name: '水冷一体管', unitPrice: 29.2, newAmount: null, sourceText: '原PDF第24项 4×29.2', error: '采购明细未匹配' }] }]
+const context = { draft, fields, editable: true }
+
+test('skip is an explicit editable field on the original row; PDF rows, identity, price and other matches stay intact', () => {
+ const rows = source(), original = structuredClone(rows), preview = assistantQuotationReviewRows(rows, context)
+ const event = assistantQuotationSkipChange(preview[1])
+ assert.deepEqual(event, { rowId: 'missing', key: 'skipCorrection', value: true })
+ const changed = assistantApplyDraftChanges(rows, event, { action: draft.action, fields, draft })
+ assert.equal(changed.length, 2); assert.equal(changed[0], rows[0]); assert.equal(changed[1].skipCorrection, true)
+ for (const key of ['id', 'finalUnitPrice', '_sourceRow', '_sourceText', '_quotePreview']) assert.deepEqual(changed[1][key], original[1][key])
+ assert.deepEqual(rows, original)
+ assert.notEqual(assistantRowsSignature(changed), assistantRowsSignature(rows), 'the old ready/confirmation signature must become stale')
+ const selected = assistantQuotationReviewRows(changed, context)[1]
+ assert.deepEqual(assistantQuotationReviewState(selected), { skipped: true, pending: true, error: false, text: '已选择跳过,请重新校验预览' })
+ assert.equal(assistantQuotationSkipChange(selected).value, false)
+})
+test('previewed skips and restored rows are shown honestly; no skip is inferred from a lookup error', () => {
+ const missing = assistantQuotationReviewRows(source(), context)[1]
+ assert.equal(missing._skipSelected, false); assert.equal(assistantQuotationReviewState(missing).error, true)
+ assert.equal(assistantQuotationReviewState({ ...missing, skipped: true, _skipSelected: true }).text, '本次跳过,不修改采购')
+ assert.equal(assistantQuotationReviewState({ ...missing, skipped: true, _skipSelected: false }).text, '已恢复处理,请重新校验预览')
+})
+test('history, succeeded, unauthorized and missing-schema rows never expose skip edits', () => {
+ for (const options of [{ ...context, editable: false }, { ...context, fields: [] }, { ...context, fields: [{ key: 'skipCorrection', readonly: true }] },
+ { ...context, draft: { ...draft, action: 'purchase.importQuote' } }, { ...context, draft: { ...draft, results: [{ rowId: 'missing', status: 'SUCCEEDED' }] } }]) {
+ const row = assistantQuotationReviewRows(source(), options)[1]
+ assert.equal(row._canSkip, false); assert.equal(assistantQuotationSkipChange(row), null)
+ }
+})