feat(assistant): 优化业务助手功能和移动应用配置
- 实现业务确认单条目的移出和恢复功能 - 添加报价匹配明细中的跳过处理选项 - 重构移动应用的环境配置使用默认开发配置 - 更新移动应用Android版本号策略 - 替换到货操作组件为独立的操作组件 - 添加安装配置检查脚本 - 增强测试覆盖包括条目移出恢复和报价跳过场景
This commit is contained in:
parent
ba81b6f778
commit
5cee6482f8
@ -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
|
||||
|
||||
@ -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'] : [])],
|
||||
|
||||
4
mobile-app/config/development.json
Normal file
4
mobile-app/config/development.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"apiUrl": "http://192.168.0.222:8080",
|
||||
"updateOrigin": "http://192.168.0.222:8090"
|
||||
}
|
||||
@ -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 更新签名证书。');
|
||||
|
||||
20
mobile-app/deploy/DEVELOPMENT.html
Normal file
20
mobile-app/deploy/DEVELOPMENT.html
Normal file
@ -0,0 +1,20 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>开发 App 与内网热更新</title><style>body{font:16px/1.8 system-ui;max-width:900px;margin:32px auto;padding:0 20px;color:#24354a}pre{white-space:pre-wrap;background:#f3f5f8;padding:16px}h2{margin-top:28px}</style>
|
||||
<h1>开发 App 与内网热更新</h1><p>2026-10-20。开发业务和更新均放开发电脑,不登录或修改正式环境 192.168.28.10。</p>
|
||||
<p>地址统一保存在 <code>mobile-app/config/development.json</code>:业务 http://192.168.0.222:8080,更新 http://192.168.0.222:8090/updates/dev。开发 App 的业务地址仍可在登录页、设置中修改;更新地址独立固定,不跟随业务地址跳转。</p>
|
||||
<h2>首次安装与后续更新</h2><p>旧开发包内置更新地址为手机自己的 127.0.0.1,需覆盖安装本次新包一次,保留同一包名和 Android 开发签名。之后页面和业务 JS 修复使用签名热更新;不需要 Expo Go 或重新安装。新增原生模块、修改 SDK、证书、原生网络设置等改变兼容指纹时仍需新包。</p>
|
||||
<p>手机须能访问开发电脑,电脑及开发更新服务须保持运行。App 启动后后台检查并下载;在“我的→设置”看到更新已备妥后,完全退出并重新打开生效,不强制中断编辑。断网继续使用内置或已下载版本。</p>
|
||||
<h2>开发电脑启动服务</h2><pre>powershell -File mobile-app/scripts/Start-DevelopmentUpdates.ps1</pre>
|
||||
<p>服务只绑定配置中的本机内网 IP,允许 dev 通道,不服务 prod 通道。更新与安装包公开资源在 .codex-tmp/app-dev-ota,签名私钥不放在服务目录,不通过 HTTP 提供。当前进程信息、日志保存在该目录;重启电脑后重新运行启动脚本。不会停止其他未知进程。</p>
|
||||
<h2>下次发布页面更新</h2><pre>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</pre>
|
||||
<p>暂存脚本会核对导出与最近 APK 的原生指纹,使用 dev 私钥签名,并把新版本及不可变资源写到开发服务目录;服务不必重启。发布前必须先通过测试。若要完整打包,使用 scripts/Build-Development.ps1;所有 APK 构建都会拒绝 loopback 更新地址或未签名配置。</p>
|
||||
<p>正式环境、正式签名、正式更新通道均保持不变。开发电脑 IP 最好固定或做 DHCP 地址保留;如果 IP 改变,现有包的固定更新地址也会失效。不要关闭防火墙来排障,只按组织网络策略允许手机访问开发服务。</p>
|
||||
<p>本机开发更新签名私钥长期保存在被 Git 忽略且限制访问的 mobile-app/keys/development/ota-private-key.pem,服务只挂公开资源,不提供私钥。保留并备份同一私钥和 certs/dev.pem;不要重新生成来替换,否则已安装客户端不会接受新签名。旧临时副本仅作保留备份,后续发布不依赖临时目录中的密钥。</p>
|
||||
<p>服务端签名、资源哈希和协议验证不等于真机已完成下载与重启生效验收,须在手机上另行核对。</p></html>
|
||||
@ -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
|
||||
|
||||
10
mobile-app/scripts/Build-Development.ps1
Normal file
10
mobile-app/scripts/Build-Development.ps1
Normal file
@ -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')
|
||||
24
mobile-app/scripts/Stage-DevelopmentUpdate.ps1
Normal file
24
mobile-app/scripts/Stage-DevelopmentUpdate.ps1
Normal file
@ -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 }
|
||||
}
|
||||
36
mobile-app/scripts/Start-DevelopmentUpdates.ps1
Normal file
36
mobile-app/scripts/Start-DevelopmentUpdates.ps1
Normal file
@ -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'
|
||||
19
mobile-app/scripts/check-installable-config.cjs
Normal file
19
mobile-app/scripts/check-installable-config.cjs
Normal file
@ -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)}`);
|
||||
}
|
||||
@ -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');
|
||||
|
||||
17
mobile-app/scripts/serve-development.mjs
Normal file
17
mobile-app/scripts/serve-development.mjs
Normal file
@ -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;});
|
||||
53
mobile-app/scripts/verify-development-ota.mjs
Normal file
53
mobile-app/scripts/verify-development-ota.mjs
Normal file
@ -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));
|
||||
@ -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
|
||||
<View style={s.row}><Button title="查询" busy={busy} onPress={()=>void load(1,query)}/><Button title="重置" secondary disabled={busy} onPress={()=>{setQuery('');void load(1,'');}}/></View>
|
||||
{!!error&&<Note>{error}</Note>}<Note>{busy?'正在获取最新数据…':`共 ${total} 条 · 第 ${page} 页`}</Note></View>
|
||||
<FlatList data={rows} keyExtractor={(row,index)=>`${row.id||row.loanNo||'row'}-${index}`} contentContainerStyle={[s.page,{paddingTop:0}]}
|
||||
refreshing={busy} onRefresh={()=>void load(page,query)} ListEmptyComponent={!busy?<Note>{error?'请重试查询。':'当前条件下暂无记录。'}</Note>:undefined}
|
||||
refreshing={busy} onRefresh={()=>void load(page,query)} ListEmptyComponent={!busy?<Note>{error?'请重试查询。':module.key==='arrival'&&arrivalQueue==='accept'?'暂无待验收记录。先在「待登记到货」中登记实际到货,再回到这里验收。':'当前条件下暂无记录。'}</Note>:undefined}
|
||||
renderItem={({item})=><RecordCard module={module} item={item} compactAmounts={compactAmounts}>
|
||||
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'领用出库'} secondary disabled={Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
|
||||
{module.key==='count'&&allows(permissions,['warehouse:check:add'])&&<Button title="登记盘点" secondary onPress={()=>setOperation({row:item,kind:'check'})}/>}
|
||||
{module.key==='check'&&Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm'])&&<Button title="确认盘点生效" secondary disabled={busy} onPress={()=>confirmCheck(item)}/>}
|
||||
{module.key==='arrival'&&allows(permissions,['warehouse:purchase:edit','warehouse:purchase:manage'])&&!item.historical&&Number(item.purchaseStatus)!==5&&<View style={s.row}>
|
||||
{!!item.priceLocked&&Number(item.remainingQuantity)>0&&<Button title="登记到货" secondary onPress={()=>setOperation({row:item,kind:'arrival'})}/>}
|
||||
{Number(item.pendingArrivalQuantity)>0&&<Button title="验收到货" secondary onPress={()=>setOperation({row:item,kind:'accept'})}/>}
|
||||
</View>}
|
||||
{module.key==='arrival'&&<ArrivalActions row={item} permissions={permissions} queue={arrivalQueue}
|
||||
onOpen={kind=>setOperation({row:item,kind})}/>}
|
||||
{module.key==='pending'&&allows(permissions,['warehouse:in:confirm'])&&(item.receiptRoot||allows(permissions,['warehouse:in:edit']))&&<Button title="办理入库" secondary onPress={()=>setOperation({row:item,kind:'receive'})}/>}
|
||||
</RecordCard>}/>
|
||||
<View style={[s.row,{padding:12,justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={busy||page<=1} onPress={()=>void load(page-1,query)}/><Button title="下一页" secondary disabled={busy||page*20>=total} onPress={()=>void load(page+1,query)}/></View>
|
||||
|
||||
32
mobile-app/src/core/arrival-actions.ts
Normal file
32
mobile-app/src/core/arrival-actions.ts
Normal file
@ -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)] : [])];
|
||||
}
|
||||
@ -2,7 +2,7 @@ export type Row = Record<string, any>;
|
||||
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','规格型号']] },
|
||||
|
||||
16
mobile-app/src/screens/ArrivalActions.tsx
Normal file
16
mobile-app/src/screens/ArrivalActions.tsx
Normal file
@ -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 <View style={{gap:8}}>
|
||||
<View style={s.row}>{actions.map(action => <Button key={action.kind} title={action.title} secondary
|
||||
disabled={!action.enabled} onPress={() => {if(action.enabled) onOpen(action.kind);}}/>)}</View>
|
||||
{[...new Set(actions.map(action => action.reason).filter(Boolean))].map(reason => <Note key={reason}>{reason}</Note>)}
|
||||
</View>;
|
||||
}
|
||||
88
mobile-app/tests/arrival-actions.test.mjs
Normal file
88
mobile-app/tests/arrival-actions.test.mjs
Normal file
@ -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,'验收到货');
|
||||
});
|
||||
36
mobile-app/tests/installable-config.test.mjs
Normal file
36
mobile-app/tests/installable-config.test.mjs
Normal file
@ -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'/);
|
||||
});
|
||||
@ -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);
|
||||
});
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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<String, Object> cancelled = service.cancel(1L, 1);
|
||||
|
||||
@ -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.<String,Object>of("_rowId","matched","id",7L,"finalUnitPrice",12,"reason","PDF报价核对");
|
||||
var skipped=Map.<String,Object>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);
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
</button>
|
||||
<el-alert v-for="item in skippedResults" :key="item.rowId" :title="`本次已跳过,未更正:${item.label}`" type="warning" :closable="false" class="assistant-skipped-result" />
|
||||
<div v-if="active || expanded" class="assistant-conversation-card-detail">
|
||||
<assistant-draft :draft="draft" :action="action" :rows="active ? rows : draft.rows || []" :read-only="!active" :busy="busy" :wide="wide" @change="event => active && $emit('change', event)" @expand="$emit('expand')" />
|
||||
<assistant-draft :draft="draft" :action="action" :rows="active ? rows : draft.rows || []" :excluded-rows="active ? excludedRows : []" :read-only="!active" :busy="busy" :wide="wide" @change="event => active && $emit('change', event)" @remove="ids => active && $emit('remove', ids)" @restore="id => active && $emit('restore', id)" @expand="$emit('expand')" />
|
||||
<assistant-results v-if="draft.results?.length" :results="draft.results" :action="draft.action || action?.key" />
|
||||
<div v-if="counts.succeeded && action && !action.query" class="assistant-page-refresh"><span>业务已处理,可刷新当前页面查看最新数据。</span><el-button size="small" :icon="Refresh" :disabled="busy" @click="$emit('refresh-page')">刷新当前页面</el-button></div>
|
||||
</div>
|
||||
@ -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))
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
<template>
|
||||
<section ref="container" class="assistant-draft" aria-label="业务确认单">
|
||||
<div class="assistant-draft-heading"><strong>{{ draft.label || action?.label || '业务确认单' }}</strong><el-tag :type="statusType" size="small">{{ statusLabel }}</el-tag><span>第 {{ draft.version }} 版 · {{ counts.total }} 项</span></div>
|
||||
<div class="assistant-draft-heading"><strong>{{ draft.label || action?.label || '业务确认单' }}</strong><el-tag :type="statusType" size="small">{{ statusLabel }}</el-tag><span>第 {{ draft.version }} 版 · {{ readOnly ? counts.total : rows.length }} 项</span></div>
|
||||
<p v-if="draft.description || action?.description" class="assistant-action-description">{{ draft.description || action.description }}</p>
|
||||
<el-alert v-if="action?.allowed === false" :title="action.deniedReason || '这项操作可以请管理员协助确认处理方式。'" type="warning" :closable="false" />
|
||||
<el-alert v-for="(error, index) in draftErrors.slice(0, showAllErrors ? draftErrors.length : 3)" :key="index" :title="error" type="warning" :closable="false" />
|
||||
<el-button v-if="draftErrors.length > 3" link type="primary" size="small" @click="showAllErrors = !showAllErrors">{{ showAllErrors ? '收起提示' : `查看其余 ${draftErrors.length - 3} 条提示` }}</el-button>
|
||||
<div class="assistant-draft-tools"><span>{{ readOnly ? '历史确认单,仅供查看。' : '核对下列数据后再确认;红色信息需先处理。' }}</span><div><el-button v-if="editable && bulkFields.length && rows.length > 1" size="small" :disabled="busy" @click="showBulk = !showBulk">{{ showBulk ? '收起批量设置' : '批量设置' }}</el-button><el-button v-if="!wide && fields.length > 5" size="small" @click="$emit('expand')">展开工作区</el-button><el-checkbox v-if="counts.failed" v-model="onlyFailed">仅未成功项</el-checkbox></div></div>
|
||||
<div class="assistant-draft-tools"><span>{{ readOnly ? '历史确认单,仅供查看。' : '核对下列数据后再确认;红色信息需先处理。' }}</span><div><el-button v-if="canExclude && rows.length > 1" size="small" :disabled="busy || !selectedIds.length" @click="removeRows(selectedIds)">移出选中项</el-button><el-button v-if="editable && bulkFields.length && rows.length > 1" size="small" :disabled="busy" @click="showBulk = !showBulk">{{ showBulk ? '收起批量设置' : '批量设置' }}</el-button><el-button v-if="!wide && fields.length > 5" size="small" @click="$emit('expand')">展开工作区</el-button><el-checkbox v-if="counts.failed" v-model="onlyFailed">仅未成功项</el-checkbox></div></div>
|
||||
<assistant-bulk-edit v-if="editable && showBulk && bulkFields.length" :action="draft.action" :draft="draft" :rows="rows" :fields="bulkFields" :selected-ids="selectedIds" :busy="busy" @change="$emit('change', $event)" />
|
||||
<assistant-purchase-project v-if="sharedProject && projectField" :action="draft.action" :field="projectField" :rows="rows" :draft="draft" :editable="editable" :busy="busy" @change="$emit('change',$event)" />
|
||||
<p v-else-if="purchase && projectField" class="assistant-purchase-note">本确认单存在多个项目或采购批次,保留逐行项目供核对,不会自动合并归属。</p>
|
||||
@ -13,7 +13,7 @@
|
||||
<p v-if="purchase && editable && (fieldGroup === 'items' || fieldGroup === 'all')" class="assistant-purchase-note">选择已有物品可带入档案信息;新物品确认后建档。单位、类别须选用业务字典。更正已有物品类别会同步修改物品档案,确认后才保存。</p>
|
||||
<p v-if="purchase && fieldGroup === 'batch'" class="assistant-purchase-note">{{ draft.action === 'purchase.update' ? '已有采购的所属批次保持不变;调整批次请使用采购界面的转批次功能。' : '选择已有批次,或填写新批次名称;两者均不填则保存为未组批明细。采购日期以校验预览为准,供应商可稍后补充。' }}</p>
|
||||
<el-table ref="draftTable" :data="pageRows" row-key="_rowId" border :max-height="tableHeight" class="assistant-data-table" :row-class-name="rowClass" @selection-change="setSelection">
|
||||
<el-table-column v-if="editable && bulkFields.length && rows.length > 1" type="selection" width="42" :fixed="tableLayout.fixed ? 'left' : false" reserve-selection :selectable="row => !busy && !isSucceeded(row)" />
|
||||
<el-table-column v-if="editable && (bulkFields.length || canExclude) && rows.length > 1" type="selection" width="42" :fixed="tableLayout.fixed ? 'left' : false" reserve-selection :selectable="row => !busy && !isSucceeded(row)" />
|
||||
<el-table-column label="行" width="50" align="center" :fixed="tableLayout.fixed ? 'left' : false"><template #default="{ row }">{{ row._sourceRow || rows.indexOf(row) + 1 }}</template></el-table-column>
|
||||
<el-table-column v-if="purchase && nameField" label="物品名称 *" :width="identityColumn.displayWidth" :min-width="identityColumn.displayMinWidth" :fixed="identityColumn.fixed" :show-overflow-tooltip="false" class-name="business-control-cell">
|
||||
<template #default="{ row }"><div class="assistant-purchase-identity">
|
||||
@ -36,8 +36,10 @@
|
||||
<span v-if="!resultFor(row) && (draft.status === 'CANCELLED' || !rowErrors(row).length)" class="assistant-muted">{{ assistantPendingRowLabel(draft) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="canExclude" label="本次处理" width="116" fixed="right" class-name="business-operation-cell"><template #default="{ row }"><el-button v-if="!isSucceeded(row)" link type="primary" size="small" :disabled="busy" :aria-label="`移出第${row._sourceRow || rows.indexOf(row) + 1}项`" @click="removeRows([row._rowId])">移出本次</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<assistant-quote-preview v-if="quoteRows.length" :rows="quoteRows" />
|
||||
<section v-if="canExclude && excludedRows.length" class="assistant-excluded-rows" aria-label="已移出本次确认单的条目"><strong>已移出本次 {{ excludedRows.length }} 项,未删除业务记录</strong><span>恢复或继续调整后,请重新校验预览。</span><div v-for="entry in excludedRows" :key="entry.row._rowId"><span>{{ entry.row._sourceRow ? `原表第${entry.row._sourceRow}项` : `第${entry.index + 1}项` }} · {{ excludedLabel(entry.row) }}</span><el-button link type="primary" size="small" :disabled="busy" :aria-label="`恢复${excludedLabel(entry.row)}`" @click="!busy && emit('restore', entry.row._rowId)">恢复处理</el-button></div></section>
|
||||
<assistant-quote-preview v-if="quoteRows.length" :rows="quoteRows" :busy="busy" @skip="event => emit('change', event)" />
|
||||
<assistant-reference-price-preview v-if="referencePriceRows.length" :rows="referencePriceRows" />
|
||||
<history-preview v-if="historyRows.length" :rows="historyRows"/>
|
||||
<template v-for="row in pageRows" :key="row._rowId"><assistant-lines v-for="field in tableFields" :key="field.key" :model-value="row[field.key] || []" :action="draft.action" :title="`第 ${rows.indexOf(row) + 1} 项 · ${field.label}`" :editable="editable && !isSucceeded(row)" :busy="busy" @update:model-value="value => changeRow(row, { key: field.key, value })" /></template>
|
||||
@ -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))) })
|
||||
</script>
|
||||
|
||||
@ -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; }
|
||||
</style>
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<section class="assistant-quote-preview" aria-label="供应商报价逐项核对">
|
||||
<header><strong>报价匹配明细 · {{ rows.length }} 项</strong><span>{{ correction ? '人工确认后同步采购金额及可追溯成本;不改变数量、状态或实际金额。' : '留空报价保持原值;本次保存不会确认采购或锁价。' }}</span></header>
|
||||
<p v-if="canSkip" class="assistant-quote-skip-hint">报价单中有、采购里没有的项目,可选“本次跳过”,保留原文、不新增采购。选择后请点击“校验预览”。</p>
|
||||
<el-table :data="pageRows" border max-height="380" class="assistant-quote-table">
|
||||
<el-table-column prop="line" label="原表行" width="70"/>
|
||||
<el-table-column prop="name" label="物品名称" min-width="160"/>
|
||||
@ -9,24 +10,32 @@
|
||||
<el-table-column prop="unit" label="单位" width="70"/>
|
||||
<el-table-column prop="quantity" label="采购数量" width="100"/>
|
||||
<el-table-column label="原报价" width="110"><template #default="{ row }">{{ row.previousPrice ?? '未报价' }}</template></el-table-column>
|
||||
<el-table-column label="新报价" width="110"><template #default="{ row }"><span :class="!row.skipped ? 'assistant-quote-new' : ''">{{ row.skipped ? (correction ? '本项不更正' : '留空不变') : row.unitPrice }}</span></template></el-table-column>
|
||||
<el-table-column label="新报价" width="110"><template #default="{ row }"><span :class="!row.skipped && !row._skipSelected ? 'assistant-quote-new' : ''">{{ row.skipped || row._skipSelected ? (correction ? '本次跳过' : '留空不变') : row.unitPrice }}</span></template></el-table-column>
|
||||
<el-table-column v-if="correction" prop="oldAmount" label="原采购金额" width="120"/>
|
||||
<el-table-column v-if="correction" label="新采购金额" width="120"><template #default="{ row }"><strong class="assistant-quote-new">{{ row.newAmount }}</strong></template></el-table-column>
|
||||
<el-table-column v-if="correction" label="新采购金额" width="120"><template #default="{ row }"><strong :class="!row.skipped && !row._skipSelected ? 'assistant-quote-new' : ''">{{ row.skipped || row._skipSelected ? '不修改' : row.newAmount }}</strong></template></el-table-column>
|
||||
<el-table-column v-if="correction" label="联动影响" min-width="260"><template #default="{ row }">{{ row.notice }}</template></el-table-column>
|
||||
<el-table-column v-if="correction" prop="sourceText" label="报价原文(核对规格及数量)" min-width="300"/>
|
||||
<el-table-column label="核对结果" min-width="200"><template #default="{ row }"><span :class="row.error ? 'assistant-quote-error' : ''">{{ row.error || (row.skipped ? '保留原值,不更正' : '匹配成功,待人工确认') }}</span></template></el-table-column>
|
||||
<el-table-column label="核对结果" min-width="200"><template #default="{ row }"><span :class="reviewState(row).error ? 'assistant-quote-error' : ''">{{ correction ? reviewState(row).text : row.error || (row.skipped ? '保留原值,不更正' : '匹配成功,待人工确认') }}</span></template></el-table-column>
|
||||
<el-table-column v-if="canSkip" label="本次处理" width="126" fixed="right" class-name="business-operation-cell assistant-quote-action-cell"><template #default="{ row }"><el-button v-if="row._canSkip" link type="primary" size="small" :disabled="busy" :aria-label="`第${row.line}项${row._skipSelected ? '恢复处理' : '本次跳过'}`" @click="toggleSkip(row)">{{ row._skipSelected ? '恢复处理' : '本次跳过' }}</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-if="rows.length > 20" v-model:current-page="page" :page-size="20" :total="rows.length" layout="total, prev, pager, next" :pager-count="5" small/>
|
||||
</section>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref, computed, watch } from 'vue'
|
||||
const props = defineProps({ rows: { type: Array, default: () => [] } })
|
||||
import { assistantQuotationReviewState, assistantQuotationSkipChange } from '@/utils/assistant-quotation-review'
|
||||
const props = defineProps({ rows: { type: Array, default: () => [] }, busy: Boolean })
|
||||
const emit = defineEmits(['skip'])
|
||||
const page = ref(1), pageRows = computed(() => props.rows.slice((page.value - 1) * 20, page.value * 20))
|
||||
const correction = computed(() => props.rows.some(row => Object.hasOwn(row, 'newAmount')))
|
||||
const canSkip = computed(() => correction.value && props.rows.some(row => row._canSkip))
|
||||
const reviewState = assistantQuotationReviewState
|
||||
function toggleSkip(row) { if (props.busy) return; const change = assistantQuotationSkipChange(row); if (change) emit('skip', change) }
|
||||
watch(() => props.rows, () => { page.value = 1 })
|
||||
</script>
|
||||
<style scoped>
|
||||
.assistant-quote-preview { margin-top: 16px; min-width: 0; }.assistant-quote-preview header { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; font-size: 13px; }.assistant-quote-preview header span { color: var(--el-text-color-secondary); }
|
||||
.assistant-quote-new { color: var(--el-color-success); font-weight: 600; }.assistant-quote-error { color: var(--el-color-danger); }.assistant-quote-table :deep(.cell) { white-space: normal; overflow-wrap: anywhere; }.el-pagination { margin-top: 10px; }
|
||||
.assistant-quote-skip-hint { margin: 0 0 10px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
|
||||
.assistant-quote-table :deep(.assistant-quote-action-cell .cell) { white-space: nowrap; }
|
||||
</style>
|
||||
|
||||
@ -32,7 +32,7 @@
|
||||
<div v-if="entry.message.delivery === 'NOT_SENT'" class="assistant-recognition-failed" role="status">上一条消息仍在处理中,本条尚未发送。请使用输入区上方的“获取最新结果”,再发送补充信息。</div>
|
||||
<div v-if="entry.message.role === 'user' && entry.message.id && !entry.message.delivery && entry.message.attachments?.length" class="assistant-message-retry"><el-button link type="primary" size="small" :disabled="!!assistant.busy || assistant.needsRefresh || !allowed" @click="retryRecognition(entry.message.id)">重新识别</el-button></div>
|
||||
<div v-if="entry.message.recognitionFailed" class="assistant-recognition-failed" role="status"><span>识别未完成,尚未执行业务。{{ retrySource(entry.message.retryMessageId)?.attachments?.length ? '可使用原消息下方的“重新识别”。' : '' }}</span><el-button v-if="retrySource(entry.message.retryMessageId) && !retrySource(entry.message.retryMessageId).attachments?.length" link type="primary" size="small" :disabled="!!assistant.busy || assistant.needsRefresh || !allowed" @click="retryRecognition(entry.message.retryMessageId)">重新识别</el-button></div>
|
||||
<assistant-conversation-card v-if="entry.draft" :draft="entry.draft" :action="actionFor(entry.draft)" :active="entry.active && canOperateDraft" :rows="draftRows" :busy="!!assistant.busy || assistant.uncertain || assistant.needsRefresh" :wide="assistant.wide" @change="changeDraftRow" @refresh-page="refreshBusinessPage" @expand="assistant.wide = true" />
|
||||
<assistant-conversation-card v-if="entry.draft" :draft="entry.draft" :action="actionFor(entry.draft)" :active="entry.active && canOperateDraft" :rows="draftRows" :excluded-rows="excludedDraftRows" :busy="!!assistant.busy || assistant.uncertain || assistant.needsRefresh" :wide="assistant.wide" @change="changeDraftRow" @remove="excludeDraftRows" @restore="restoreDraftRow" @refresh-page="refreshBusinessPage" @expand="assistant.wide = true" />
|
||||
<assistant-query v-if="entry.query" :query="entry.query" :action="actionFor(entry.query)" :busy="!!assistant.busy || assistant.needsRefresh" @refine="refineQuery" />
|
||||
</article>
|
||||
<div v-if="assistant.busy === 'message'" class="assistant-loading" role="status"><el-icon class="is-loading"><Loading /></el-icon> 正在理解需求并查询业务信息,业务数据尚未变更…</div>
|
||||
@ -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
|
||||
|
||||
27
ruoyi-ui-vue3/src/utils/assistant-draft-exclusions.js
Normal file
27
ruoyi-ui-vue3/src/utils/assistant-draft-exclusions.js
Normal file
@ -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 || '待处理条目'
|
||||
}
|
||||
25
ruoyi-ui-vue3/src/utils/assistant-quotation-review.js
Normal file
25
ruoyi-ui-vue3/src/utils/assistant-quotation-review.js
Normal file
@ -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 || '匹配成功,待人工确认' }
|
||||
}
|
||||
@ -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: '<span />' } }))
|
||||
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() }
|
||||
})
|
||||
})
|
||||
26
ruoyi-ui-vue3/tests/ui/assistant-draft-review.html
Normal file
26
ruoyi-ui-vue3/tests/ui/assistant-draft-review.html
Normal file
@ -0,0 +1,26 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>助手确认单范围调整 · 隔离 UI 测试</title><div id="app"></div>
|
||||
<script type="module">
|
||||
import {createApp,ref} from 'vue/dist/vue.esm-bundler.js'
|
||||
import {createPinia} from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import Draft from '../../src/components/BusinessAssistant/AssistantDraft.vue'
|
||||
import {assistantApplyDraftChanges} from '../../src/utils/assistant-draft-edit.js'
|
||||
import {assistantExcludeDraftRows,assistantRestoreDraftRow} from '../../src/utils/assistant-draft-exclusions.js'
|
||||
createApp({components:{Draft},setup(){
|
||||
const mode=ref('quote'),rows=ref([]),excluded=ref([]),draft=ref({}),message=ref(''),action={allowed:true,query:false}
|
||||
const quoteFields=[{key:'id',ref:'purchase',label:'采购明细'},{key:'finalUnitPrice',type:'decimal',label:'新报价'},{key:'skipCorrection',type:'boolean',label:'本项暂不更正'}]
|
||||
const purchaseFields=[{key:'materialName',label:'物品名称'},{key:'quantity',label:'数量',type:'decimal'}]
|
||||
function reset(value){mode.value=value;excluded.value=[];message.value='';
|
||||
rows.value=value==='quote'?[{_rowId:'quote-1',id:7,finalUnitPrice:88,_quotePreview:[{line:1,name:'模拟水泵',quantity:2,previousPrice:60,unitPrice:88,newAmount:176,notice:'模拟匹配成功'}]},
|
||||
{_rowId:'quote-24',id:{keyword:'水冷一体管',spec:'白色带线1.5米'},finalUnitPrice:29.2,_sourceRow:24,_sourceText:'报价第24项:水冷一体管;4×29.2',_errors:['采购明细未匹配,请选择已有记录'],_quotePreview:[{line:24,name:'水冷一体管',quantity:4,previousPrice:null,unitPrice:29.2,newAmount:null,sourceText:'报价第24项:水冷一体管;4×29.2',notice:'未匹配采购记录,不会新增或修改',error:'采购明细未匹配,请选择已有记录'}]}]
|
||||
:[{_rowId:'item-1',materialName:'模拟水泵',quantity:2},{_rowId:'item-24',materialName:'模拟待补充物品',quantity:4,_sourceRow:24,_errors:['请补充单位']}]
|
||||
draft.value={id:value==='quote'?1:2,action:value==='quote'?'purchase.correctPrice':'purchase.create',label:value==='quote'?'更正采购报价':'导入采购确认',status:'WAIT_CONFIRM',ready:false,version:1,fields:value==='quote'?quoteFields:purchaseFields,results:[]}
|
||||
}
|
||||
function change(event){rows.value=assistantApplyDraftChanges(rows.value,event,{action:draft.value.action,fields:draft.value.fields,draft:draft.value});message.value='待重新校验,未执行业务'}
|
||||
function remove(ids){const result=assistantExcludeDraftRows(rows.value,ids,{draft:draft.value,action});if(result.error){message.value=result.error;return}rows.value=result.rows;excluded.value.push(...result.removed);message.value='只调整本次范围,未执行业务'}
|
||||
function restore(id){const entry=excluded.value.find(item=>item.row._rowId===id);rows.value=assistantRestoreDraftRow(rows.value,entry,{draft:draft.value,action});excluded.value=excluded.value.filter(item=>item!==entry);message.value='已恢复,需重新校验'}
|
||||
function preview(){if(mode.value==='quote')rows.value=rows.value.map(row=>row.skipCorrection?{...row,_errors:[],_quotePreview:row._quotePreview.map(q=>({...q,skipped:true,error:null}))}:row);message.value='仅模拟校验:'+rows.value.length+' 项保留,'+rows.value.filter(r=>r.skipCorrection).length+' 项明确跳过;未执行业务'}
|
||||
reset('quote');return{mode,rows,excluded,draft,message,action,change,remove,restore,preview,reset}
|
||||
},template:`<main><h2>确认单范围调整 · 隔离 UI 测试</h2><p>全部为模拟数据,不调用业务接口,不写数据库。</p><nav><button @click="reset('quote')">报价核对场景</button><button @click="reset('purchase')">导入采购场景</button></nav><Draft :draft="draft" :action="action" :rows="rows" :excluded-rows="excluded" @change="change" @remove="remove" @restore="restore"/><footer><span role="status">{{message}}</span><button @click="preview">校验预览(模拟)</button></footer></main>`}).use(createPinia()).use(ElementPlus).mount('#app')
|
||||
</script><style>body{font:14px/1.6 system-ui;background:#f5f7fb;color:#303840;margin:0}main{width:650px;max-width:calc(100vw - 32px);margin:20px auto}nav,footer{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:12px 0}button{cursor:pointer}nav>button,footer>button{padding:8px 14px;background:#fff;border:1px solid #d5dce8;border-radius:5px;color:#2873bb}footer{background:#fff;padding:12px;border:1px solid #e0e5ed}footer span{flex:1;font-size:12px}</style></html>
|
||||
37
ruoyi-ui-vue3/tests/unit/assistant-draft-exclusions.test.mjs
Normal file
37
ruoyi-ui-vue3/tests/unit/assistant-draft-exclusions.test.mjs
Normal file
@ -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)
|
||||
})
|
||||
37
ruoyi-ui-vue3/tests/unit/assistant-quotation-review.test.mjs
Normal file
37
ruoyi-ui-vue3/tests/unit/assistant-quotation-review.test.mjs
Normal file
@ -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)
|
||||
}
|
||||
})
|
||||
Loading…
Reference in New Issue
Block a user