feat(app): 优化移动端应用配置和功能实现
- 添加生产环境服务器地址配置支持内外网切换 - 实现采购列表只看我创建的功能开关 - 更新构建脚本中的默认生产环境API地址 - 优化采购单表格单元格编辑体验改用自动补全组件 - 调整应用更新检查逻辑增强生产环境兼容性 - 修复开发服务器切换时的一些验证问题 - 增强应用启动时的服务地址配置灵活性
This commit is contained in:
parent
881331fae5
commit
6b43b0104f
@ -5,9 +5,9 @@ module.exports = () => {
|
||||
return {
|
||||
name: env.variant === 'prod' ? '设备科综合管理系统' : '设备科综合管理系统·开发',
|
||||
icon: `./assets/brand/app-icon-blue-${env.variant}.png`,
|
||||
slug: 'cmvr-wms', version: '1.0.0', orientation: 'portrait', userInterfaceStyle: 'automatic',
|
||||
slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.1', orientation: 'portrait', userInterfaceStyle: 'automatic',
|
||||
platforms: ['android', 'web'],
|
||||
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 7 : 5,
|
||||
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 6,
|
||||
adaptiveIcon: { foregroundImage: `./assets/brand/app-icon-blue-${env.variant}-adaptive.png`, backgroundColor: '#ffffff' },
|
||||
permissions: ['android.permission.REQUEST_INSTALL_PACKAGES'], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
|
||||
plugins: ['./plugins/with-apk-installer.cjs', 'expo-sharing', '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 }],
|
||||
|
||||
2
mobile-app/fingerprint.config.cjs
Normal file
2
mobile-app/fingerprint.config.cjs
Normal file
@ -0,0 +1,2 @@
|
||||
// A change in the generated native downloader requires a new Android runtime.
|
||||
module.exports={extraSources:[{type:'file',filePath:'plugins/native/CmvrPackageTransfer.java',reasons:['cmvrNativePackageDownloader']}]};
|
||||
105
mobile-app/plugins/native/CmvrPackageTransfer.java
Normal file
105
mobile-app/plugins/native/CmvrPackageTransfer.java
Normal file
@ -0,0 +1,105 @@
|
||||
package __CMVR_PACKAGE__;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
/** APK bytes stay in native background threads; progress never gates network reads. */
|
||||
public final class CmvrPackageTransfer {
|
||||
public interface Progress { void update(String phase, long bytes, long total, int connections); }
|
||||
private final Set<HttpURLConnection> active = ConcurrentHashMap.newKeySet();
|
||||
private final AtomicBoolean cancelled = new AtomicBoolean();
|
||||
private final AtomicLong received = new AtomicLong();
|
||||
private long lastEvent;
|
||||
private long lastBytes;
|
||||
private String lastPhase="";
|
||||
private final Progress progress;
|
||||
private final String address, hash;
|
||||
private final Map<String,String> headers;
|
||||
private final File target;
|
||||
private final long size;
|
||||
private final int requested;
|
||||
public CmvrPackageTransfer(String address, Map<String,String> headers, File target, long size, String hash, int connections, Progress progress) {
|
||||
this.address=address;this.headers=headers;this.target=target;this.size=size;this.hash=hash;this.requested=Math.max(1,Math.min(4,connections));this.progress=progress;
|
||||
if(size<1||size>250L*1024*1024||!hash.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("安装包版本信息无效");
|
||||
}
|
||||
public void cancel() { cancelled.set(true);for(HttpURLConnection c:active)c.disconnect(); }
|
||||
private void check() throws IOException { if(cancelled.get()||Thread.currentThread().isInterrupted())throw new IOException("下载已取消"); }
|
||||
private synchronized void report(String phase,long bytes,int connections,boolean force) {
|
||||
if(!phase.equals(lastPhase)){lastPhase=phase;lastBytes=0;}bytes=Math.max(lastBytes,bytes);lastBytes=bytes;
|
||||
long now=System.nanoTime();if(force||now-lastEvent>=150_000_000L){lastEvent=now;progress.update(phase,bytes,size,connections);}
|
||||
}
|
||||
private HttpURLConnection connect(long start,long end,boolean range) throws IOException {
|
||||
check();HttpURLConnection c=(HttpURLConnection)new URL(address).openConnection();active.add(c);
|
||||
try {
|
||||
c.setInstanceFollowRedirects(false);c.setConnectTimeout(15000);c.setReadTimeout(30000);c.setUseCaches(false);
|
||||
for(Map.Entry<String,String> h:headers.entrySet())c.setRequestProperty(h.getKey(),h.getValue());
|
||||
c.setRequestProperty("Accept-Encoding","identity");if(range)c.setRequestProperty("Range","bytes="+start+"-"+end);
|
||||
int status=c.getResponseCode();check();
|
||||
if(status==401)throw new IOException("AUTH_EXPIRED");
|
||||
if(status!=200&&status!=206)throw new IOException("无法下载安装包,请重新检查更新("+status+")");
|
||||
String type=Objects.toString(c.getContentType(),"").toLowerCase(Locale.ROOT);
|
||||
if(!type.startsWith("application/vnd.android.package-archive")&&!type.startsWith("application/octet-stream"))throw new IOException("服务未返回安装包文件");
|
||||
if(!Objects.toString(c.getContentEncoding(),"identity").equalsIgnoreCase("identity"))throw new IOException("安装包传输格式不正确");
|
||||
return c;
|
||||
}catch(IOException e){close(c);throw e;}
|
||||
}
|
||||
private void close(HttpURLConnection c){active.remove(c);c.disconnect();}
|
||||
private void rangeHeaders(HttpURLConnection c,long start,long end) throws IOException {
|
||||
if(c.getResponseCode()!=206||!Objects.equals(c.getHeaderField("Content-Range"),"bytes "+start+"-"+end+"/"+size)||c.getContentLengthLong()!=end-start+1)
|
||||
throw new IOException("安装包分段响应不正确,请重新下载");
|
||||
}
|
||||
public int run() throws Exception {
|
||||
int count=1;ExecutorService pool=null;
|
||||
try {
|
||||
check();report("downloading",0,1,true);
|
||||
// Reuse the full response if the server does not support Range.
|
||||
HttpURLConnection probe=connect(0,0,requested>1&&size>=8L*1024*1024);
|
||||
try {
|
||||
if(probe.getResponseCode()==206){rangeHeaders(probe,0,0);try(InputStream in=probe.getInputStream()){if(in.read()<0||in.read()!=-1)throw new IOException("安装包分段响应不完整");}count=requested;}
|
||||
else { sequential(probe);check();return 1; }
|
||||
}finally{close(probe);}
|
||||
try(RandomAccessFile file=new RandomAccessFile(target,"rw")){file.setLength(size);}
|
||||
final int workers=count;pool=Executors.newFixedThreadPool(workers);List<Future<?>> tasks=new ArrayList<>();
|
||||
long block=(size+workers-1)/workers;
|
||||
for(int i=0;i<workers;i++){final long start=i*block,end=Math.min(size-1,start+block-1);tasks.add(pool.submit(()->{try{part(start,end,workers);}catch(Exception e){throw new CompletionException(e);}}));}
|
||||
try{for(Future<?> task:tasks)task.get();}catch(ExecutionException e){throw new IOException(message(e),e);}
|
||||
check();if(received.get()!=size||target.length()!=size)throw new IOException("安装包下载不完整,请重试");
|
||||
report("downloading",size,workers,true);MessageDigest digest=MessageDigest.getInstance("SHA-256");long checked=0;byte[] buffer=new byte[256*1024];report("verifying",0,workers,true);
|
||||
try(InputStream in=new FileInputStream(target)){for(int n;(n=in.read(buffer))!=-1;){check();digest.update(buffer,0,n);checked+=n;report("verifying",checked,workers,false);}}
|
||||
verify(digest,checked);report("verifying",size,workers,true);return count;
|
||||
}catch(Exception e){cancel();throw e;}
|
||||
finally{if(pool!=null){pool.shutdownNow();pool.awaitTermination(35,TimeUnit.SECONDS);}if(cancelled.get())target.delete();}
|
||||
}
|
||||
private static String message(Throwable e){while(e.getCause()!=null)e=e.getCause();return Objects.toString(e.getMessage(),"安装包下载失败,请重试");}
|
||||
private void sequential(HttpURLConnection c) throws Exception {
|
||||
if(c.getContentLengthLong()!=size)throw new IOException("安装包大小不匹配,请重新检查更新");
|
||||
MessageDigest digest=MessageDigest.getInstance("SHA-256");byte[] buffer=new byte[256*1024];long total=0;
|
||||
try(InputStream in=c.getInputStream();OutputStream out=new BufferedOutputStream(new FileOutputStream(target),256*1024)){
|
||||
for(int n;(n=in.read(buffer))!=-1;){check();total+=n;if(total>size)throw new IOException("安装包大小不匹配");out.write(buffer,0,n);digest.update(buffer,0,n);received.set(total);report("downloading",total,1,false);}
|
||||
}
|
||||
check();report("downloading",total,1,true);report("verifying",total,1,true);verify(digest,total);
|
||||
}
|
||||
private void verify(MessageDigest digest,long total)throws IOException {
|
||||
StringBuilder actual=new StringBuilder();for(byte b:digest.digest())actual.append(String.format(Locale.ROOT,"%02x",b));
|
||||
if(total!=size||target.length()!=size||!hash.equals(actual.toString()))throw new IOException("安装包校验失败,请重新下载");
|
||||
}
|
||||
private void part(long start,long end,int connections)throws Exception {
|
||||
long position=start;byte[] buffer=new byte[256*1024];
|
||||
for(int attempt=0;position<=end;attempt++) {
|
||||
check();HttpURLConnection c=null;
|
||||
try {
|
||||
c=connect(position,end,true);rangeHeaders(c,position,end);
|
||||
try(InputStream in=c.getInputStream();RandomAccessFile out=new RandomAccessFile(target,"rw")) {
|
||||
out.seek(position);
|
||||
while(position<=end){check();int n=in.read(buffer,0,(int)Math.min(buffer.length,end-position+1));if(n<0)throw new EOFException("安装包分段下载中断");out.write(buffer,0,n);position+=n;long done=received.addAndGet(n);report("downloading",done,connections,false);}
|
||||
if(in.read()!=-1)throw new IOException("安装包分段大小不匹配");
|
||||
}
|
||||
}catch(IOException e){if(cancelled.get()||position>end||attempt>=2||Objects.equals(e.getMessage(),"AUTH_EXPIRED"))throw e;}
|
||||
finally{if(c!=null)close(c);}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,8 @@ module.exports=config=>{
|
||||
});
|
||||
return withDangerousMod(config,['android',async cfg=>{
|
||||
const dir=path.join(cfg.modRequest.platformProjectRoot,'app/src/main/java',...pkg.split('.'));await fs.mkdir(dir,{recursive:true});
|
||||
const transfer=await fs.readFile(path.join(__dirname,'native/CmvrPackageTransfer.java'),'utf8');
|
||||
await fs.writeFile(path.join(dir,'CmvrPackageTransfer.java'),transfer.replace('package __CMVR_PACKAGE__;','package '+pkg+';'));
|
||||
await fs.writeFile(path.join(dir,'CmvrApkVerificationPackage.kt'),`package ${pkg}
|
||||
import android.content.pm.PackageInfo
|
||||
import android.content.pm.PackageManager
|
||||
@ -24,13 +26,48 @@ import com.facebook.react.bridge.*
|
||||
import com.facebook.react.uimanager.ViewManager
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.net.URI
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
class CmvrApkVerificationPackage : ReactPackage {
|
||||
override fun createNativeModules(context: ReactApplicationContext): List<NativeModule> = listOf(CmvrApkVerification(context))
|
||||
override fun createViewManagers(context: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
|
||||
}
|
||||
class CmvrApkVerification(private val context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
|
||||
private val downloads = ConcurrentHashMap<String, CmvrPackageTransfer>()
|
||||
override fun getName() = "CmvrApkVerification"
|
||||
@ReactMethod fun addListener(name: String) { }
|
||||
@ReactMethod fun removeListeners(count: Double) { }
|
||||
@ReactMethod fun cancelDownload(id: String) { downloads[id]?.cancel() }
|
||||
@ReactMethod fun download(id: String, options: ReadableMap, promise: Promise) {
|
||||
try {
|
||||
require(id.matches(Regex("[a-zA-Z0-9-]{1,100}")) && !downloads.containsKey(id))
|
||||
val hash = requireNotNull(options.getString("sha256"))
|
||||
val size = options.getDouble("size");require(size >= 1 && size <= 250L*1024*1024 && size % 1.0 == 0.0)
|
||||
val url = URI(requireNotNull(options.getString("url")))
|
||||
val host = requireNotNull(url.host);val ip = host.split('.').mapNotNull { it.toIntOrNull() }
|
||||
val internal = ip.size == 4 && ip.all { it in 0..255 } && (ip[0] == 10 || ip[0] == 192 && ip[1] == 168 || ip[0] == 172 && ip[1] in 16..31)
|
||||
require((url.scheme == "http" || url.scheme == "https") && url.userInfo == null && url.fragment == null && url.query == null)
|
||||
require(internal || host == "localhost" || host == "127.0.0.1" || url.scheme == "https" && host == "wms.svc.cmvr-iot.icu")
|
||||
require(url.path.matches(Regex("/(dev-api/|prod-api/)?system/mobile-release/" + hash + "/content")))
|
||||
val targetUri = requireNotNull(options.getString("uri"));val parsed = Uri.parse(targetUri);require(parsed.scheme == "file")
|
||||
val file = File(requireNotNull(parsed.path)).canonicalFile;val base = File(context.cacheDir,"app-updates").canonicalFile
|
||||
require(file.parentFile == base && file.name.matches(Regex("[a-f0-9]{64}-[a-z0-9-]+\\\\.apk")))
|
||||
val headers = mutableMapOf<String,String>();val source = requireNotNull(options.getMap("headers"));val keys = source.keySetIterator()
|
||||
while(keys.hasNextKey()) { val key=keys.nextKey();require(key in setOf("Authorization","X-CMVR-Dev-Server"));val value=requireNotNull(source.getString(key));require(value.length <= 8192 && !value.contains('\\r') && !value.contains('\\n'));headers[key]=value }
|
||||
require(headers["Authorization"]?.startsWith("Bearer ") == true)
|
||||
val job = CmvrPackageTransfer(url.toString(),headers,file,size.toLong(),hash,4) { phase, bytes, total, connections ->
|
||||
val event=Arguments.createMap();event.putString("id",id);event.putString("phase",phase);event.putDouble("bytes",bytes.toDouble());event.putDouble("total",total.toDouble());event.putInt("connections",connections)
|
||||
context.emitDeviceEvent("CmvrPackageProgress",event)
|
||||
}
|
||||
downloads[id]=job
|
||||
Thread({
|
||||
try { val connections=job.run();val result=Arguments.createMap();result.putString("uri",targetUri);result.putString("sha256",hash);result.putDouble("size",file.length().toDouble());result.putInt("connections",connections);promise.resolve(result) }
|
||||
catch(error: Exception) { promise.reject(if(error.message == "AUTH_EXPIRED") "AUTH_EXPIRED" else "DOWNLOAD_FAILED",error.message ?: "安装包下载失败,请重试") }
|
||||
finally { downloads.remove(id,job) }
|
||||
},"cmvr-package-download").start()
|
||||
} catch(error: Exception) { promise.reject("INVALID_DOWNLOAD","安装包下载参数无效,请重新检查更新") }
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
private fun signatures(info: PackageInfo): Set<String> {
|
||||
val signatures = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures
|
||||
|
||||
7
mobile-app/release-notes.json
Normal file
7
mobile-app/release-notes.json
Normal file
@ -0,0 +1,7 @@
|
||||
[
|
||||
"优化库存与采购卡片,重点信息直接展示,规格字号更紧凑。",
|
||||
"隐藏批次号,保留批次名称和供应商。",
|
||||
"统一版本更新入口,下载进度展示更简洁。",
|
||||
"更新说明按条目展示,方便查看本次变化。",
|
||||
"待入库增加只看我的,可按本人发起的采购和生产来源筛选。"
|
||||
]
|
||||
@ -1,5 +1,5 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { readFile,writeFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
const require=createRequire(import.meta.url);
|
||||
const cli=require.resolve('expo/bin/cli');
|
||||
@ -15,4 +15,5 @@ config.runtimeVersion=runtime;
|
||||
delete config._internal;
|
||||
await writeFile('dist/resolved-config.json',JSON.stringify(config,null,2));
|
||||
await writeFile('dist/runtime-version.txt',runtime);
|
||||
await writeFile('dist/update-notes.json',await readFile(new URL('../release-notes.json',import.meta.url),'utf8'));
|
||||
console.log(`Exported Android update for native runtime ${runtime}`);
|
||||
|
||||
@ -18,6 +18,9 @@ export async function publishUpdate({ exportDir, root, origin, environment, runt
|
||||
if (!exported?.bundle || !Array.isArray(exported.assets)) throw Error('Run Expo Android export first');
|
||||
if (expoConfig.extra?.environment !== environment) throw Error('Export environment mismatch');
|
||||
if (expoConfig.runtimeVersion !== runtimeVersion) throw Error('Export/native runtime mismatch; resolve the fingerprint before publishing');
|
||||
let releaseNotes=[];
|
||||
try{releaseNotes=JSON.parse(await readFile(path.join(exportDir,'update-notes.json'),'utf8'));}catch(error){if(error.code!=='ENOENT')throw error;}
|
||||
if(!Array.isArray(releaseNotes)||releaseNotes.length>20||releaseNotes.some(note=>typeof note!=='string'||note.length>1000))throw Error('Invalid update notes');
|
||||
const key = await readFile(keyFile);
|
||||
const certificate = new X509Certificate(await readFile(certificateFile));
|
||||
if (Date.now() < Date.parse(certificate.validFrom) || Date.now() >= Date.parse(certificate.validTo)) throw Error('Signing certificate expired/not yet valid');
|
||||
@ -38,7 +41,7 @@ export async function publishUpdate({ exportDir, root, origin, environment, runt
|
||||
const manifest = { id, createdAt: new Date().toISOString(), runtimeVersion,
|
||||
launchAsset: await asset(exported.bundle, 'js', true),
|
||||
assets: await Promise.all(exported.assets.map(a => asset(a.path, a.ext))),
|
||||
metadata: { environment }, extra: { expoClient: expoConfig } };
|
||||
metadata: { environment, releaseNotes }, extra: { expoClient: expoConfig } };
|
||||
const body = JSON.stringify(manifest);
|
||||
const signature = sign('RSA-SHA256', Buffer.from(body), keyPassphrase ? { key, passphrase: keyPassphrase } : key);
|
||||
if (!verify('RSA-SHA256', Buffer.from(body), certificate.publicKey, signature)) throw Error('Signing key does not match embedded certificate');
|
||||
|
||||
6
mobile-app/scripts/test-native-download.cjs
Normal file
6
mobile-app/scripts/test-native-download.cjs
Normal file
@ -0,0 +1,6 @@
|
||||
const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process');
|
||||
const root=path.resolve(__dirname,'../..'),out=path.join(root,'.codex-tmp/native-package-tests');fs.mkdirSync(out,{recursive:true});
|
||||
const javaHome=process.env.JAVA_HOME||'C:/Users/Administrator/.jdks/ms-17.0.19',javac=path.join(javaHome,'bin/javac.exe'),java=path.join(javaHome,'bin/java.exe');
|
||||
const source=fs.readFileSync(path.join(root,'mobile-app/plugins/native/CmvrPackageTransfer.java'),'utf8').replace('package __CMVR_PACKAGE__;','package testapp;');fs.writeFileSync(path.join(out,'CmvrPackageTransfer.java'),source);
|
||||
const compile=cp.spawnSync(javac,['--release','17','-encoding','UTF-8','-d',out,path.join(out,'CmvrPackageTransfer.java'),path.join(root,'mobile-app/tests/native/CmvrPackageTransferTest.java')],{encoding:'utf8'});if(compile.status!==0)throw Error(compile.stderr);
|
||||
const run=cp.spawnSync(java,['-Djava.net.preferIPv4Stack=true','-Djdk.net.unixdomain.tmpdir='+path.join(root,'.codex-tmp/jtmp'),'-cp',out,'testapp.CmvrPackageTransferTest'],{encoding:'utf8',timeout:120000});process.stdout.write(run.stdout||'');if(run.status!==0)throw Error(run.stderr||run.error?.message);console.log('Java sources used by Android compiled and passed socket tests');
|
||||
@ -18,6 +18,7 @@ assert.equal(verify('RSA-SHA256',Buffer.concat([bytes,Buffer.from('tampered')]),
|
||||
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');
|
||||
try{assert.deepEqual(manifest.metadata.releaseNotes,JSON.parse(await readFile(new URL('../dist/update-notes.json',import.meta.url),'utf8')));}catch(error){if(error.code!=='ENOENT')throw error;}
|
||||
assert.equal(manifest.extra.expoClient.extra.apiUrl,config.apiUrl);
|
||||
assert.equal(manifest.extra.expoClient.updates.url,origin+'/updates/dev');
|
||||
const assets=[];
|
||||
@ -46,7 +47,7 @@ try {
|
||||
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,
|
||||
runtime,updateId:manifest.id,releaseNotes:manifest.metadata.releaseNotes,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));
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import {canViewPurchaseQuotes} from './core/purchase-quote-permission';
|
||||
import {Text,ReadingContext,type ReadingSize} from './typography';
|
||||
import {usePackageUpdates,PackageUpdateDialog,PackageUpdateStatus} from './PackageUpdates';
|
||||
import {usePackageUpdates} from './PackageUpdates';
|
||||
import {VersionUpdateDialog,VersionUpdateStatus} from './VersionUpdates';
|
||||
import {LoginView} from './screens/LoginView';
|
||||
import {BusinessList} from './screens/BusinessList';
|
||||
import {FileLibrary} from './screens/FileLibrary';
|
||||
@ -14,7 +15,7 @@ import * as SecureStore from 'expo-secure-store';
|
||||
import * as Crypto from 'expo-crypto';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { ApiClient, allows, internalUrl, productionServer, PRODUCTION_PUBLIC_URL, PRODUCTION_INTERNAL_URL } from './core/network';
|
||||
import { AppUpdateDialog, useAppUpdates, type AppUpdateControls } from './AppUpdates';
|
||||
import { useAppUpdates, type AppUpdateControls } from './AppUpdates';
|
||||
import { modules, display, recordDisplay, routeComponents, validDate, type Module, type Row, localDate } from './core/modules';
|
||||
import { AppearanceContext, Button, Card, Choice, Field, Heading, Icon, Note, s, useTheme, type Appearance, type IconName } from './ui';
|
||||
import { Assistant } from './screens/Assistant';
|
||||
@ -117,11 +118,11 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
|
||||
{selected?.key==='files'?<FileLibrary api={api} scope={scope} permissions={user.permissions}/>:!!selected&&<BusinessList key={page} api={api} scope={scope} module={selected} permissions={user.permissions} canViewQuotes={canViewPurchaseQuotes(user.user.userId,user.roles)} initialQuery={entry?.query} onNavigate={open}/>}
|
||||
{(page==='profile'||page==='password')&&<Account key={page} api={api} kind={page} policy={String(user.pwdChrtype||'0')} bindLeave={bindLeave} onSaved={profile=>setUser(old=>old?{...old,user:{...old.user,...profile}}:null)}/>}
|
||||
{(page==='feedback'||page==='feedback-list')&&<Feedback key={page} api={api} mode={page==='feedback'?'create':'list'} bindLeave={bindLeave} open={open}/>}
|
||||
{(page==='settings'||page==='about')&&<Settings updates={updates} environment={variant} baseUrl={server} connection={connection} packageUpdate={<PackageUpdateStatus control={packageUpdates}/>} logout={logout} about={page==='about'}/>}
|
||||
{(page==='settings'||page==='about')&&<Settings environment={variant} baseUrl={server} connection={connection} versionUpdate={<VersionUpdateStatus updates={updates} packages={packageUpdates}/>} logout={logout} about={page==='about'}/>}
|
||||
</View>
|
||||
{!page&&!keyboard&&<View accessibilityRole="tablist" style={{flexDirection:'row',backgroundColor:t.card,borderTopWidth:1,borderColor:t.line,paddingTop:6,paddingBottom:5}}>{tabs.map(([key,label,icon])=><Pressable key={key} accessibilityRole="tab" accessibilityLabel={label} accessibilityState={{selected:tab===key}} onPress={()=>go(key)} style={{flex:1,alignItems:'center',justifyContent:'center',minHeight:50,gap:3}}><View style={{paddingHorizontal:17,paddingVertical:4,borderRadius:18,backgroundColor:tab===key?t.soft:'transparent'}}><Icon name={icon} size={21} color={tab===key?t.accent:t.muted}/></View><Text style={{fontSize:12,lineHeight:18,color:tab===key?t.accent:t.muted,fontWeight:tab===key?'700':'400'}}>{label}</Text></Pressable>)}</View>}
|
||||
</>}
|
||||
<PackageUpdateDialog control={packageUpdates}/>{!packageUpdates.visible&&<AppUpdateDialog {...updates}/>}
|
||||
<VersionUpdateDialog updates={updates} packages={packageUpdates} enabled={!!user}/>
|
||||
</SafeAreaView>;
|
||||
}
|
||||
function ProductionConnection({address,onSave}:{address:string;onSave:(value:string)=>Promise<void>}){
|
||||
|
||||
@ -1,15 +1,15 @@
|
||||
import {Text} from './typography';
|
||||
import React from 'react';
|
||||
import {Modal,ScrollView,View} from 'react-native';
|
||||
import {Button,Icon,Note,useTheme} from './ui';
|
||||
import {Button,Note,useTheme} from './ui';
|
||||
import type {UpdateView} from './core/updates';
|
||||
import {UpdateNotes} from './UpdateNotes';
|
||||
|
||||
export function AppUpdateDialog({view,later,restart}:{view:UpdateView;later:()=>void;restart:()=>void}){
|
||||
const t=useTheme();if(!view.visible)return null;
|
||||
return <Modal transparent visible animationType="fade" onRequestClose={later}><View style={{flex:1,backgroundColor:'rgba(10,20,35,.5)',justifyContent:'center',alignItems:'center',padding:24}}><View accessibilityViewIsModal accessibilityRole="alert" style={{width:'100%',maxWidth:380,maxHeight:'85%',borderRadius:20,backgroundColor:t.card,padding:22,gap:18}}>
|
||||
<ScrollView contentContainerStyle={{gap:14}}><View style={{width:52,height:52,borderRadius:16,backgroundColor:t.soft,justifyContent:'center',alignItems:'center'}}><Icon name="cloud-download-outline" size={29}/></View>
|
||||
<Text style={{fontSize:21,lineHeight:30,fontWeight:'700',color:t.text}}>发现新版本</Text><Note>更新已下载完成,重启 App 后即可使用。</Note>
|
||||
<View style={{backgroundColor:t.soft,padding:12,borderRadius:10}}><Note>请先保存正在填写的内容,并等待当前操作完成。重启后,未提交的内容不会保留。</Note></View>
|
||||
return <Modal transparent visible animationType="fade" onRequestClose={later}><View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',alignItems:'center',padding:24}}><View accessibilityViewIsModal accessibilityRole="alert" style={{width:'100%',maxWidth:380,maxHeight:'85%',borderRadius:20,backgroundColor:t.card,padding:22,gap:16}}>
|
||||
<ScrollView contentContainerStyle={{gap:12}}>
|
||||
<Text style={{fontSize:18,lineHeight:25,fontWeight:'700',color:t.text}}>发现新版本</Text><UpdateNotes notes={view.notes}/><Note>更新已下载,重启后生效。请先保存当前内容,未提交的内容不会保留。</Note>
|
||||
{!!view.error&&<Text accessibilityRole="alert" style={{color:'#c64650',fontSize:14,lineHeight:21}}>{view.error}</Text>}
|
||||
</ScrollView>
|
||||
<View style={{gap:9}}><Button title={view.restarting?'正在重启…':'重启并更新'} busy={view.restarting} onPress={restart}/><Button title="稍后再说" secondary disabled={view.restarting} onPress={later}/></View>
|
||||
|
||||
@ -13,7 +13,7 @@ export function useAppUpdates(){
|
||||
void current.check();const listener=AppState.addEventListener('change',state=>current.foreground(state==='active'));
|
||||
return()=>{listener.remove();current.dispose();if(controller.current===current)controller.current=null;};
|
||||
},[enabled]);
|
||||
const check=useCallback(()=>{void controller.current?.check(true);},[]);
|
||||
const check=useCallback(()=>controller.current?.check(true)??Promise.resolve(),[]);
|
||||
const later=useCallback(()=>controller.current?.later(),[]);
|
||||
const restart=useCallback(()=>{void controller.current?.restart();},[]);
|
||||
return {view,text:updateMessages[view.state],enabled,check,later,restart};
|
||||
|
||||
@ -1,32 +1,120 @@
|
||||
import React,{useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {AppState,Modal,NativeModules,Platform,ScrollView,View} from 'react-native';
|
||||
import {ActivityIndicator,AppState,DeviceEventEmitter,Modal,NativeModules,Platform,ScrollView,View} from 'react-native';
|
||||
import Constants from 'expo-constants';
|
||||
import * as Application from 'expo-application';
|
||||
import {Directory,File,FileMode,Paths} from 'expo-file-system';
|
||||
import {fetch as expoFetch} from 'expo/fetch';
|
||||
import type {ApiClient} from './core/network';
|
||||
import {newerPackage,packageVerifier,processPackageChunk,verifyInstalledPackage,type PackageRelease} from './core/package-update';
|
||||
import {Button,Card,Heading,Icon,Note,s,useTheme} from './ui';
|
||||
import {newerPackage,packageVerifier,createPackageDownloadProcessor,verifyInstalledPackage,type PackageRelease} from './core/package-update';
|
||||
import {nativePackageDownload,downloadMeter} from './core/native-package-download';
|
||||
import {readPreference,savePreference} from './core/preferences';
|
||||
import {ignoredPackageMatches} from './core/package-cache';
|
||||
import {rememberPackage,restorePackage,validatePackageFile} from './package-cache';
|
||||
import {Button,Heading,Note,useTheme} from './ui';
|
||||
import {Text} from './typography';
|
||||
import {UpdateNotes} from './UpdateNotes';
|
||||
export type PackageCheckResult={release:PackageRelease|null;error:string};
|
||||
export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
|
||||
const [release,setRelease]=useState<PackageRelease|null>(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'downloading'|'verifying'|'installing'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState('');
|
||||
const [release,setRelease]=useState<PackageRelease|null>(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'restoring'|'downloading'|'verifying'|'installing'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState(''),[ignored,setIgnored]=useState(false);
|
||||
const [transfer,setTransfer]=useState({bytes:0,total:0,bytesPerSecond:0,remainingSeconds:null as number|null,connections:1}),[verifyProgress,setVerifyProgress]=useState(0);
|
||||
const [checked,setChecked]=useState(false);
|
||||
const file=useRef<File|null>(null),fileHash=useRef(''),ctl=useRef<AbortController|null>(null),generation=useRef(0),busy=useRef(false),last=useRef(0),shown=useRef('');
|
||||
// Read the installed native build, never the OTA manifest's version.
|
||||
const current=Number(Application.nativeBuildVersion),environment=String(Constants.expoConfig?.extra?.environment||'dev');
|
||||
const available=enabled&&Platform.OS==='android'&&Number.isInteger(current)&¤t>0;
|
||||
const check=useCallback(async(force=false)=>{if(!available||busy.current||!force&&Date.now()-last.current<15*60*1000)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;last.current=Date.now();const checkCtl=new AbortController();ctl.current=checkCtl;setPhase('checking');if(force)setError('');try{const data=await api.request<any>('/system/mobile-release',{signal:checkCtl.signal});const next=newerPackage(data.data,current,environment);if(!valid()||checkCtl.signal.aborted)return;if(fileHash.current!==next?.sha256){file.current=null;fileHash.current='';}setRelease(next);if(next&&(force||shown.current!==next.sha256)){setVisible(true);shown.current=next.sha256;}if(!next&&force)setError('安装包已是当前版本');}catch(e){if(valid()&&!checkCtl.signal.aborted){last.current=Date.now()-14*60*1000;if(force)setError((e as Error).message);}}finally{if(valid()){busy.current=false;setPhase(file.current?'ready':'idle');}}},[api,available,current,environment]);
|
||||
useEffect(()=>{generation.current++;busy.current=false;shown.current='';last.current=0;file.current=null;fileHash.current='';setRelease(null);setVisible(false);setPhase('idle');setError('');void check();const listener=AppState.addEventListener('change',state=>{if(state==='active')void check();});return()=>{generation.current++;ctl.current?.abort();listener.remove();};},[scope,check]);
|
||||
async function download(){if(!release||busy.current)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);const abort=new AbortController();ctl.current=abort;let output:File|null=null;
|
||||
try{const dir=new Directory(Paths.cache,'app-updates');dir.create({idempotent:true,intermediates:true});output=new File(dir,release.sha256+'-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.apk');output.create();const handle=output.open(FileMode.WriteOnly),verify=packageVerifier(release);
|
||||
let processed=0;try{await api.download(release.downloadPath,async bytes=>{await processPackageChunk(bytes,chunk=>{verify.write(chunk);handle.writeBytes(chunk);},length=>{processed+=length;if(valid())setProgress(Math.min(99,Math.floor(processed/release.size*100)));},abort.signal);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch});if(valid())setPhase('verifying');await new Promise<void>(resolve=>setTimeout(resolve,0));if(abort.signal.aborted||!valid())throw new Error('下载已取消');verify.finish();}finally{handle.close();}
|
||||
const check=useCallback(async(force=false):Promise<PackageCheckResult|undefined>=>{
|
||||
if(!available||busy.current||!force&&Date.now()-last.current<15*60*1000)return;
|
||||
const run=generation.current,valid=()=>generation.current===run;busy.current=true;last.current=Date.now();const checkCtl=new AbortController();ctl.current=checkCtl;setPhase('checking');if(force)setError('');
|
||||
try{
|
||||
const [data,ignore]=await Promise.all([api.request<any>('/system/mobile-release',{signal:checkCtl.signal}),readPreference(scope,'ignored-package').catch(()=>null)]);
|
||||
const next=newerPackage(data.data,current,environment);if(!valid()||checkCtl.signal.aborted)return;
|
||||
if(fileHash.current!==next?.sha256||!file.current?.exists){file.current=null;fileHash.current='';}
|
||||
setRelease(next);const skip=!!next&&ignoredPackageMatches(ignore,next);setIgnored(skip);
|
||||
const show=next&&(force||!skip&&shown.current!==next.sha256);
|
||||
if(next&&show&&!file.current){
|
||||
const reveal=setTimeout(()=>{if(valid()&&!checkCtl.signal.aborted){setPhase('restoring');setVisible(true);}},250);
|
||||
try{
|
||||
const cached=await restorePackage(scope,next,checkCtl.signal,()=>{});
|
||||
if(!valid()||checkCtl.signal.aborted)return;
|
||||
if(cached){file.current=cached;fileHash.current=next.sha256;setProgress(100);}
|
||||
}finally{clearTimeout(reveal);}
|
||||
}
|
||||
if(show){setVisible(true);shown.current=next.sha256;}
|
||||
return{release:next,error:''};
|
||||
}catch(e){if(valid()&&!checkCtl.signal.aborted){last.current=Date.now()-14*60*1000;if(force)setError((e as Error).message);return{release:null,error:(e as Error).message};}}
|
||||
finally{if(valid()){busy.current=false;setChecked(true);setPhase(file.current?'ready':'idle');}}
|
||||
},[api,available,current,environment,scope]);
|
||||
useEffect(()=>{generation.current++;busy.current=false;shown.current='';last.current=0;file.current=null;fileHash.current='';setRelease(null);setVisible(false);setPhase('idle');setError('');setIgnored(false);setChecked(false);void check();const listener=AppState.addEventListener('change',state=>{if(state==='active')void check();});return()=>{generation.current++;ctl.current?.abort();listener.remove();};},[scope,check]);
|
||||
async function download(){if(!release||busy.current)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);setVerifyProgress(0);setTransfer({bytes:0,total:release.size,bytesPerSecond:0,remainingSeconds:null,connections:1});const meter=downloadMeter(),abort=new AbortController();ctl.current=abort;let output:File|null=null;
|
||||
try{const dir=new Directory(Paths.cache,'app-updates');dir.create({idempotent:true,intermediates:true});output=new File(dir,release.sha256+'-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.apk');output.create();
|
||||
const bridge=NativeModules.CmvrApkVerification;
|
||||
if(typeof bridge?.download==='function'&&typeof bridge?.cancelDownload==='function'){
|
||||
await api.nativePackageDownload(release.downloadPath,(url,headers,signal)=>nativePackageDownload(bridge,DeviceEventEmitter,release,output!.uri,url,headers,signal,event=>{
|
||||
if(!valid())return;
|
||||
if(event.phase==='verifying'){setPhase('verifying');setVerifyProgress(Math.floor(event.bytes/release.size*100));}
|
||||
else {setProgress(Math.min(100,Math.floor(event.bytes/release.size*100)));setTransfer({...meter(event.bytes,release.size),connections:event.connections});}
|
||||
}),abort.signal);
|
||||
}else{
|
||||
const handle=output.open(FileMode.WriteOnly),verify=packageVerifier(release);
|
||||
let lastPercent=0;const processor=createPackageDownloadProcessor(chunk=>{verify.write(chunk);handle.writeBytes(chunk);},processed=>{const next=Math.min(99,Math.floor(processed/release.size*100));if(valid()){setTransfer({...meter(processed,release.size),connections:1});if(next!==lastPercent){lastPercent=next;setProgress(next);}}},abort.signal);
|
||||
try{await api.download(release.downloadPath,bytes=>processor.push(bytes),{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch});await processor.finish();if(valid())setPhase('verifying');await new Promise<void>(resolve=>setTimeout(resolve,0));if(abort.signal.aborted||!valid())throw new Error('下载已取消');verify.finish();}finally{handle.close();}
|
||||
}
|
||||
if(abort.signal.aborted||!valid())throw new Error('下载已取消');
|
||||
await rememberPackage(scope,release,output).catch(()=>{});
|
||||
if(abort.signal.aborted||!valid())throw new Error('下载已取消');file.current=output;fileHash.current=release.sha256;setPhase('ready');setProgress(100);
|
||||
}catch(e){try{if(output?.exists)output.delete();}catch{}if(valid()){file.current=null;fileHash.current='';setPhase('idle');setError(abort.signal.aborted?'下载已取消,可重新下载':(e as Error).message);}}
|
||||
finally{if(valid())busy.current=false;}
|
||||
}
|
||||
async function install(){if(!file.current||!release||busy.current)return;busy.current=true;setError('');setPhase('installing');await new Promise<void>(resolve=>setTimeout(resolve,0));try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;setPhase('ready');return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;setPhase('ready');}}
|
||||
function later(){if(phase==='downloading'||phase==='verifying')ctl.current?.abort();setVisible(false);}
|
||||
return {release,visible,phase,progress,error,available,check:()=>void check(true),download:()=>void download(),install:()=>void install(),later};
|
||||
async function install(){
|
||||
if(!file.current||!release||busy.current)return;
|
||||
const run=generation.current,valid=()=>generation.current===run,abort=new AbortController();ctl.current=abort;
|
||||
busy.current=true;setError('');setPhase('installing');await new Promise<void>(resolve=>setTimeout(resolve,0));
|
||||
try{
|
||||
if(!await validatePackageFile(scope,release,file.current,abort.signal)){
|
||||
if(valid()){file.current=null;fileHash.current='';setError('本地安装包已被清理或发生变化,请重新下载。');setPhase('idle');}
|
||||
return;
|
||||
}
|
||||
if(!valid()||abort.signal.aborted)return;
|
||||
await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);
|
||||
if(!valid()||abort.signal.aborted)return;
|
||||
try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}
|
||||
catch{if(valid())setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}
|
||||
}catch{if(valid()&&!abort.signal.aborted)setError('安装包的包名、签名或版本不匹配,请联系管理员。');}
|
||||
finally{if(valid()){busy.current=false;if(file.current)setPhase('ready');}}
|
||||
}
|
||||
function later(){if(['downloading','verifying','restoring'].includes(phase))ctl.current?.abort();setVisible(false);}
|
||||
async function ignoreVersion(){
|
||||
if(!release||busy.current)return;const run=generation.current;busy.current=true;
|
||||
try{await savePreference(scope,'ignored-package',{versionCode:release.versionCode,sha256:release.sha256,environment:release.environment});if(generation.current===run){setIgnored(true);setVisible(false);}}
|
||||
catch{if(generation.current===run)setError('未能保存忽略设置,请重试');}
|
||||
finally{if(generation.current===run)busy.current=false;}
|
||||
}
|
||||
return {release,visible,phase,progress,transfer,verifyProgress,error,available,ignored,checked,check:()=>check(true),download:()=>void download(),install:()=>void install(),ignoreVersion:()=>void ignoreVersion(),later};
|
||||
}
|
||||
export type PackageControls=ReturnType<typeof usePackageUpdates>;
|
||||
export function PackageUpdateStatus({control:c}:{control:PackageControls}){return c.available?<Card><Heading>安装包更新</Heading><Note>{c.release?`新安装包 ${c.release.versionName}(${c.release.versionCode})`:'检查需要重新安装的新版本'}{c.phase==='downloading'?` · ${c.progress}%`:''}</Note>{!!c.error&&<Note>{c.error}</Note>}<Button title="检查安装包更新" secondary busy={c.phase==='checking'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.check}/></Card>:null;}
|
||||
export function PackageUpdateDialog({control:c}:{control:PackageControls}){const t=useTheme();if(!c.visible||!c.release)return null;return <Modal transparent visible animationType="fade" onRequestClose={c.later}><View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:380,alignSelf:'center',maxHeight:'85%',backgroundColor:t.card,borderRadius:20,padding:22,gap:16}}><ScrollView contentContainerStyle={{gap:12}}><Icon name="cloud-download-outline" size={30}/><Heading>发现新版安装包</Heading><Note>版本 {c.release.versionName}({c.release.versionCode}) · {(c.release.size/1024**2).toFixed(1)} MB</Note>{!!c.release.notes&&<Text style={{color:t.text,fontSize:14,lineHeight:22}}>{c.release.notes}</Text>}<Note>请先保存当前内容。下载完成后由手机系统确认安装;首次安装可能需要允许本应用安装未知应用。</Note>{c.phase==='downloading'&&<><View style={{height:6,backgroundColor:t.soft,borderRadius:3,overflow:'hidden'}}><View style={{height:6,width:`${c.progress}%`,backgroundColor:t.accent}}/></View><Note>{c.progress===0?'正在连接并接收安装包…':`已接收并处理 ${c.progress}%`}</Note></>}{c.phase==='verifying'&&<Note>正在完成文件完整性校验…</Note>}{c.phase==='installing'&&<Note>正在验证安装包,请稍候…</Note>}{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}</ScrollView><Button title={c.phase==='ready'?'安装新版':c.phase==='downloading'?'正在下载…':c.phase==='verifying'?'正在校验…':c.phase==='installing'?'正在验证…':'下载新版'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.phase==='ready'?c.install:c.download}/><Button title={['downloading','verifying'].includes(c.phase)?'取消下载':'稍后再说'} secondary onPress={c.later}/></View></View></Modal>;}
|
||||
function PackageTransferProgress({control:c}:{control:PackageControls}){
|
||||
const t=useTheme(),verifying=c.phase==='verifying',percent=Math.max(0,Math.min(100,verifying?c.verifyProgress:c.progress));
|
||||
return <View style={{gap:9,paddingVertical:4}}>
|
||||
<View style={{flexDirection:'row',justifyContent:'space-between',gap:8}}><Text style={{fontSize:13,color:t.muted,flexShrink:1}}>{verifying?'正在校验':'正在下载'}</Text><Text style={{fontSize:13,fontWeight:'600',color:t.accent}}>{percent}%</Text></View>
|
||||
<View accessibilityRole="progressbar" accessibilityValue={{min:0,max:100,now:percent}} aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent} style={{height:7,backgroundColor:t.line,borderRadius:4,overflow:'hidden'}}><View style={{height:7,width:`${percent}%`,backgroundColor:t.accent}}/></View>
|
||||
</View>;
|
||||
}
|
||||
export function PackageUpdateDialog({control:c}:{control:PackageControls}){
|
||||
const t=useTheme();if(!c.visible||!c.release)return null;
|
||||
const busy=['checking','restoring','downloading','verifying','installing'].includes(c.phase);
|
||||
const current=Application.nativeApplicationVersion||Constants.expoConfig?.version,version=current&¤t!==c.release.versionName?`${current} → ${c.release.versionName}`:`版本 ${c.release.versionName}`;
|
||||
return <Modal transparent visible animationType="fade" onRequestClose={c.later}>
|
||||
<View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:380,alignSelf:'center',maxHeight:'85%',backgroundColor:t.card,borderRadius:20,padding:22,gap:16}}>
|
||||
<ScrollView contentContainerStyle={{gap:12}}><Heading>发现新版本</Heading><Note>{version}</Note>
|
||||
<UpdateNotes notes={c.release.notes}/>
|
||||
{['downloading','verifying'].includes(c.phase)&&<PackageTransferProgress control={c}/>}
|
||||
{c.phase==='restoring'&&<View style={{flexDirection:'row',alignItems:'center',gap:10}}><ActivityIndicator color={t.accent}/><Note>正在核对本地安装包…</Note></View>}
|
||||
{c.phase==='ready'&&<Note>下载完成,可直接安装。</Note>}
|
||||
{c.phase==='installing'&&<Note>正在验证安装包,请稍候…</Note>}
|
||||
{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}
|
||||
</ScrollView>
|
||||
{!busy&&<Button title={c.phase==='ready'?'立即安装':'立即更新'} onPress={c.phase==='ready'?c.install:c.download}/>}
|
||||
<View style={{flexDirection:'row',gap:10}}><Button style={{flex:1,paddingHorizontal:8}} title={['downloading','verifying'].includes(c.phase)?'取消下载':'稍后再说'} secondary onPress={c.later}/>{!busy&&<Button style={{flex:1,paddingHorizontal:8}} title="忽略此版本" secondary onPress={c.ignoreVersion}/>}</View>
|
||||
</View></View>
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
9
mobile-app/src/UpdateNotes.tsx
Normal file
9
mobile-app/src/UpdateNotes.tsx
Normal file
@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import {View} from 'react-native';
|
||||
import {Text} from './typography';
|
||||
import {useTheme} from './ui';
|
||||
import {updateNotes} from './core/update-notes';
|
||||
export function UpdateNotes({notes}:{notes:unknown}){
|
||||
const t=useTheme(),items=updateNotes(notes);if(!items.length)return null;
|
||||
return <View style={{gap:8}}><Text style={{fontSize:13,lineHeight:20,fontWeight:'600',color:t.text}}>本次更新</Text>{items.map((text,index)=><View key={index} style={{flexDirection:'row',alignItems:'flex-start',gap:9}}><View accessibilityElementsHidden importantForAccessibility="no-hide-descendants" style={{width:4,height:4,borderRadius:2,backgroundColor:t.muted,marginTop:9,flexShrink:0}}/><Text style={{fontSize:13,lineHeight:21,color:t.text,flex:1,minWidth:0}}>{text}</Text></View>)}</View>;
|
||||
}
|
||||
21
mobile-app/src/VersionUpdates.tsx
Normal file
21
mobile-app/src/VersionUpdates.tsx
Normal file
@ -0,0 +1,21 @@
|
||||
import React,{useRef,useState} from 'react';
|
||||
import * as Application from 'expo-application';
|
||||
import Constants from 'expo-constants';
|
||||
import {Button,Card,Heading,Note} from './ui';
|
||||
import {AppUpdateDialog,type AppUpdateControls} from './AppUpdates';
|
||||
import {PackageUpdateDialog,type PackageControls} from './PackageUpdates';
|
||||
import {checkVersionUpdate} from './core/version-update';
|
||||
|
||||
export function VersionUpdateStatus({updates,packages}:{updates:AppUpdateControls;packages:PackageControls}){
|
||||
const [checking,setChecking]=useState(false),[error,setError]=useState(''),lock=useRef(false);
|
||||
const busy=checking||['checking','restoring','downloading','verifying','installing'].includes(packages.phase)||['checking','downloading'].includes(updates.view.state);
|
||||
const current=Application.nativeApplicationVersion||Constants.expoConfig?.version||'—';
|
||||
const text=packages.release?packages.phase==='ready'?'新版已下载,待安装':`发现新版本 ${packages.release.versionName}${packages.ignored?' · 已忽略':''}`:updates.view.state==='disabled'?'':updates.text;
|
||||
async function check(){if(lock.current||busy)return;lock.current=true;setChecking(true);setError('');try{const result=await checkVersionUpdate(packages,updates);setError(result.error);}catch(e){setError((e as Error).message||'检查失败,请稍后重试');}finally{lock.current=false;setChecking(false);}}
|
||||
return <Card><Heading>版本更新</Heading><Note>当前版本 {current}</Note>{!!text&&<Note>{text}</Note>}{!!error&&<Note>{error}</Note>}{(packages.available||updates.enabled)&&<Button title="检查更新" secondary busy={busy} onPress={()=>void check()}/>}</Card>;
|
||||
}
|
||||
export function VersionUpdateDialog({updates,packages,enabled}:{updates:AppUpdateControls;packages:PackageControls;enabled:boolean}){
|
||||
if(!enabled||packages.available&&!packages.checked)return null;
|
||||
if(packages.visible)return <PackageUpdateDialog control={{...packages,later:()=>{updates.later();packages.later();},ignoreVersion:()=>{updates.later();packages.ignoreVersion();}}}/>;
|
||||
return <AppUpdateDialog {...updates}/>;
|
||||
}
|
||||
@ -5,23 +5,20 @@ export type Module = { key: string; title: string; path: string; permissions: st
|
||||
export const modules: Module[] = [
|
||||
{key:'files',title:'共享文件',path:'/system/files',permissions:[['system:file:list','system:file:manage']],search:'keyword',titleKey:'name',fields:[]},
|
||||
{ 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:'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','规格型号']] },
|
||||
{ key: 'stock', title: '库存查询', path: '/warehouse/stock/list', permissions: [['warehouse:stock:list']], search: 'productName', titleKey: 'productName',
|
||||
guide: '这里用于查询;现场领用、移库、盘点请从对应入口办理。可直接办理领用、移库或跨项目借用。',
|
||||
guide: '这里用于查询;现场领用、移库、盘点请从对应入口办理。可直接办理领用、移库。',
|
||||
fields: [['projectName','所属项目'],['areaName','库区'],['stockNum','库存数量'],['unit','单位'],['spec','规格型号'],['brand','品牌'],['averageUnitCost','平均单价'],['stockAmount','库存金额']] },
|
||||
{ key: 'purchase', title: '采购明细', path: '/warehouse/purchase/list', permissions: [['warehouse:purchase:list','warehouse:purchase:manage']], search: 'materialName', titleKey: 'materialName',
|
||||
guide: '一批采购对应一个项目;确认采购后再登记到货,验收合格后到「待入库」办理入库。',
|
||||
fields: [['purchaseStatus','采购状态'],['projectName','所属项目'],['purchaseBatchNo','采购批次'],['materialParams','规格型号'],['materialBrand','品牌'],['quantity','采购数量'],['unit','单位'],['finalUnitPrice','报价'],['actualUnitPrice','实际单价(内部参考)'],['actualAmount','实际金额(内部参考)'],['acceptedQuantity','已验收数量'],['remainingQuantity','未到数量']] },
|
||||
fields: [['purchaseStatus','采购状态'],['materialParams','规格型号'],['materialBrand','品牌'],['purchaseBatchName','批次名称'],['supplierName','供应商'],['quantity','采购数量'],['unit','单位'],['projectName','所属项目'],['purchaseBatchNo','批次编号'],['finalUnitPrice','报价'],['actualUnitPrice','实际单价(内部参考)'],['actualAmount','实际金额(内部参考)'],['acceptedQuantity','已验收数量'],['remainingQuantity','未到数量']] },
|
||||
{ key: 'pending', title: '待入库', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 0 },
|
||||
guide: '采购验收合格或生产完工验收后,记录才会进入待入库;选择实际存放库区并确认后,才计入库存。',
|
||||
fields: [['sourceProjectName','来源项目'],['purchaseBatchNo','采购批次'],['spec','规格型号'],['inNum','应入库数量'],['receivedQuantity','已入库数量'],['unit','单位'],['sourceNo','来源单号']] },
|
||||
{ key: 'in', title: '入库记录', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 1 },
|
||||
fields: [['sourceProjectName','所属项目'],['areaName','库区'],['inNum','入库数量'],['unit','单位'],['businessDate','业务日期'],['inNo','入库单号']] },
|
||||
{ key: 'loans', title: '借用与归还', path: '/project/loans', permissions: [['project:project:list','warehouse:stock:list','warehouse:purchase:list','warehouse:purchase:manage']], search: '', titleKey: 'itemName',
|
||||
guide: '查看借还记录;从库存发起借用,可按实际数量部分归还或按多个库区全部归还。借用不等于领用。',
|
||||
fields: [['lenderProjectName','借出项目'],['borrowerProjectName','借入项目'],['quantity','借用数量'],['returnedQuantity','已还数量'],['outstandingQuantity','未还数量'],['unit','单位'],['loanNo','借用编号']] },
|
||||
{ key: 'check', title: '库存盘点', path: '/warehouse/check/list', permissions: [['warehouse:check:list']], search: 'productName', titleKey: 'productName',
|
||||
guide: '从「现场盘点」登记实际清点数量,不是差异数量;这里核对盘点记录,确认后才调整库存。',
|
||||
fields: [['projectName','所属项目'],['areaName','库区'],['bookNum','账面数量'],['realNum','实际数量'],['diffNum','差异数量'],['checkNo','盘点单号'],['businessDate','业务日期']] },
|
||||
|
||||
32
mobile-app/src/core/native-package-download.ts
Normal file
32
mobile-app/src/core/native-package-download.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import type {PackageRelease} from './package-update';
|
||||
export type PackageProgress={id:string;phase:'downloading'|'verifying';bytes:number;total:number;connections:number};
|
||||
export type NativePackageBridge={download:(id:string,options:Record<string,unknown>)=>Promise<{uri:string;sha256:string;size:number;connections:number}>;cancelDownload:(id:string)=>void};
|
||||
type Events={addListener:(name:string,callback:(event:PackageProgress)=>void)=>{remove:()=>void}};
|
||||
export async function nativePackageDownload(bridge:NativePackageBridge,events:Events,release:PackageRelease,uri:string,url:string,headers:Record<string,string>,signal:AbortSignal,onProgress:(event:PackageProgress)=>void){
|
||||
const id=Date.now().toString(36)+'-'+Math.random().toString(36).slice(2),cancel=()=>bridge.cancelDownload(id);
|
||||
const subscription=events.addListener('CmvrPackageProgress',event=>{
|
||||
if(signal.aborted||event.id!==id||event.total!==release.size||!Number.isSafeInteger(event.bytes)||event.bytes<0||event.bytes>release.size||!['downloading','verifying'].includes(event.phase))return;
|
||||
onProgress({...event,connections:Math.max(1,Math.min(4,Number(event.connections)||1))});
|
||||
});
|
||||
signal.addEventListener('abort',cancel,{once:true});
|
||||
try {
|
||||
if(signal.aborted)throw new Error('下载已取消');
|
||||
const pending=bridge.download(id,{uri,url,headers,size:release.size,sha256:release.sha256});
|
||||
// Cancellation can race with registration of the native job.
|
||||
if(signal.aborted)cancel();
|
||||
const result=await pending;
|
||||
if(signal.aborted)throw new Error('下载已取消');
|
||||
if(result.uri!==uri||result.sha256!==release.sha256||result.size!==release.size)throw new Error('安装包校验失败,请重新下载');
|
||||
return result;
|
||||
}finally{subscription.remove();signal.removeEventListener('abort',cancel);}
|
||||
}
|
||||
/** Actual received bytes over a short window, independent of the progress percentage. */
|
||||
export function downloadMeter(now:()=>number=()=>Date.now()) {
|
||||
let samples:{time:number;bytes:number}[]=[];
|
||||
return (bytes:number,total:number)=>{
|
||||
const time=now();if(samples.length&&bytes<samples.at(-1)!.bytes)samples=[];
|
||||
samples.push({time,bytes});while(samples.length>2&&samples[1].time<time-2500)samples.shift();
|
||||
const first=samples[0],elapsed=time-first.time,rate=elapsed>0?Math.max(0,(bytes-first.bytes)*1000/elapsed):0;
|
||||
return {bytes,total,bytesPerSecond:rate,remainingSeconds:rate>0?Math.max(0,Math.ceil((total-bytes)/rate)):null};
|
||||
};
|
||||
}
|
||||
@ -30,6 +30,7 @@ export class ApiError extends Error {
|
||||
export class ApiClient {
|
||||
private token = '';
|
||||
private generation = 0;
|
||||
private nativeDownloads = new Set<AbortController>();
|
||||
readonly baseUrl: string;
|
||||
private expired: () => void;
|
||||
private transport: typeof fetch;
|
||||
@ -38,10 +39,22 @@ export class ApiClient {
|
||||
this.baseUrl = baseUrl; this.expired = expired; this.transport = transport;
|
||||
this.devPreviewServer=devPreviewServer?internalUrl(devPreviewServer,true):undefined;
|
||||
}
|
||||
authenticate(token: string) { this.generation++; this.token = token; }
|
||||
clear() { this.generation++; this.token = ''; }
|
||||
authenticate(token: string) { this.generation++; this.token = token;for(const job of this.nativeDownloads)job.abort(); }
|
||||
clear() { this.generation++; this.token = '';for(const job of this.nativeDownloads)job.abort(); }
|
||||
captureSession() { return this.generation; }
|
||||
isSessionCurrent(value: number) { return value === this.generation; }
|
||||
async nativePackageDownload<T>(path:string,transfer:(url:string,headers:Record<string,string>,signal:AbortSignal)=>Promise<T>,signal:AbortSignal):Promise<T> {
|
||||
if(!/^\/system\/mobile-release\/[a-f0-9]{64}\/content$/.test(path))throw new ApiError('下载地址无效',400);
|
||||
const epoch=this.generation,ctl=new AbortController(),abort=()=>ctl.abort();this.nativeDownloads.add(ctl);signal.addEventListener('abort',abort,{once:true});if(signal.aborted)ctl.abort();
|
||||
const timer=setTimeout(abort,900000);
|
||||
try {
|
||||
if(ctl.signal.aborted)throw new ApiError('下载已取消',499);
|
||||
const result=await transfer(this.baseUrl+path,{Authorization:`Bearer ${this.token}`,...(this.devPreviewServer?{'X-CMVR-Dev-Server':this.devPreviewServer}:{})},ctl.signal);
|
||||
if(epoch!==this.generation||ctl.signal.aborted)throw new ApiError('账号或连接已切换,下载取消',409);
|
||||
return result;
|
||||
}catch(error){if(epoch===this.generation&&(error as any)?.code==='AUTH_EXPIRED'){this.clear();this.expired();}throw error;}
|
||||
finally{clearTimeout(timer);signal.removeEventListener('abort',abort);this.nativeDownloads.delete(ctl);}
|
||||
}
|
||||
/** Stream authenticated downloads into a caller-owned file, with bounded memory. */
|
||||
async download(path:string, sink:(bytes:Uint8Array)=>Promise<void>, options:{signal?:AbortSignal;maxBytes?:number;onProgress?:(bytes:number,total:number)=>void;transport?:typeof fetch}={}) {
|
||||
if(!/^\/system\/files\/[a-zA-Z0-9-]+\/content$/.test(path)&&!/^\/system\/mobile-release\/[a-f0-9]{64}\/content$/.test(path))throw new ApiError('下载地址无效',400);
|
||||
|
||||
40
mobile-app/src/core/package-cache.ts
Normal file
40
mobile-app/src/core/package-cache.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import {packageVerifier,type PackageRelease} from './package-update.ts';
|
||||
export type PackageFileInfo={exists:boolean;size?:number;modificationTime?:number;creationTime?:number|null};
|
||||
export type FileVerification={size:number;modificationTime:number;creationTime:number|null};
|
||||
export type SavedPackage={name:string;sha256:string;size:number;versionCode:number;environment:string;schema?:2;verification?:FileVerification};
|
||||
export function fileVerification(info:PackageFileInfo):FileVerification|null {
|
||||
if(!info.exists||!Number.isSafeInteger(info.size)||Number(info.size)<1||!Number.isFinite(info.modificationTime)||Number(info.modificationTime)<=0)return null;
|
||||
return {size:info.size!,modificationTime:info.modificationTime!,creationTime:Number.isFinite(info.creationTime)&&Number(info.creationTime)>0?info.creationTime!:null};
|
||||
}
|
||||
export function savedPackage(release:PackageRelease,name:string,info?:PackageFileInfo):SavedPackage {
|
||||
if(!validPackageName(release,name))throw new Error('本地安装包名称无效');
|
||||
const stamp=info&&fileVerification(info);
|
||||
return {name,sha256:release.sha256,size:release.size,versionCode:release.versionCode,environment:release.environment,...(stamp&&stamp.size===release.size?{schema:2 as const,verification:stamp}:{})};
|
||||
}
|
||||
export function reusablePackage(record:any,release:PackageRelease,name:string,info:PackageFileInfo):boolean {
|
||||
const stamp=fileVerification(info),previous=record?.verification;
|
||||
return !!stamp&&record?.schema===2&&cachedPackageNames(release,[],record)[0]===name&&previous?.size===release.size&&stamp.size===release.size&&previous.modificationTime===stamp.modificationTime&&previous.creationTime===stamp.creationTime;
|
||||
}
|
||||
export function validPackageName(release:PackageRelease,name:unknown):name is string {
|
||||
return typeof name==='string'&&name.startsWith(release.sha256+'-')&&/^[a-f0-9]{64}-[a-z0-9-]+\.apk$/.test(name);
|
||||
}
|
||||
export function cachedPackageNames(release:PackageRelease,names:string[],record:any):string[] {
|
||||
const preferred=record&&record.sha256===release.sha256&&record.size===release.size&&record.versionCode===release.versionCode&&record.environment===release.environment&&validPackageName(release,record.name)?[record.name]:[];
|
||||
return [...new Set([...preferred,...names.filter(name=>validPackageName(release,name)).sort().reverse()])].slice(0,20);
|
||||
}
|
||||
export function ignoredPackageMatches(record:any,release:PackageRelease):boolean {
|
||||
return record?.versionCode===release.versionCode&&record?.sha256===release.sha256&&record?.environment===release.environment;
|
||||
}
|
||||
/** Read a private cached file in bounded chunks. This does not access the network. */
|
||||
export async function verifyCachedPackage(release:PackageRelease,read:(length:number)=>Promise<Uint8Array>,signal:AbortSignal,onProgress:(bytes:number)=>void,options:{now?:()=>number;pause?:()=>Promise<void>}={}){
|
||||
const verifier=packageVerifier(release),now=options.now??(()=>Date.now()),pause=options.pause??(()=>new Promise<void>(resolve=>setTimeout(resolve,0)));
|
||||
let bytes=0,work=0,lastProgress=-Infinity;
|
||||
const check=()=>{if(signal.aborted)throw new Error('本地安装包检查已取消');};
|
||||
for(;;){
|
||||
check();const part=await read(256*1024);check();if(!part.length)break;
|
||||
const start=now();verifier.write(part);bytes+=part.length;work+=Math.max(0,now()-start);
|
||||
const time=now();if(time-lastProgress>=150||bytes===release.size){onProgress(bytes);lastProgress=time;}
|
||||
if(work>=16){work=0;await pause();check();}
|
||||
}
|
||||
check();verifier.finish();onProgress(bytes);
|
||||
}
|
||||
@ -8,15 +8,33 @@ export function newerPackage(value:any,current:number,environment:string):Packag
|
||||
}
|
||||
/** Hash incrementally; never install a partial file or merely trust its filename. */
|
||||
export function packageVerifier(release:Pick<PackageRelease,'size'|'sha256'>){const hash=sha256.create();let size=0;return {write(bytes:Uint8Array){size+=bytes.length;if(size>release.size)throw new Error('安装包大小不匹配');hash.update(bytes);},finish(){if(size!==release.size||bytesToHex(hash.digest())!==release.sha256)throw new Error('安装包校验失败,请重新下载');}};}
|
||||
/** Split even a buffered network response into bounded work and give the UI a turn. */
|
||||
export async function processPackageChunk(bytes:Uint8Array,write:(chunk:Uint8Array)=>void,onChunk:(length:number)=>void,signal:AbortSignal,step=256*1024){
|
||||
for(let offset=0;offset<bytes.length;offset+=step){
|
||||
if(signal.aborted)throw new Error('下载已取消');
|
||||
const part=bytes.subarray(offset,Math.min(offset+step,bytes.length));
|
||||
write(part);onChunk(part.length);
|
||||
await new Promise<void>(resolve=>setTimeout(resolve,0));
|
||||
type ProcessingOptions={blockSize?:number;yieldAfterMs?:number;progressEveryMs?:number;now?:()=>number;pause?:()=>Promise<void>};
|
||||
/** Coalesce network fragments in bounded memory. The writer consumes each view synchronously.
|
||||
* Yield for actual processing work, not for every network fragment; throttle rendering separately.
|
||||
*/
|
||||
export function createPackageDownloadProcessor(write:(chunk:Uint8Array)=>void,onProgress:(bytes:number)=>void,signal:AbortSignal,options:ProcessingOptions={}){
|
||||
const {blockSize=256*1024,yieldAfterMs=16,progressEveryMs=100,now=()=>Date.now(),pause=()=>new Promise<void>(resolve=>setTimeout(resolve,0))}=options;
|
||||
if(!Number.isInteger(blockSize)||blockSize<1||blockSize>1024*1024||yieldAfterMs<=0||progressEveryMs<0)throw new Error('安装包处理参数无效');
|
||||
const buffer=new Uint8Array(blockSize);let used=0,processed=0,workMs=0,lastProgress=-Infinity,finished=false;
|
||||
const check=()=>{if(signal.aborted)throw new Error('下载已取消');};
|
||||
async function flush(final=false){
|
||||
check();
|
||||
if(used){const start=now();write(buffer.subarray(0,used));processed+=used;used=0;workMs+=Math.max(0,now()-start);}
|
||||
const time=now();
|
||||
if(processed&&(final||time-lastProgress>=progressEveryMs)){const start=now();onProgress(processed);lastProgress=time;workMs+=Math.max(0,now()-start);}
|
||||
check();
|
||||
if(workMs>=yieldAfterMs){workMs=0;await pause();check();}
|
||||
}
|
||||
if(signal.aborted)throw new Error('下载已取消');
|
||||
return {
|
||||
async push(bytes:Uint8Array){
|
||||
check();if(finished)throw new Error('安装包处理已完成');
|
||||
for(let offset=0;offset<bytes.length;){
|
||||
check();const count=Math.min(blockSize-used,bytes.length-offset),start=now();buffer.set(bytes.subarray(offset,offset+count),used);used+=count;offset+=count;workMs+=Math.max(0,now()-start);
|
||||
if(used===blockSize)await flush();
|
||||
}
|
||||
},
|
||||
async finish(){check();if(!finished){await flush(true);finished=true;}return processed;}
|
||||
};
|
||||
}
|
||||
/** No fallback to the Android installer when the native trust check is absent. */
|
||||
export async function verifyInstalledPackage(bridge:{verify:(uri:string,version:number)=>Promise<boolean>}|undefined,uri:string,version:number){
|
||||
|
||||
42
mobile-app/src/core/record-presentation.ts
Normal file
42
mobile-app/src/core/record-presentation.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import {display,type Module,type Row} from './modules.ts';
|
||||
export const recordType={
|
||||
title:{fontSize:14,lineHeight:20,fontWeight:'600' as const,includeFontPadding:false},
|
||||
body:{fontSize:12.5,lineHeight:19,includeFontPadding:false},
|
||||
specification:{fontSize:11.5,lineHeight:18,includeFontPadding:false},
|
||||
label:{fontSize:11,lineHeight:17,includeFontPadding:false},
|
||||
quantity:{fontSize:16,lineHeight:22,fontWeight:'600' as const,includeFontPadding:false},
|
||||
};
|
||||
export const inventoryModules=['stock','use','move','count','pending','in','out','check'];
|
||||
const first=(...values:unknown[])=>values.find(value=>value!=null&&String(value).trim()!=='');
|
||||
export function itemIdentity(row:Row,purchase=false){
|
||||
return {name:display(purchase?first(row.materialName,row.productName,row.itemName,row.item_name,row.requestNo):first(row.productName,row.itemName,row.materialName,row.item_name,row.taskNo,row.task_no)),
|
||||
spec:display(purchase?first(row.materialParams,row.productSpec,row.spec):first(row.spec,row.productSpec,row.materialParams)),
|
||||
brand:display(purchase?first(row.materialBrand,row.productBrand,row.brand):first(row.brand,row.productBrand,row.materialBrand)),
|
||||
batchName:display(first(row.purchaseBatchName,row.batchName)),batchNo:display(row.purchaseBatchNo),supplier:display(row.supplierName)};
|
||||
}
|
||||
export function recordQuantity(value:unknown){
|
||||
if(value==null||value==='')return '—';const text=String(value);
|
||||
if(!/^-?\d+(?:\.\d+)?$/.test(text))return display(value);
|
||||
const [whole,fraction='']=text.split('.'),tail=fraction.replace(/0+$/,'');
|
||||
return whole.replace(/\B(?=(\d{3})+(?!\d))/g,',')+(tail?'.'+tail:'');
|
||||
}
|
||||
export function recordLayout(width:number,fontScale=1){
|
||||
const screen=Number.isFinite(width)&&width>0?Math.min(width,480):360,scale=Number.isFinite(fontScale)&&fontScale>=1?fontScale:1;
|
||||
return {stackedFacts:(screen-52)/scale<230,stackedDetails:(screen-52)/scale<215,labelWidth:Math.ceil(52*scale)};
|
||||
}
|
||||
type RecordStatus={label:string;tone:'active'|'warning'|'success'|'muted'};
|
||||
const purchaseStatuses:Record<number,RecordStatus>={0:{label:'待采购',tone:'muted'},1:{label:'已下单',tone:'active'},2:{label:'采购中',tone:'active'},3:{label:'部分到货',tone:'warning'},4:{label:'已到齐',tone:'success'}};
|
||||
export function purchaseRecordStatus(row:Row):RecordStatus {
|
||||
if(Number(row.purchaseStatus)===5)return{label:'已取消',tone:'muted'};
|
||||
if(Number(row.pendingArrivalQuantity)>0)return{label:'待验收',tone:'warning'};
|
||||
if(row.purchaseStatus==null||String(row.purchaseStatus).trim()==='')return{label:'待核对',tone:'muted'};
|
||||
return purchaseStatuses[Number(row.purchaseStatus)]||{label:'待核对',tone:'muted'};
|
||||
}
|
||||
const quantityKeys:Record<string,string>={stock:'stockNum',move:'stockNum',use:'stockNum',count:'stockNum',purchase:'quantity',pending:'inNum',in:'inNum',check:'realNum',out:'outNum',production:'planned_quantity'};
|
||||
const primary:Record<string,string[]>={stock:['projectName','areaName'],use:['projectName','areaName'],move:['projectName','areaName'],count:['projectName','areaName'],pending:['sourceProjectName','purchaseBatchNo'],in:['sourceProjectName','areaName','businessDate'],out:['usageProjectName','areaName','outTime'],check:['projectName','areaName','bookNum','diffNum']};
|
||||
export function recordFields(module:Module,compactAmounts:boolean,canViewQuotes:boolean){
|
||||
const identity=new Set(['unit','spec','brand','materialParams','materialBrand','purchaseBatchNo',quantityKeys[module.key],...(module.key==='purchase'?['purchaseStatus','purchaseBatchName','supplierName']:[])]);
|
||||
const fields=module.fields.filter(([key])=>!identity.has(key)&&(module.key!=='purchase'||key!=='finalUnitPrice'||canViewQuotes)&&(!compactAmounts||!['actualUnitPrice','actualAmount'].includes(key)));
|
||||
const focus=primary[module.key]??(inventoryModules.includes(module.key)||module.key==='purchase'?[]:fields.slice(0,3).map(([key])=>key));
|
||||
return{quantityKey:quantityKeys[module.key],quantityLabel:module.fields.find(([key])=>key===quantityKeys[module.key])?.[1]||'数量',primary:fields.filter(([key])=>focus.includes(key)),secondary:fields.filter(([key])=>!focus.includes(key))};
|
||||
}
|
||||
@ -3,7 +3,7 @@ export type OperationKind='use'|'move'|'receive'|'borrow'|'check'|'return';
|
||||
export type OperationRow={source:Row;quantity:string;area:Row|null;stock?:Row|null;key:string;status:'editing'|'pending'|'success'|'failed'|'uncertain';error:string;payload?:RequestStep[]};
|
||||
export type RequestStep={path:string;method:string;body:Row};
|
||||
export type OperationForm={date:string;remark:string;project:Row|null};
|
||||
export const operationTitles:Record<OperationKind,string>={use:'领用出库',move:'移库',receive:'办理入库',borrow:'借用',check:'登记盘点',return:'归还库存'};
|
||||
export const operationTitles:Record<OperationKind,string>={use:'物料领用',move:'移库',receive:'办理入库',borrow:'借用',check:'登记盘点',return:'归还库存'};
|
||||
export function available(kind:OperationKind,row:OperationRow){return kind==='return'?Math.min(Number(row.source.outstandingQuantity)||0,Number(row.stock?.stockNum)||0):Number(kind==='receive'?row.source.inNum:row.source.stockNum)||0;}
|
||||
export function canRetry(kind:OperationKind,row:OperationRow){return kind!=='check'&&!(kind==='receive'&&!row.source.receiptRoot);}
|
||||
export function validateOperation(kind:OperationKind,rows:OperationRow[],form:OperationForm):string{
|
||||
|
||||
11
mobile-app/src/core/update-notes.ts
Normal file
11
mobile-app/src/core/update-notes.ts
Normal file
@ -0,0 +1,11 @@
|
||||
/** Accept existing plain-text release notes as well as signed update bullet lists. */
|
||||
export function updateNotes(value:unknown):string[]{
|
||||
const source=typeof value==='string'?value:Array.isArray(value)?value.filter((v):v is string=>typeof v==='string').join('\n'):'';
|
||||
const lines=source.slice(0,8000).replace(/(^|[\s;;。])(?:\d{1,2}[、..))](?!\d)|[•●▪·*])\s*/g,'$1\n').replace(/。(?=\S)/g,'。\n').split(/[\r\n;;]+/);
|
||||
return [...new Set(lines.map(line=>line.replace(/^\s*[-—]\s+/,'').trim()).filter(line=>line&&!/^(?:本次更新|更新说明|更新内容)[::]?$/.test(line)))].slice(0,20);
|
||||
}
|
||||
export function manifestUpdateNotes(manifest:unknown):string[]{
|
||||
if(!manifest||typeof manifest!=='object')return[];
|
||||
const metadata=(manifest as {metadata?:unknown}).metadata;
|
||||
return metadata&&typeof metadata==='object'?updateNotes((metadata as {releaseNotes?:unknown}).releaseNotes):[];
|
||||
}
|
||||
@ -1,13 +1,14 @@
|
||||
export type UpdateState = 'disabled' | 'checking' | 'current' | 'downloading' | 'ready' | 'failed';
|
||||
export type UpdateView = { state: UpdateState; visible: boolean; restarting: boolean; error: string };
|
||||
import {manifestUpdateNotes} from './update-notes.ts';
|
||||
export type UpdateView = { state: UpdateState; visible: boolean; restarting: boolean; error: string; notes?:string[] };
|
||||
export type UpdateDriver = {
|
||||
isEnabled: boolean;
|
||||
checkForUpdateAsync: () => Promise<{ isAvailable: boolean; isRollBackToEmbedded?: boolean }>;
|
||||
fetchUpdateAsync: () => Promise<{ isNew: boolean; isRollBackToEmbedded?: boolean }>;
|
||||
checkForUpdateAsync: () => Promise<{ isAvailable: boolean; isRollBackToEmbedded?: boolean; manifest?:unknown }>;
|
||||
fetchUpdateAsync: () => Promise<{ isNew: boolean; isRollBackToEmbedded?: boolean; manifest?:unknown }>;
|
||||
reloadAsync: () => Promise<void>;
|
||||
};
|
||||
export const updateMessages: Record<UpdateState, string> = {
|
||||
disabled: '当前运行方式不支持热更新', checking: '正在检查内网更新…', current: '已是当前版本',
|
||||
disabled: '当前运行方式不支持更新', checking: '正在检查更新…', current: '已是最新版本',
|
||||
downloading: '正在后台下载更新,不影响操作…', ready: '更新已下载,可重启应用立即生效',
|
||||
failed: '暂未连接更新服务,继续使用当前版本',
|
||||
};
|
||||
@ -27,7 +28,7 @@ export function createUpdateController(driver: UpdateDriver, changed: (view: Upd
|
||||
if (view.state === 'ready') { if (force) show(); return Promise.resolve(); }
|
||||
const interval = view.state === 'failed' ? 60_000 : 15 * 60_000;
|
||||
if (!force && now() - lastCheck < interval) return Promise.resolve();
|
||||
lastCheck = now(); emit({ state: 'checking', error: '' });
|
||||
lastCheck = now(); emit({ state: 'checking', error: '', notes:[] });
|
||||
inFlight = Promise.resolve().then(async () => {
|
||||
try {
|
||||
if (disposed) return;
|
||||
@ -38,7 +39,7 @@ export function createUpdateController(driver: UpdateDriver, changed: (view: Upd
|
||||
const fetched = await driver.fetchUpdateAsync();
|
||||
if (disposed) return;
|
||||
if (!fetched.isNew && !fetched.isRollBackToEmbedded) { emit({ state: 'current' }); return; }
|
||||
emit({ state: 'ready', visible: active && !deferred });
|
||||
emit({ state: 'ready', visible: active && !deferred, notes:manifestUpdateNotes(fetched.manifest) });
|
||||
} catch { emit({ state: 'failed' }); }
|
||||
finally { inFlight = undefined; }
|
||||
});
|
||||
|
||||
11
mobile-app/src/core/version-update.ts
Normal file
11
mobile-app/src/core/version-update.ts
Normal file
@ -0,0 +1,11 @@
|
||||
type PackageCheck={available:boolean;check:()=>Promise<{release:unknown;error:string}|undefined>};
|
||||
/** Prefer an installable release; an explicit check must also recover ignored releases. */
|
||||
export async function checkVersionUpdate(packages:PackageCheck,updates:{check:()=>Promise<void>;later:()=>void}){
|
||||
if(packages.available){
|
||||
const result=await packages.check();
|
||||
if(!result)return{error:''};
|
||||
if(result.release){updates.later();return{error:''};}
|
||||
if(result.error)return{error:result.error};
|
||||
}
|
||||
await updates.check();return{error:''};
|
||||
}
|
||||
48
mobile-app/src/package-cache.ts
Normal file
48
mobile-app/src/package-cache.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import {Directory,File,FileMode,Paths} from 'expo-file-system';
|
||||
import {readPreference,savePreference} from './core/preferences';
|
||||
import {cachedPackageNames,savedPackage,verifyCachedPackage,reusablePackage,fileVerification} from './core/package-cache';
|
||||
import type {PackageRelease} from './core/package-update';
|
||||
|
||||
export async function rememberPackage(scope:string,release:PackageRelease,file:File){
|
||||
await savePreference(scope,'downloaded-package',savedPackage(release,file.name,file.info()));
|
||||
}
|
||||
async function validateFile(scope:string,release:PackageRelease,file:File,record:unknown,signal:AbortSignal,onProgress:(bytes:number)=>void):Promise<boolean>{
|
||||
const check=()=>{if(signal.aborted)throw new Error('本地安装包检查已取消');};
|
||||
check();const before=file.info();if(!before.exists||before.size!==release.size)return false;
|
||||
// Completed files are private and immutable. Reuse their SHA-256 result only
|
||||
// while the recorded size, creation time and last-write time still match.
|
||||
if(reusablePackage(record,release,file.name,before))return true;
|
||||
if(typeof file.digest==='function'){
|
||||
const hash=await file.digest('SHA-256');check();if(hash!==release.sha256)return false;onProgress(release.size);
|
||||
}else{
|
||||
const handle=file.open(FileMode.ReadOnly);
|
||||
try{await verifyCachedPackage(release,count=>handle.readBytes(count),signal,onProgress);}finally{handle.close();}
|
||||
}
|
||||
check();const after=file.info(),a=fileVerification(before),b=fileVerification(after);
|
||||
if(!after.exists||after.size!==release.size||a&&b&&(a.modificationTime!==b.modificationTime||a.creationTime!==b.creationTime))return false;
|
||||
await rememberPackage(scope,release,file).catch(()=>{});check();return true;
|
||||
}
|
||||
export async function validatePackageFile(scope:string,release:PackageRelease,file:File,signal:AbortSignal):Promise<boolean>{
|
||||
const record=await readPreference(scope,'downloaded-package').catch(()=>null);
|
||||
return validateFile(scope,release,file,record,signal,()=>{});
|
||||
}
|
||||
export async function restorePackage(scope:string,release:PackageRelease,signal:AbortSignal,onProgress:(bytes:number)=>void):Promise<File|null>{
|
||||
const dir=new Directory(Paths.cache,'app-updates');
|
||||
if(!dir.exists)return null;
|
||||
const record=await readPreference(scope,'downloaded-package').catch(()=>null);
|
||||
// Also recover complete files downloaded before the persistent record existed.
|
||||
const preferred=cachedPackageNames(release,[],record),checked=new Set<string>();
|
||||
async function attempt(name:string){
|
||||
if(signal.aborted)throw new Error('本地安装包检查已取消');
|
||||
const file=new File(dir,name);
|
||||
checked.add(name);
|
||||
try{
|
||||
return await validateFile(scope,release,file,record,signal,onProgress)?file:null;
|
||||
}catch(error){if(signal.aborted)throw error;}
|
||||
return null;
|
||||
}
|
||||
for(const name of preferred){const file=await attempt(name);if(file)return file;}
|
||||
const names=dir.list().filter(entry=>entry instanceof File).map(entry=>entry.name);
|
||||
for(const name of cachedPackageNames(release,names,null)){if(checked.has(name))continue;const file=await attempt(name);if(file)return file;}
|
||||
return null;
|
||||
}
|
||||
@ -23,7 +23,7 @@ export function Account({api,kind,policy,onSaved,bindLeave}:{api:ApiClient;kind:
|
||||
async function save(){if(lock.current||uncertain)return;const message=kind==='profile'?(form?profileError(form):'请先加载个人资料。'):passwordError(old,next,confirm,policy);if(message)return setError(message);
|
||||
lock.current=true;setBusy(true);setError('');setSuccess('');
|
||||
try{if(kind==='profile'&&form){await api.request('/system/user/profile',{method:'PUT',body:profilePayload(form)});setOriginal(JSON.stringify(form));onSaved(form);setSuccess('个人资料已保存。');}
|
||||
else{await api.request('/system/user/profile/updatePwd',{method:'PUT',body:{oldPassword:old,newPassword:next}});setOld('');setNext('');setConfirm('');setSuccess('密码已修改,下次登录请使用新密码。');}}
|
||||
else{await api.request('/system/user/profile/updatePwd',{method:'PUT',body:{oldPassword:old,newPassword:next}});setOld('');setNext('');setConfirm('');setSuccess('密码已修改,下次登录请使用新密码。');Alert.alert('密码修改成功','密码已修改成功,下次登录请使用新密码。',[{text:'我知道了'}]);}}
|
||||
catch(e){const unknown=e instanceof ApiError&&e.code===503;setUncertain(unknown);setError((e as Error).message+(unknown?' 本次结果尚未确定,请返回核对;不要重复提交。':''));}
|
||||
finally{lock.current=false;setBusy(false);}}
|
||||
async function changeAvatar(){if(lock.current||uncertain)return;lock.current=true;setBusy(true);setError('');setSuccess('');try{
|
||||
|
||||
@ -6,13 +6,16 @@ import type {Row} from '../core/modules';
|
||||
import {formatDateTime} from '../core/date-display';
|
||||
import {Button,Card,Heading,Note,s,useTheme} from '../ui';
|
||||
import {ArrivalPhotos} from './ArrivalPhotos';
|
||||
import {Text} from '../typography';
|
||||
import {ItemIdentity,RecordMeta} from './ItemIdentity';
|
||||
import {purchaseRecordStatus,recordQuantity,recordType} from '../core/record-presentation';
|
||||
|
||||
export function ArrivalHistory({api,row,close}:{api:ApiClient;row:Row;close:()=>void}){
|
||||
const t=useTheme(),[records,setRecords]=useState<Row[]>([]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[expanded,setExpanded]=useState<number|null>(null);
|
||||
useEffect(()=>{const ctl=new AbortController();setLoading(true);setError('');void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:ctl.signal}).then(r=>{if(!ctl.signal.aborted)setRecords(r.data||[]);}).catch(e=>{if(!ctl.signal.aborted)setError(e.message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,row.id,attempt]);
|
||||
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>到货记录</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}><Note>{row.materialName} · {row.materialParams} · {row.unit}</Note>
|
||||
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>到货记录</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}><Card style={{padding:12}}><ItemIdentity item={row} purchase quantity={row.quantity??null} quantityLabel="采购数量" status={purchaseRecordStatus(row)}/></Card>
|
||||
{loading&&<Note>正在读取到货记录…</Note>}{!!error&&<><Note>{error}</Note><Button title="重新加载" secondary onPress={()=>setAttempt(n=>n+1)}/></>}{!loading&&!error&&!records.length&&<Note>暂无到货记录</Note>}
|
||||
{records.map(record=><Card key={record.id}><Heading>{record.arrivalNo}</Heading><Note>{formatDateTime(record.arrivalDate)} · 到货 {record.arrivalQuantity} {row.unit} · {['待验收','验收通过','拒收','已撤销'][record.acceptanceStatus]||'已撤销'}</Note>{!!record.remark&&<Note>{record.remark}</Note>}{!!record.acceptanceRemark&&<Note>验收说明:{record.acceptanceRemark}</Note>}
|
||||
{records.map(record=><Card key={record.id} style={{padding:12,gap:7}}><Text style={{...recordType.body,fontWeight:'600',color:t.text}}>{record.arrivalNo}</Text><RecordMeta label="到货日期" value={formatDateTime(record.arrivalDate)}/><RecordMeta label="到货数量" value={`${recordQuantity(record.arrivalQuantity)} ${row.unit||''}`}/><RecordMeta label="验收状态" value={['待验收','验收通过','拒收','已撤销'][record.acceptanceStatus]||'已撤销'}/>{!!record.remark&&<Note>{record.remark}</Note>}{!!record.acceptanceRemark&&<Note>验收说明:{record.acceptanceRemark}</Note>}
|
||||
{(record.photos||[]).length?<><Button title={expanded===record.id?'收起照片':`查看到货照片(${record.photos.length})`} secondary onPress={()=>setExpanded(expanded===record.id?null:record.id)}/>{expanded===record.id&&<ArrivalPhotos api={api} requestId={row.id} photos={record.photos} readonly/>}</>:<Note>未上传到货照片</Note>}</Card>)}
|
||||
</ScrollView></SafeAreaView></Modal>;
|
||||
}
|
||||
|
||||
@ -1,14 +1,15 @@
|
||||
import {Text,TextInput} from '../typography';
|
||||
import React from 'react';
|
||||
import {ActivityIndicator,Pressable,View,useWindowDimensions} from 'react-native';
|
||||
import {ActivityIndicator,Pressable,View} from 'react-native';
|
||||
import {Card,Icon,useTheme} from '../ui';
|
||||
import {display,type Row} from '../core/modules';
|
||||
import type {ArrivalKind} from '../core/arrival-actions';
|
||||
import {arrivalLayout} from '../core/arrival-layout';
|
||||
import {ItemIdentity,RecordMeta} from './ItemIdentity';
|
||||
import {purchaseRecordStatus} from '../core/record-presentation';
|
||||
|
||||
export function OnlyMineToggle({value,onChange}:{value:boolean;onChange:(value:boolean)=>void}){
|
||||
export function OnlyMineToggle({value,onChange,label='只看我创建的采购明细'}:{value:boolean;onChange:(value:boolean)=>void;label?:string}){
|
||||
const t=useTheme();
|
||||
return <Pressable accessibilityRole="checkbox" accessibilityLabel="只看我创建的采购明细" accessibilityState={{checked:value}} onPress={()=>onChange(!value)} style={{flexDirection:'row',alignItems:'center',gap:5,paddingVertical:6,paddingHorizontal:4}}>
|
||||
return <Pressable accessibilityRole="checkbox" accessibilityLabel={label} accessibilityState={{checked:value}} onPress={()=>onChange(!value)} style={{flexDirection:'row',alignItems:'center',gap:5,paddingVertical:6,paddingHorizontal:4}}>
|
||||
<Icon name={value?'checkbox':'square-outline'} size={19} color={value?t.accent:t.muted}/><Text style={{fontSize:13,color:value?t.accent:t.text}}>只看我的</Text>
|
||||
</Pressable>;
|
||||
}
|
||||
@ -43,23 +44,9 @@ export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,rese
|
||||
|
||||
export function ArrivalCard({item,queue,children}:{item:Row;queue:ArrivalKind;children:React.ReactNode}){
|
||||
const t=useTheme(),key=queue==='accept'?'pendingArrivalQuantity':'remainingQuantity';
|
||||
const {width,fontScale}=useWindowDimensions(),layout=arrivalLayout(width,fontScale);
|
||||
return <Card style={{padding:14,gap:10}}>
|
||||
<View style={{flexDirection:layout.stackedHeader?'column':'row',alignItems:layout.stackedHeader?'stretch':'flex-start',gap:8}}>
|
||||
<View style={{flex:layout.stackedHeader?undefined:1,minWidth:0,gap:4}}><Text selectable style={{color:t.text,fontSize:16,fontWeight:'700',lineHeight:24}}>{display(item.materialName)}</Text>
|
||||
<Text selectable style={{color:t.muted,fontSize:14,lineHeight:20}}>{display(item.materialParams)}</Text>
|
||||
</View>
|
||||
<View style={{flexDirection:layout.stackedHeader?'row':'column',justifyContent:'space-between',alignItems:layout.stackedHeader?'center':'flex-end',flexShrink:0,gap:2,...(!layout.stackedHeader?{minWidth:78,maxWidth:130}:{})}}>
|
||||
<Text style={{color:t.muted,fontSize:12,lineHeight:20}}>{queue==='accept'?'待验收':'待登记'}</Text>
|
||||
<View style={{flexDirection:'row',alignItems:'baseline',justifyContent:'flex-end',flexShrink:1,gap:5}}>
|
||||
<Text selectable adjustsFontSizeToFit minimumFontScale={0.85} numberOfLines={1} style={{color:t.accent,fontSize:20,lineHeight:26,fontWeight:'700',flexShrink:1}}>{display(item[key])}</Text>
|
||||
<Text style={{color:t.muted,fontSize:14,lineHeight:20,flexShrink:1,textAlign:'right'}}>{display(item.unit)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
<View style={{gap:6}}>{[['projectName','项目'],['purchaseBatchNo','采购批次'],['supplierName','供应商']].map(([field,label])=><View key={field} style={{flexDirection:layout.stackedDetails?'column':'row',alignItems:layout.stackedDetails?'stretch':'flex-start',gap:layout.stackedDetails?2:8}}>
|
||||
<Text style={{...(!layout.stackedDetails?{width:layout.labelWidth}:{}),color:t.muted,fontSize:12,lineHeight:22,flexShrink:0}}>{label}</Text><Text selectable style={{...(!layout.stackedDetails?{flex:1}:{}),minWidth:0,color:t.text,fontSize:14,lineHeight:22}}>{display(item[field])}</Text>
|
||||
</View>)}</View>
|
||||
<View style={{alignItems:'stretch'}}>{children}</View>
|
||||
return <Card style={{padding:12,gap:9}}>
|
||||
<ItemIdentity item={item} purchase quantity={item[key]??null} quantityLabel={queue==='accept'?'待验收数量':'可登记到货数量'} status={purchaseRecordStatus(item)}/>
|
||||
<RecordMeta label="项目" value={display(item.projectName)} secondary/>
|
||||
<View style={{paddingTop:8,borderTopWidth:1,borderColor:t.line,alignItems:'stretch'}}>{children}</View>
|
||||
</Card>;
|
||||
}
|
||||
|
||||
@ -9,6 +9,8 @@ import {display,localDate,validDate,type Row} from '../core/modules';
|
||||
import {Button,Card,Choice,DateField,Field,Heading,Note,s,useTheme} from '../ui';
|
||||
import {Dialog as Alert} from '../dialogs';
|
||||
import {useOperationDraft} from '../hooks/useOperationDraft';
|
||||
import {ItemIdentity} from './ItemIdentity';
|
||||
import {purchaseRecordStatus} from '../core/record-presentation';
|
||||
|
||||
export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;row:Row;mode:'arrival'|'accept';close:()=>void;done:()=>void;scope?:string}){
|
||||
const t=useTheme(),accept=mode==='accept',lock=useRef(false),alive=useRef(true),requestKey=useRef(Crypto.randomUUID());
|
||||
@ -54,7 +56,7 @@ export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;
|
||||
return <Modal visible animationType="slide" onRequestClose={requestClose}><SafeAreaView style={[s.fill,{backgroundColor:t.bg,width:'100%',maxWidth:Platform.OS==='web'?480:undefined,alignSelf:'center'}]}><KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
|
||||
<View style={{paddingHorizontal:18,paddingVertical:10,flexDirection:'row',alignItems:'center',justifyContent:'space-between',borderBottomWidth:1,borderColor:t.line}}><Heading>{title}</Heading><Button title="关闭" secondary disabled={busy} onPress={requestClose}/></View>
|
||||
<ScrollView style={s.fill} keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{paddingBottom:18}]}>
|
||||
<Note>{display(row.materialName)} · {display(row.materialParams)} · {display(row.unit)}</Note><Note>{display(row.projectName)} · {display(row.purchaseBatchNo)}</Note>
|
||||
<Card style={{padding:12,gap:8}}><ItemIdentity item={row} purchase quantity={row.quantity??null} quantityLabel="采购数量" status={purchaseRecordStatus(row)}/></Card>
|
||||
{!draft.ready&&<Note>{draft.error||'正在读取本机草稿…'}</Note>}{!!draft.error&&draft.ready&&<Note>{draft.error}</Note>}{draft.restored&&!attempted&&<Note>已恢复上次填写,请核对本次数量和照片。</Note>}{checkingPhotos&&<Note>正在核对草稿照片…</Note>}
|
||||
{loading&&<Note>正在获取最新待验收到货记录…</Note>}
|
||||
{!preview?<>
|
||||
|
||||
@ -48,7 +48,7 @@ export function Assistant({api}:{api:ApiClient}){
|
||||
return <KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
|
||||
<View style={[s.row,{paddingHorizontal:14,paddingBottom:10,justifyContent:'space-between'}]}><Text style={{color:t.muted,fontSize:11}}>查询即返回 · 操作先确认</Text><Pressable accessibilityRole="button" accessibilityLabel="开启新对话" disabled={busy||uncertain||!session} onPress={()=>Alert.alert('开启新对话','将开始新的对话,未发送的文字和附件会清空。已办理的业务不受影响。',[{text:'继续当前对话',style:'cancel'},{text:'新对话',onPress:()=>void newConversation()}])} style={{padding:9,flexDirection:'row',gap:5,opacity:busy||uncertain?.5:1}}><Icon name="create-outline" size={17}/><Text style={{color:t.accent,fontSize:12}}>新对话</Text></Pressable></View>
|
||||
<ScrollView ref={scroll} contentContainerStyle={s.page} keyboardShouldPersistTaps="handled" onContentSizeChange={()=>{if(followLatest.current)scroll.current?.scrollToEnd({animated:true});}}>
|
||||
{!session?.messages?.length&&<View style={{paddingTop:18,gap:18}}><Image source={require('../../assets/assistant.png')} style={{width:66,height:66,borderRadius:22}}/><Text style={{fontSize:27,fontWeight:'700',lineHeight:38,color:t.text}}>把需求告诉我,{ '\n' }我们一起完成。</Text><Note>不知道从哪里开始也没关系。先说一部分,我会帮你核对,缺少的信息可以接着补充。</Note><View style={{gap:10}}>{['帮我查一下库存','我要登记到货,该怎么做?','我想借用物资'].map(prompt=><Pressable key={prompt} accessibilityRole="button" accessibilityLabel={prompt} disabled={busy||uncertain} onPress={()=>setText(prompt)} style={{padding:15,borderRadius:14,borderWidth:1,borderColor:t.line,backgroundColor:t.card,flexDirection:'row',alignItems:'center',gap:12}}><Icon name="sparkles-outline" size={17}/><Text style={{flex:1,color:t.text,fontSize:14}}>{prompt}</Text><Icon name="arrow-up-outline" size={16}/></Pressable>)}</View></View>}
|
||||
{!session?.messages?.length&&<View style={{paddingTop:18,gap:18}}><Image source={require('../../assets/assistant.png')} style={{width:66,height:66,borderRadius:22}}/><Text style={{fontSize:27,fontWeight:'700',lineHeight:38,color:t.text}}>把需求告诉我,{ '\n' }我们一起完成。</Text><Note>不知道从哪里开始也没关系。先说一部分,我会帮你核对,缺少的信息可以接着补充。</Note><View style={{gap:10}}>{['帮我查一下库存','我要登记到货,该怎么做?','我想领用物资'].map(prompt=><Pressable key={prompt} accessibilityRole="button" accessibilityLabel={prompt} disabled={busy||uncertain} onPress={()=>setText(prompt)} style={{padding:15,borderRadius:14,borderWidth:1,borderColor:t.line,backgroundColor:t.card,flexDirection:'row',alignItems:'center',gap:12}}><Icon name="sparkles-outline" size={17}/><Text style={{flex:1,color:t.text,fontSize:14}}>{prompt}</Text><Icon name="arrow-up-outline" size={16}/></Pressable>)}</View></View>}
|
||||
{[...(session?.messages||[]),...(pending?[pending]:[])].map((message:Row,i:number)=><View key={message.id||`pending-${i}`} style={{gap:10}}>
|
||||
{message.role!=='user'&&<View style={s.row}><Image source={require('../../assets/assistant.png')} style={{width:28,height:28,borderRadius:14}}/><Text style={{color:t.muted,fontSize:11}}>{message.durationMs?`耗时 ${(message.durationMs/1000).toFixed(1)} 秒`:'AI 助手'}</Text></View>}
|
||||
<View style={{alignSelf:message.role==='user'?'flex-end':'stretch',maxWidth:message.role==='user'?'92%':'100%',backgroundColor:message.role==='user'?t.soft:t.card,padding:15,borderRadius:16,borderTopRightRadius:message.role==='user'?4:16,borderTopLeftRadius:message.role==='user'?16:4,borderWidth:1,borderColor:t.line,gap:10}}><Text selectable style={{color:t.text,lineHeight:24}}>{message.content}</Text>{message.attachments?.map((f:Row)=>f.type==='image'?<ProtectedImage key={f.id} api={api} path={`${root}/attachments/${encodeURIComponent(f.id)}/content`} label={f.name}/>:<Note key={f.id}>{f.name}</Note>)}</View>
|
||||
|
||||
@ -9,6 +9,7 @@ import {available,canRetry,operationTitles,runOperations,validateOperation,type
|
||||
import {Button,Card,Choice,DateField,Field,Heading,Note,s,useTheme} from '../ui';
|
||||
import {useOperationDraft} from '../hooks/useOperationDraft';
|
||||
import {Dialog as Alert} from '../dialogs';
|
||||
import {ItemIdentity,RecordMeta} from './ItemIdentity';
|
||||
|
||||
type Snapshot={rows:OperationRow[];form:OperationForm;preview:boolean};
|
||||
export type BatchOperationProps={api:ApiClient;input:Row[];kind:OperationKind;scope:string;close:()=>void;done:()=>void};
|
||||
@ -63,10 +64,10 @@ export function BatchOperation({api,input,kind,scope,close,done}:BatchOperationP
|
||||
{['move','borrow','receive','return'].includes(kind)&&<Choice label="统一目标库区" items={areas} value={null} onChange={area=>setRows(old=>old.map(r=>({...r,area})))} nameKey="areaName"/>}
|
||||
<View style={s.row}><Button title={kind==='return'?'填入所选库区可还数量':'全部填入可用数量'} secondary disabled={!ready} onPress={fill}/>{kind==='return'&&<Button title="全部归还" secondary disabled={!ready} onPress={allReturn}/>}</View>
|
||||
</>:<Card><Note>{form.date} · {form.remark||'无备注'}</Note>{!!form.project&&<Note>借入项目:{form.project.projectName}</Note>}<Note>{attempted?`共 ${rows.length} 项,已成功 ${succeeded} 项`:'请逐项核对数量和目标库区后提交。'}</Note></Card>}
|
||||
{rows.map((row,index)=><Card key={row.key} style={{padding:12,gap:8}}><Text style={{fontSize:15,lineHeight:21,fontWeight:'600',color:t.text}}>{index+1}. {display(row.source.productName||row.source.itemName)}</Text><Text style={{fontSize:12,lineHeight:18,color:t.muted}}>{display(row.source.projectName||row.source.sourceProjectName||row.source.borrowerProjectName)} · {display(row.source.areaName||row.stock?.areaName)}</Text>
|
||||
{rows.map((row,index)=><Card key={row.key} style={{padding:12,gap:8}}><ItemIdentity item={row.source} index={index} quantity={available(kind,row)} quantityLabel={kind==='check'?'账面数量':'可用数量'}/><RecordMeta label="项目" value={display(row.source.projectName||row.source.sourceProjectName||row.source.borrowerProjectName)} secondary/><RecordMeta label="库区" value={display(row.source.areaName||row.stock?.areaName)} secondary/>
|
||||
{!preview?<>
|
||||
{kind==='return'&&<Choice label="取料库存" items={stocks} value={row.stock||null} onChange={stock=>changeRow(index,{stock})} nameKey="label"/>}
|
||||
<Note>{kind==='check'?'账面':'可用'} {available(kind,row)} {row.source.unit||''}{kind==='return'?` · 未还 ${row.source.outstandingQuantity}`:''}</Note>
|
||||
{kind==='return'&&<Note>未还 {row.source.outstandingQuantity} {row.source.unit||''}</Note>}
|
||||
<Field label={kind==='check'?'实际盘点数量':'本次数量'} value={row.quantity} onChange={quantity=>changeRow(index,{quantity})} keyboard="decimal-pad"/>
|
||||
{['move','receive','borrow','return'].includes(kind)&&<Choice label="目标库区" items={areas} value={row.area} onChange={area=>changeRow(index,{area})} nameKey="areaName"/>}
|
||||
{rows.length>1&&<Button title="移除此项" secondary onPress={()=>setRows(old=>old.filter((_,i)=>i!==index))}/>}
|
||||
|
||||
@ -2,8 +2,9 @@ import React,{useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {ActivityIndicator,FlatList,Pressable,View} from 'react-native';
|
||||
import {Text,TextInput} from '../typography';
|
||||
import {ApiClient,allows} from '../core/network';
|
||||
import {display,recordDisplay,type Module,type Row} from '../core/modules';
|
||||
import {Button,Card,Icon,Note,s,useTheme} from '../ui';
|
||||
import {display,type Module,type Row} from '../core/modules';
|
||||
import {RecordCard} from './RecordCard';
|
||||
import {Button,Icon,Note,s,useTheme} from '../ui';
|
||||
import {ArrivalCard,ArrivalListTools,OnlyMineToggle} from './ArrivalListParts';
|
||||
import {arrivalListQuery} from '../core/arrival-list';
|
||||
import {ArrivalActions} from './ArrivalActions';
|
||||
@ -27,7 +28,7 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
|
||||
const initialFilters=Object.fromEntries(Object.entries(initialQuery).filter(([key])=>!['arrivalQueue','borrow'].includes(key)));
|
||||
const load=useCallback(async(next:number,text:string,append=false)=>{
|
||||
if(append&&busyRef.current)return;lastRequest.current={next,text,append};const id=++serial.current;controller.current?.abort();controller.current=new AbortController();busyRef.current=true;setBusy(true);setError('');appliedQuery.current=text.trim();
|
||||
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),...(['arrival','purchase'].includes(module.key)&&onlyMine?{onlyMine:true}:{}),pageNum:next,pageSize:20,...(module.search?{[module.search]:text.trim()}:{})},signal:controller.current.signal}),module.key==='purchase'?api.request<Row>('/warehouse/amount-display',{signal:controller.current.signal}):Promise.resolve(null)]);
|
||||
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),...(['arrival','purchase','pending'].includes(module.key)&&onlyMine?{onlyMine:true}:{}),pageNum:next,pageSize:20,...(module.search?{[module.search]:text.trim()}:{})},signal:controller.current.signal}),module.key==='purchase'?api.request<Row>('/warehouse/amount-display',{signal:controller.current.signal}):Promise.resolve(null)]);
|
||||
if(id!==serial.current)return;if(money)setCompactAmounts(money.data.enabled===true);const result=data.data&&Array.isArray(data.data.rows)?data.data:data;
|
||||
setRows(old=>{const fresh=result.rows||[];return append?[...old,...fresh.filter((r:Row)=>!old.some(v=>String(v.id||v.loanNo)===String(r.id||r.loanNo)))]:fresh;});setTotal(result.total||0);setPage(next);
|
||||
if(!append){setSelected([]);offset.current=0;list.current?.scrollToOffset({offset:0,animated:false});}
|
||||
@ -44,20 +45,23 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
|
||||
function confirmCheck(row:Row){if(busyRef.current)return;Alert.alert('确认盘点生效',`${display(row.productName)}:账面 ${display(row.bookNum)} → 实盘 ${display(row.realNum)}。确认后调整库存。`,[{text:'返回核对',style:'cancel'},{text:'确认生效',onPress:()=>{if(busyRef.current)return;busyRef.current=true;setBusy(true);void api.request(`/warehouse/check/confirm/${row.id}`,{method:'PUT'}).then(refresh).catch(e=>setError((e as Error).message+' 请刷新核对结果。')).finally(()=>{busyRef.current=false;setBusy(false);});}}]);}
|
||||
const canSelect=['stock','use','move'].includes(module.key)?stockWrite:module.key==='pending'&&allows(permissions,['warehouse:in:confirm']);
|
||||
const done=()=>{setOperation(null);setBatch(null);setSelected([]);void refresh();};
|
||||
const actions=(item:Row)=><View style={{gap:8}}>
|
||||
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'领用出库'} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
|
||||
{module.key==='stock'&&stockWrite&&<View style={s.row}><Button title="领用" disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'use'})}/><Button title="借用" secondary disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'borrow'})}/><Button title="移库" secondary disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'move'})}/></View>}
|
||||
{module.key==='loans'&&stockWrite&&stockRead&&!!item.active&&Number(item.outstandingQuantity)>0&&<Button title="办理归还" disabled={busy} onPress={()=>setOperation({row:item,kind:'return'})}/>}
|
||||
const actions=(item:Row)=>{
|
||||
const visible=['stock','use','move'].includes(module.key)?stockWrite:module.key==='count'?allows(permissions,['warehouse:check:add']):module.key==='check'?Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm']):module.key==='pending'?eligible(item):['purchase','arrival'].includes(module.key);
|
||||
if(!visible)return null;
|
||||
return <View style={{gap:8}}>
|
||||
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'物料领用'} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
|
||||
{module.key==='stock'&&stockWrite&&<View style={{flexDirection:'row',gap:8}}><Button title="领用" style={{flex:1,minWidth:0}} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'use'})}/><Button title="移库" secondary style={{flex:1,minWidth:0}} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'move'})}/></View>}
|
||||
{module.key==='count'&&allows(permissions,['warehouse:check:add'])&&<Button title="登记盘点" disabled={busy} onPress={()=>setOperation({row:item,kind:'check'})}/>}
|
||||
{module.key==='check'&&Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm'])&&<Button title="确认盘点生效" disabled={busy} onPress={()=>confirmCheck(item)}/>}
|
||||
{module.key==='purchase'&&<Button title="到货记录" secondary disabled={busy} onPress={()=>setHistoryRow(item)}/>}
|
||||
{module.key==='arrival'&&<ArrivalActions row={item} permissions={permissions} queue={arrivalQueue} onHistory={()=>setHistoryRow(item)} onOpen={kind=>{if(!busy)setOperation({row:item,kind});}}/>}
|
||||
{module.key==='pending'&&eligible(item)&&<Button title="办理入库" disabled={busy} onPress={()=>setOperation({row:item,kind:'receive'})}/>}
|
||||
</View>;
|
||||
};
|
||||
return <View style={s.fill}>
|
||||
{module.key==='arrival'?<ArrivalListTools query={query} setQuery={setQuery} queue={arrivalQueue} setQueue={changeArrivalQueue} busy={busy} total={total} page={page} onlyMine={onlyMine} setOnlyMine={changeOnlyMine} search={()=>void load(1,query)} reset={()=>{setQuery('');void load(1,'');}}/>:<View style={{paddingHorizontal:14,paddingVertical:8,gap:8}}>
|
||||
{!!module.search&&<View style={{flexDirection:'row',gap:8,alignItems:'center'}}><View style={{flex:1,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:9,backgroundColor:t.card,paddingLeft:10}}><Icon name="search-outline" size={18}/><TextInput accessibilityLabel="搜索物品或关键词" placeholder="搜索物品或关键词" placeholderTextColor={t.muted} value={query} onChangeText={setQuery} onSubmitEditing={()=>void load(1,query)} returnKeyType="search" style={{flex:1,minWidth:0,minHeight:42,fontSize:14,color:t.text,padding:8}}/>{!!query&&<Pressable accessibilityRole="button" accessibilityLabel="清除搜索" onPress={()=>{setQuery('');void load(1,'');}} style={{padding:10}}><Icon name="close-circle" size={17}/></Pressable>}</View><Button title="查询" busy={busy} onPress={()=>void load(1,query)}/></View>}
|
||||
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{module.key==='purchase'&&<OnlyMineToggle value={onlyMine} onChange={changeOnlyMine}/>} {canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}{module.key==='loans'&&stockWrite&&stockRead&&onNavigate&&<Button title="发起借用" secondary onPress={()=>onNavigate('stock',{borrow:true})}/>}</View>
|
||||
<View style={{flexDirection:'row',flexWrap:'wrap',gap:4,justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{['purchase','pending'].includes(module.key)&&<OnlyMineToggle label={module.key==='pending'?'只看本人发起的待入库来源':'只看我创建的采购明细'} value={onlyMine} onChange={changeOnlyMine}/>} {canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}</View>
|
||||
</View>}
|
||||
{!!error&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Text accessibilityRole="alert" style={{fontSize:13,lineHeight:19,color:'#bd3636'}}>{error}</Text><Button title="重试" secondary onPress={()=>void load(lastRequest.current.next,lastRequest.current.text,lastRequest.current.append)}/></View>}
|
||||
{picking&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Button title={`选择已加载可办理项(最多 100 项)`} secondary disabled={busy} onPress={()=>setSelected(rows.filter(eligible).slice(0,100))}/></View>}
|
||||
@ -65,17 +69,9 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
|
||||
refreshing={busy&&page===1} onRefresh={()=>void refresh()} ListEmptyComponent={!busy?<Note>{error?'查询失败,请重试。':module.key==='arrival'?'当前没有待办理的到货记录。':'当前条件下暂无记录。'}</Note>:<ActivityIndicator color={t.accent}/>}
|
||||
renderItem={({item})=><View>{picking&&<Pressable accessibilityRole="checkbox" accessibilityState={{checked:selected.some(r=>r.id===item.id),disabled:!eligible(item)||busy}} accessibilityLabel={`选择 ${item.productName||item.materialName}`} disabled={!eligible(item)||busy} onPress={()=>toggle(item)} style={{flexDirection:'row',gap:6,alignItems:'center',padding:8}}><Icon name={selected.some(r=>r.id===item.id)?'checkbox':'square-outline'} size={21} color={eligible(item)?t.accent:t.muted}/><Text style={{fontSize:13,color:t.muted}}>{eligible(item)?'加入本次办理':'当前不可办理'}</Text></Pressable>}{module.key==='arrival'?<ArrivalCard item={item} queue={arrivalQueue}>{actions(item)}</ArrivalCard>:<RecordCard module={module} item={item} compactAmounts={compactAmounts} canViewQuotes={canViewQuotes}>{!picking&&actions(item)}</RecordCard>}</View>}
|
||||
ListFooterComponent={rows.length<total?<View style={{paddingTop:12}}><Button title={`加载更多(还剩 ${Math.max(0,total-rows.length)} 条)`} secondary busy={busy} onPress={()=>void load(page+1,appliedQuery.current,true)}/></View>:rows.length?<Text style={{textAlign:'center',fontSize:12,color:t.muted,padding:12}}>已显示全部记录</Text>:undefined}/>
|
||||
{picking&&<View style={{backgroundColor:t.card,borderTopWidth:1,borderColor:t.line,padding:12,gap:8}}><Text style={{fontSize:13,color:t.text}}>已选 {selected.length} 项</Text><View style={s.row}>{module.key==='pending'?<Button title="批量入库" disabled={!selected.length||busy} onPress={()=>setBatch('receive')}/>:<><Button title="批量领用" disabled={!selected.length||busy} onPress={()=>setBatch('use')}/><Button title="批量移库" secondary disabled={!selected.length||busy} onPress={()=>setBatch('move')}/><Button title="批量借用" secondary disabled={!selected.length||busy} onPress={()=>setBatch('borrow')}/></>}</View></View>}
|
||||
{picking&&<View style={{backgroundColor:t.card,borderTopWidth:1,borderColor:t.line,padding:12,gap:8}}><Text style={{fontSize:13,color:t.text}}>已选 {selected.length} 项</Text><View style={s.row}>{module.key==='pending'?<Button title="批量入库" disabled={!selected.length||busy} onPress={()=>setBatch('receive')}/>:<><Button title="批量领用" disabled={!selected.length||busy} onPress={()=>setBatch('use')}/><Button title="批量移库" secondary disabled={!selected.length||busy} onPress={()=>setBatch('move')}/></>}</View></View>}
|
||||
{!!historyRow&&<ArrivalHistory api={api} row={historyRow} close={()=>setHistoryRow(null)}/>}
|
||||
{!!batch&&<BatchOperation api={api} input={selected} kind={batch} scope={scope} close={()=>setBatch(null)} done={done}/>}
|
||||
{!!operation&&(operation.kind==='arrival'||operation.kind==='accept'?<ArrivalOperation api={api} row={operation.row} mode={operation.kind} scope={scope} close={()=>setOperation(null)} done={done}/>:operation.kind==='return'?<LoanOperation api={api} row={operation.row} scope={scope} close={()=>setOperation(null)} done={done}/>:<StockOperation api={api} row={operation.row} kind={operation.kind as OperationKind} scope={scope} close={()=>setOperation(null)} done={done}/>)}
|
||||
</View>;
|
||||
}
|
||||
function RecordCard({module,item,children,compactAmounts,canViewQuotes}:{module:Module;item:Row;children:React.ReactNode;compactAmounts:boolean;canViewQuotes:boolean}){
|
||||
const t=useTheme(),[more,setMore]=useState(false),quantityKey:Record<string,string>={stock:'stockNum',move:'stockNum',use:'stockNum',count:'stockNum',purchase:'quantity',pending:'inNum',in:'inNum',loans:'outstandingQuantity',check:'diffNum',out:'outNum',production:'planned_quantity'},quantity=quantityKey[module.key];
|
||||
const fields=module.fields.filter(([key])=>(module.key!=='purchase'||key!=='finalUnitPrice'||canViewQuotes)&&key!==quantity&&key!=='unit'&&(!compactAmounts||!['actualUnitPrice','actualAmount'].includes(key)));
|
||||
return <Card style={{padding:12,gap:8}}><View style={{flexDirection:'row',alignItems:'flex-start',gap:10}}><Text style={{color:t.text,fontSize:16,fontWeight:'600',lineHeight:22,flex:1,minWidth:0}}>{display(item[module.titleKey]||item.productName||item.taskNo)}</Text>{quantity&&<View style={{maxWidth:'42%',alignItems:'flex-end',gap:2}}><Text style={{fontSize:18,lineHeight:24,fontWeight:'700',color:t.accent}}>{display(item[quantity])} <Text style={{fontSize:12}}>{item.unit||''}</Text></Text><Text style={{fontSize:12,lineHeight:18,color:t.muted}}>{module.fields.find(([key])=>key===quantity)?.[1]}</Text></View>}</View>
|
||||
{(more?fields:fields.slice(0,3)).map(([key,label])=><View key={key} style={{flexDirection:'row',alignItems:'flex-start',gap:8}}><Text style={{width:76,color:t.muted,fontSize:12,lineHeight:20}}>{label}</Text><Text selectable style={{flex:1,minWidth:0,color:t.text,fontSize:14,lineHeight:20}}>{recordDisplay(module,key,item[key])}</Text></View>)}
|
||||
{fields.length>3&&<Pressable accessibilityRole="button" accessibilityLabel={more?'收起详情':'展开详情'} onPress={()=>setMore(v=>!v)} style={{paddingVertical:8,flexDirection:'row',alignItems:'center',gap:4}}><Text style={{fontSize:12,color:t.muted}}>{more?'收起详情':'展开详情'}</Text><Icon name={more?'chevron-up':'chevron-down'} size={13}/></Pressable>}{children}
|
||||
</Card>;
|
||||
}
|
||||
|
||||
31
mobile-app/src/screens/ItemIdentity.tsx
Normal file
31
mobile-app/src/screens/ItemIdentity.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
import React from 'react';
|
||||
import {View,useWindowDimensions} from 'react-native';
|
||||
import {Text,useReadingScale} from '../typography';
|
||||
import {useTheme} from '../ui';
|
||||
import {itemIdentity,recordLayout,recordQuantity,recordType} from '../core/record-presentation';
|
||||
import type {Row} from '../core/modules';
|
||||
|
||||
export function RecordMeta({label,value,secondary=false,small=false}:{label:string;value:string;secondary?:boolean;small?:boolean}){
|
||||
const t=useTheme(),scale=useReadingScale(),{width,fontScale}=useWindowDimensions(),layout=recordLayout(width,fontScale*scale);
|
||||
return <View style={{flexDirection:layout.stackedDetails?'column':'row',alignItems:'flex-start',gap:layout.stackedDetails?2:8,minWidth:0}}>
|
||||
<Text style={{...recordType.label,color:t.muted,...(!layout.stackedDetails?{width:layout.labelWidth}:{}),flexShrink:0}}>{label}</Text>
|
||||
<Text selectable style={{...(small?recordType.specification:secondary?recordType.label:recordType.body),color:secondary?t.muted:t.text,...(!layout.stackedDetails?{flex:1}:{}),minWidth:0,flexShrink:1}}>{value}</Text>
|
||||
</View>;
|
||||
}
|
||||
export function ItemIdentity({item,purchase=false,quantity,quantityLabel='数量',status,index,details=true}:{item:Row;purchase?:boolean;quantity?:unknown;quantityLabel?:string;status?:{label:string;tone:string};index?:number;details?:boolean}){
|
||||
const t=useTheme(),scale=useReadingScale(),{width,fontScale}=useWindowDimensions(),layout=recordLayout(width,fontScale*scale),identity=itemIdentity(item,purchase),amount=recordQuantity(quantity),stacked=layout.stackedFacts||amount.length>12;
|
||||
const dark=t.bg==='#101722',tone=status?.tone==='success'?{text:dark?'#8bddad':'#237653',bg:dark?'#193d2d':'#edf8f2'}:status?.tone==='warning'?{text:dark?'#f5cb80':'#946113',bg:dark?'#42331e':'#fff6e7'}:{text:status?.tone==='muted'?t.muted:t.accent,bg:status?.tone==='muted'?t.bg:t.soft};
|
||||
return <View style={{gap:8,minWidth:0}}>
|
||||
<View style={{flexDirection:'row',alignItems:'flex-start',gap:8,minWidth:0}}><Text selectable style={{...recordType.title,color:t.text,flex:1,minWidth:0}}>{index!=null?`${index+1}. `:''}{identity.name}</Text>
|
||||
{!!status&&<View style={{paddingHorizontal:7,paddingVertical:3,borderRadius:5,backgroundColor:tone.bg,maxWidth:'44%',flexShrink:0}}><Text style={{...recordType.label,fontSize:11,lineHeight:16,color:tone.text}}>{status.label}</Text></View>}
|
||||
</View>
|
||||
{details&&<View style={{backgroundColor:t.bg,borderRadius:6,paddingHorizontal:8,paddingVertical:6,gap:3,minWidth:0}}><RecordMeta label="规格" value={identity.spec} small/><RecordMeta label="品牌" value={identity.brand}/></View>}
|
||||
{quantity!==undefined&&<View style={{flexDirection:stacked?'column':'row',justifyContent:'space-between',alignItems:stacked?'stretch':'baseline',gap:3,minWidth:0}}>
|
||||
<Text style={{...recordType.label,color:t.muted}}>{quantityLabel}</Text><View style={{flexDirection:'row',alignItems:'baseline',justifyContent:'flex-end',flexWrap:'wrap',gap:4,minWidth:0,flexShrink:1}}><Text selectable style={{...recordType.quantity,color:t.accent,flexShrink:1}}>{amount}</Text>{!!item.unit&&<Text style={{...recordType.label,color:t.muted,flexShrink:1}}>{String(item.unit)}</Text>}</View>
|
||||
</View>}
|
||||
{purchase&&<View style={{gap:5,paddingTop:8,borderTopWidth:1,borderColor:t.line}}>
|
||||
<RecordMeta label="批次" value={identity.batchName}/>
|
||||
<RecordMeta label="供应商" value={identity.supplier}/>
|
||||
</View>}
|
||||
</View>;
|
||||
}
|
||||
18
mobile-app/src/screens/RecordCard.tsx
Normal file
18
mobile-app/src/screens/RecordCard.tsx
Normal file
@ -0,0 +1,18 @@
|
||||
import React,{useState} from 'react';
|
||||
import {Pressable,View} from 'react-native';
|
||||
import {Text} from '../typography';
|
||||
import {Card,Icon,useTheme} from '../ui';
|
||||
import {recordDisplay,type Module,type Row} from '../core/modules';
|
||||
import {inventoryModules,purchaseRecordStatus,recordFields,recordType} from '../core/record-presentation';
|
||||
import {ItemIdentity,RecordMeta} from './ItemIdentity';
|
||||
|
||||
export function RecordCard({module,item,children,compactAmounts,canViewQuotes}:{module:Module;item:Row;children?:React.ReactNode;compactAmounts:boolean;canViewQuotes:boolean}){
|
||||
const t=useTheme(),[more,setMore]=useState(false),fields=recordFields(module,compactAmounts,canViewQuotes),purchase=module.key==='purchase',secondary=fields.secondary.filter(([key])=>item[key]!=null&&item[key]!=='');
|
||||
return <Card style={{padding:12,gap:9}}>
|
||||
<ItemIdentity item={item} purchase={purchase} details={purchase||inventoryModules.includes(module.key)} quantity={fields.quantityKey?item[fields.quantityKey]??null:undefined} quantityLabel={fields.quantityLabel} status={purchase?purchaseRecordStatus(item):undefined}/>
|
||||
{!!fields.primary.length&&<View style={{gap:4,paddingTop:8,borderTopWidth:1,borderColor:t.line}}>{fields.primary.map(([key,label])=><RecordMeta key={key} label={label} value={recordDisplay(module,key,item[key])} secondary/>)}</View>}
|
||||
{more&&<View style={{gap:5,paddingTop:4}}>{secondary.map(([key,label])=><RecordMeta key={key} label={label} value={recordDisplay(module,key,item[key])}/>)}</View>}
|
||||
{!!secondary.length&&<Pressable accessibilityRole="button" accessibilityLabel={more?'收起详情':'展开详情'} accessibilityState={{expanded:more}} onPress={()=>setMore(v=>!v)} style={{minHeight:34,flexDirection:'row',alignItems:'center',gap:5}}><Text style={{...recordType.label,color:t.muted}}>{more?'收起信息':'更多信息'}</Text><Icon name={more?'chevron-up':'chevron-down'} size={13}/></Pressable>}
|
||||
{!!children&&<View style={{paddingTop:8,borderTopWidth:1,borderColor:t.line}}>{children}</View>}
|
||||
</Card>;
|
||||
}
|
||||
@ -11,10 +11,9 @@ import {usePrivateImage} from '../files';
|
||||
import {ApiClient} from '../core/network';
|
||||
import type {Module,Row} from '../core/modules';
|
||||
import {workspaceColumns} from '../core/workspace-layout';
|
||||
import type {AppUpdateControls} from '../AppUpdates';
|
||||
|
||||
const icons:Record<string,IconName>={arrival:'checkmark-circle-outline',use:'file-tray-outline',move:'swap-horizontal-outline',count:'clipboard-outline',stock:'cube-outline',purchase:'cart-outline',pending:'download-outline',in:'file-tray-full-outline',loans:'swap-horizontal-outline',check:'clipboard-outline',out:'file-tray-outline',production:'construct-outline',files:'folder-outline'};
|
||||
const hints:Record<string,string>={arrival:'登记到货、逐次验收合格数量',use:'选择库存,核对后领用出库',move:'同项目库存更换实际存放库区',count:'现场清点,登记实际数量',stock:'查询物品、数量和所在库区',purchase:'采购明细与报价进展',pending:'核对物品,现场办理入库',in:'追溯每一次入库',loans:'查询项目间借还进度',check:'查看盘点记录、确认盘点',out:'查看领用与退回记录',production:'查询任务、产量与执行状态',files:'查看、上传和下载共享文件'};
|
||||
const hints:Record<string,string>={arrival:'登记到货、逐次验收合格数量',use:'选择库存,核对后物料领用',move:'同项目库存更换实际存放库区',count:'现场清点,登记实际数量',stock:'查询物品、数量和所在库区',purchase:'采购明细与报价进展',pending:'核对物品,现场办理入库',in:'追溯每一次入库',loans:'查询项目间借还进度',check:'查看盘点记录、确认盘点',out:'查看领用与退回记录',production:'查询任务、产量与执行状态',files:'查看、上传和下载共享文件'};
|
||||
type Props={api:ApiClient;user:Row;modules:Module[];scope:string;open:(name:string,query?:Row)=>void;go:(tab:string)=>void;ai:boolean};
|
||||
export function Workspace({api,user,modules,scope,open,go,ai}:Props){
|
||||
const t=useTheme(),scale=useReadingScale(),{width,fontScale}=useWindowDimensions(),columns=workspaceColumns(width,fontScale*scale);
|
||||
@ -49,13 +48,12 @@ export function Me({api,user,open}:{api:ApiClient;user:Row;open:(name:string)=>v
|
||||
<Text style={{color:t.muted,fontSize:11,textAlign:'center',letterSpacing:2,marginTop:8}}>CMVR · 让工作更简单</Text>
|
||||
</ScrollView>;
|
||||
}
|
||||
export function Settings({updates,environment,baseUrl,connection,packageUpdate,logout,about=false}:{updates:AppUpdateControls;environment:string;baseUrl:string;connection?:React.ReactNode;packageUpdate?:React.ReactNode;logout:()=>void;about?:boolean}){
|
||||
export function Settings({environment,baseUrl,connection,versionUpdate,logout,about=false}:{environment:string;baseUrl:string;connection?:React.ReactNode;versionUpdate?:React.ReactNode;logout:()=>void;about?:boolean}){
|
||||
const t=useTheme(),{mode,setMode}=useContext(AppearanceContext),reading=useContext(ReadingContext);
|
||||
return <ScrollView contentContainerStyle={s.page}>{about?<><View style={{alignItems:'center',paddingVertical:24,gap:12}}><View style={{backgroundColor:t.accent,padding:20,borderRadius:25}}><Icon name="layers-outline" color="#fff" size={43}/></View><Heading>CMVR 移动工作空间</Heading><Note>把业务带到现场,让协作更轻松。</Note></View><Card><Note>应用版本 {Constants.expoConfig?.version}</Note><Note>当前环境 {environment==='prod'?'正式环境':'开发环境'}</Note><Note>更新标识 {Updates.updateId?.slice(0,8)||'内置版本'}</Note></Card><Card><Heading>数据与安全</Heading><Note>业务数据来自公司内网服务。可见数据和可用操作由后台权限决定;AI 操作须经人工确认,查询直接返回。</Note><Note>请仅在可信的公司网络使用。不要在反馈或 AI 对话中填写密码和授权码。</Note></Card></>:<>
|
||||
<Card><Heading>外观</Heading><Note>选择适合你的阅读方式。</Note><View style={s.row}>{([['system','跟随系统'],['light','浅色'],['dark','深色']] as const).map(([value,label])=><Button key={value} title={`${mode===value?'✓ ':''}${label}`} secondary={mode!==value} onPress={()=>setMode(value)}/>)}</View></Card>
|
||||
<Card><Heading>文字大小</Heading><Note>默认紧凑字号,同时遵循手机系统字体设置。</Note><View style={s.row}>{([['compact','紧凑'],['standard','标准'],['large','大字']] as const).map(([key,label])=><Button key={key} title={label} secondary={reading.size!==key} onPress={()=>reading.setSize(key)}/>)}</View><Text style={{color:t.text}}>物品名称 · 库存数量 128 个</Text></Card>{connection||<Card><Heading>内网连接</Heading><Note>当前:{environment==='prod'?'正式环境':'开发环境'}</Note><Text selectable style={{color:t.text,lineHeight:22}}>{baseUrl}</Text><Note>正式服务由安装包固定,避免误切环境。</Note></Card>}
|
||||
<Card><Heading>应用更新</Heading><Note>{updates.text}</Note><Note>打开 App 或回到前台时自动检查更新。下载完成会弹窗提示,由你选择何时重启;选择稍后也可在下次启动时生效。</Note><Note>版本 {Constants.expoConfig?.version} · {Updates.updateId?.slice(0,8)||'内置版本'}</Note>{updates.enabled&&<Button title={updates.view.state==='ready'?'立即更新':'检查更新'} secondary busy={['checking','downloading'].includes(updates.view.state)} onPress={updates.check}/>}</Card>
|
||||
{packageUpdate}
|
||||
{versionUpdate}
|
||||
<Button title="退出登录" secondary onPress={logout}/>
|
||||
</>}</ScrollView>;
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@ import {createRequire} from 'node:module';
|
||||
import vm from 'node:vm';
|
||||
import {arrivalListQuery} from '../src/core/arrival-list.ts';
|
||||
import {arrivalLayout} from '../src/core/arrival-layout.ts';
|
||||
import {purchaseRecordStatus} from '../src/core/record-presentation.ts';
|
||||
test('registration queue asks the server for confirmed eligible purchases, not all not-yet-accepted purchases',()=>{
|
||||
assert.deepEqual(arrivalListQuery('arrival'),{pendingRegistration:true,arrivalReady:true,priceLocked:true});
|
||||
assert.deepEqual(arrivalListQuery('accept'),{pendingAcceptance:true,priceLocked:true});
|
||||
@ -15,7 +16,7 @@ const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.
|
||||
const exports={};
|
||||
vm.runInNewContext(compiled,{exports,require:name=>({react:React,'react/jsx-runtime':require('react/jsx-runtime'),
|
||||
'react-native':{ActivityIndicator:'Loading',Pressable:'Pressable',Text:'Text',TextInput:'TextInput',View:'View',useWindowDimensions:()=>({width:393,fontScale:1})},
|
||||
'../typography':{Text:'Text',TextInput:'TextInput'},'../core/arrival-layout':{arrivalLayout},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>({})},'../core/modules':{display:v=>v==null?'—':String(v)}}[name]||require(name))});
|
||||
'../typography':{Text:'Text',TextInput:'TextInput'},'./ItemIdentity':{ItemIdentity:'ItemIdentity',RecordMeta:'RecordMeta'},'../core/record-presentation':{purchaseRecordStatus},'../core/arrival-layout':{arrivalLayout},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>({})},'../core/modules':{display:v=>v==null?'—':String(v)}}[name]||require(name))});
|
||||
function nodes(tree){const all=[];function walk(n){if(!n||typeof n!=='object')return;all.push(n);React.Children.toArray(n.props?.children).forEach(walk);}walk(tree);return all;}
|
||||
test('compact queue tabs have equal width, correct state, accessible search and explicit clear',()=>{
|
||||
const calls=[];const tree=exports.ArrivalListTools({query:'水冷',setQuery:v=>calls.push(v),queue:'accept',setQueue:v=>calls.push(v),busy:false,search:()=>calls.push('search'),reset:()=>calls.push('reset'),total:25,page:2});
|
||||
@ -25,13 +26,9 @@ test('compact queue tabs have equal width, correct state, accessible search and
|
||||
all.find(n=>n.type==='TextInput').props.onSubmitEditing();all.find(n=>n.props.accessibilityLabel==='清除搜索').props.onPress();
|
||||
assert.deepEqual(calls,['arrival','search','reset']);
|
||||
});
|
||||
test('acceptance card keeps quantity and unit together without a tall fixed-size badge',()=>{
|
||||
test('acceptance card forwards the pending quantity and complete identity to the compact shared item header',()=>{
|
||||
const all=nodes(exports.ArrivalCard({item:{materialName:'很长的物品名称',materialParams:'规格',remainingQuantity:0,pendingArrivalQuantity:18,unit:'很长的测试单位'},queue:'accept',children:null}));
|
||||
assert.ok(all.some(n=>n.type==='Text'&&n.props.children==='18'));
|
||||
assert.ok(all.some(n=>n.type==='Text'&&n.props.children==='很长的测试单位'&&n.props.style.fontSize===14));
|
||||
assert.ok(all.some(n=>n.type==='Text'&&n.props.children==='待验收'));
|
||||
assert.ok(all.some(n=>n.type==='View'&&n.props.style.flexDirection==='row'&&React.Children.toArray(n.props.children).some(c=>c.props?.children==='18')&&React.Children.toArray(n.props.children).some(c=>c.props?.children==='很长的测试单位')));
|
||||
assert.ok(all.filter(n=>n.type==='Text').every(n=>n.props.style.fontSize>=12));
|
||||
const summary=all.find(n=>n.type==='ItemIdentity');assert.ok(summary);assert.equal(summary.props.quantity,18);assert.equal(summary.props.item.unit,'很长的测试单位');assert.equal(summary.props.item.materialParams,'规格');assert.equal(summary.props.quantityLabel,'待验收数量');assert.equal(summary.props.purchase,true);
|
||||
assert.ok(all.filter(n=>n.type==='View').every(n=>n.props.style.width!==94));
|
||||
});
|
||||
test('query state survives queue changes and pagination uses applied search rather than unsent text',()=>{
|
||||
|
||||
@ -6,6 +6,7 @@ import vm from 'node:vm';
|
||||
import {modules} from '../src/core/modules.ts';
|
||||
import {allows} from '../src/core/network.ts';
|
||||
import * as dateDisplay from '../src/core/date-display.ts';
|
||||
import {purchaseRecordStatus} from '../src/core/record-presentation.ts';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
|
||||
async function screen({mode='arrival',failure=false}={}){
|
||||
@ -17,6 +18,7 @@ async function screen({mode='arrival',failure=false}={}){
|
||||
const native={Modal:'Modal',ScrollView:'ScrollView',View:'View',KeyboardAvoidingView:'KeyboardAvoidingView',Platform:{OS:'android'}};
|
||||
const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',DateField:'DateField',Field:'Field',Heading:'Heading',Note:'Note'};
|
||||
const imports={'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}},'../hooks/useOperationDraft':{useOperationDraft:()=>({ready:true,restored:false,error:'',saveNow:async()=>{},clear:async()=>{}})}};
|
||||
imports['./ItemIdentity']={ItemIdentity:'ItemIdentity'};imports['../core/record-presentation']={purchaseRecordStatus};
|
||||
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>imports[name]||require(name),AbortController});
|
||||
const api={async request(path,options){calls.push({path,...options});if(failure)throw Error('timeout');return {data:{}};}};
|
||||
const render=()=>{cursor=0;refCursor=0;return module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});};
|
||||
|
||||
@ -34,7 +34,7 @@ test('home keeps all allowed field-operation shortcuts without the oversized mar
|
||||
'expo-constants':{},'expo-updates':{},'../ui':{Card:'Card',Icon:'Icon',Avatar:'Avatar',Heading:'Heading',Note:'Note',s:{row:{},page:{}},useTheme:()=>({})},
|
||||
'../typography':{Text:'Text',useReadingScale:()=>1},'../core/preferences':{},'../core/workspace-tasks':{workspaceTasks,shortcutOrder},'../core/workspace-layout':{workspaceColumns},'../core/account':{imagePath:()=>''},'../files':{usePrivateImage:()=>undefined}});
|
||||
const all=nodes(module.Workspace({api:{},user:{userName:'测试管理员'},modules,ai:true,open:v=>opened.push(v),go:v=>visited.push(v)}));
|
||||
for(const title of ['到货验收','待入库','出库领用','移库','现场盘点']){
|
||||
for(const title of ['到货验收','待入库','物料领用','移库','现场盘点']){
|
||||
const node=all.find(n=>n.props.accessibilityLabel===title&&typeof n.props.style==='function');assert.ok(node);node.props.onPress();
|
||||
assert.equal(node.props.style({pressed:false}).flexBasis,workspaceColumns(width,fontScale)===1?'100%':'47%');
|
||||
}
|
||||
|
||||
28
mobile-app/tests/native-package-download.test.mjs
Normal file
28
mobile-app/tests/native-package-download.test.mjs
Normal file
@ -0,0 +1,28 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {nativePackageDownload,downloadMeter} from '../src/core/native-package-download.ts';
|
||||
import {ApiClient} from '../src/core/network.ts';
|
||||
const hash='a'.repeat(64),release={sha256:hash,size:100,versionCode:9,versionName:'1.0.2',environment:'dev',notes:'',downloadPath:`/system/mobile-release/${hash}/content`},uri='file:///cache/app-updates/'+hash+'-123.apk';
|
||||
function harness(){let listener,removed=false;return {events:{addListener(name,fn){assert.equal(name,'CmvrPackageProgress');listener=fn;return {remove(){removed=true}}}},emit:v=>listener(v),removed:()=>removed};}
|
||||
test('native transfer gets authenticated options, scoped progress and cleans listeners',async()=>{
|
||||
const h=harness(),progress=[];let options;const abort=new AbortController();
|
||||
const bridge={download:async(id,value)=>{options=value;h.emit({id:'other',phase:'downloading',bytes:50,total:100});h.emit({id,phase:'downloading',bytes:50,total:100,connections:4});h.emit({id,phase:'verifying',bytes:101,total:100});h.emit({id,phase:'verifying',bytes:100,total:100,connections:4});return {uri,sha256:hash,size:100,connections:4}},cancelDownload(){}};
|
||||
const result=await nativePackageDownload(bridge,h.events,release,uri,'http://192.168.0.222:8090/dev-api'+release.downloadPath,{Authorization:'Bearer test'},abort.signal,e=>progress.push(e));
|
||||
assert.equal(result.connections,4);assert.equal(options.headers.Authorization,'Bearer test');assert.equal(options.size,100);assert.deepEqual(progress.map(e=>e.bytes),[50,100]);assert.equal(h.removed(),true);
|
||||
});
|
||||
test('cancel and mismatched native results never produce an installable result',async()=>{
|
||||
const h=harness(),abort=new AbortController();let cancelled=false;
|
||||
const bridge={download:async()=>{abort.abort();return {uri,sha256:hash,size:100}},cancelDownload(){cancelled=true}};
|
||||
await assert.rejects(nativePackageDownload(bridge,h.events,release,uri,'http://example',{},abort.signal,()=>{}),/取消/);assert(cancelled);assert(h.removed());
|
||||
const good={uri,sha256:hash,size:100};for(const bad of [{...good,size:99},{...good,sha256:'b'.repeat(64)},{...good,uri:'file:///other'}]){
|
||||
const events=harness();await assert.rejects(nativePackageDownload({download:async()=>bad,cancelDownload(){}},events.events,release,uri,'http://example',{},new AbortController().signal,()=>{}),/校验/);assert(events.removed());
|
||||
}
|
||||
});
|
||||
test('account switching actively cancels native traffic and rejects stale results',async()=>{
|
||||
const api=new ApiClient('http://127.0.0.1:8080',()=>{});api.authenticate('one');let finish,cancelled=false;
|
||||
const pending=api.nativePackageDownload(release.downloadPath,async(url,headers,signal)=>{assert.equal(headers.Authorization,'Bearer one');assert.equal(url,'http://127.0.0.1:8080'+release.downloadPath);signal.addEventListener('abort',()=>cancelled=true);return new Promise(r=>finish=r)},new AbortController().signal);
|
||||
api.authenticate('two');assert(cancelled);finish('done');await assert.rejects(pending,/切换/);
|
||||
await assert.rejects(api.nativePackageDownload('/system/files/not-an-apk',()=>Promise.resolve(),new AbortController().signal),/无效/);
|
||||
});
|
||||
test('download meter uses real byte deltas and remaining time without made-up progress',()=>{
|
||||
let now=0;const meter=downloadMeter(()=>now);assert.equal(meter(0,10000).bytesPerSecond,0);now=1000;assert.deepEqual(meter(2000,10000),{bytes:2000,total:10000,bytesPerSecond:2000,remainingSeconds:4});now=2000;assert.equal(meter(6000,10000).bytesPerSecond,3000);now=3000;assert.equal(meter(10000,10000).remainingSeconds,0);now=4000;assert.equal(meter(0,10000).bytesPerSecond,0);
|
||||
});
|
||||
68
mobile-app/tests/native/CmvrPackageTransferTest.java
Normal file
68
mobile-app/tests/native/CmvrPackageTransferTest.java
Normal file
@ -0,0 +1,68 @@
|
||||
package testapp;
|
||||
import com.sun.net.httpserver.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
public class CmvrPackageTransferTest {
|
||||
static byte[] data=new byte[12*1024*1024];static String hash;static int passed;
|
||||
static AtomicInteger active=new AtomicInteger(),maximum=new AtomicInteger(),redirected=new AtomicInteger();static AtomicBoolean retry=new AtomicBoolean();
|
||||
static void check(boolean condition,String message){if(!condition)throw new AssertionError(message);}
|
||||
static String hash(byte[] bytes)throws Exception{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));}
|
||||
static void serve(HttpExchange x,String mode)throws IOException {
|
||||
try {
|
||||
if(!"Bearer test-token".equals(x.getRequestHeaders().getFirst("Authorization"))){x.sendResponseHeaders(401,-1);return;}
|
||||
if(mode.equals("redirect")){x.getResponseHeaders().set("Location","/forbidden");x.sendResponseHeaders(302,-1);return;}
|
||||
if(mode.equals("forbidden")){redirected.incrementAndGet();x.sendResponseHeaders(500,-1);return;}
|
||||
long start=0,end=data.length-1;String range=x.getRequestHeaders().getFirst("Range");boolean partial=range!=null&&!mode.equals("plain")&&!mode.equals("slow");
|
||||
if(partial){String[] values=range.substring(6).split("-");start=Long.parseLong(values[0]);end=Long.parseLong(values[1]);x.getResponseHeaders().set("Content-Range","bytes "+start+"-"+end+"/"+(mode.equals("bad-range")?data.length+1:data.length));}
|
||||
x.getResponseHeaders().set("Content-Type","application/vnd.android.package-archive");long length=end-start+1;x.sendResponseHeaders(partial?206:200,length);
|
||||
int current=active.incrementAndGet();maximum.accumulateAndGet(current,Math::max);
|
||||
boolean truncate=mode.equals("retry")&&length>1&&retry.compareAndSet(false,true);
|
||||
try(OutputStream out=x.getResponseBody()){
|
||||
for(long offset=start;offset<=end;){int count=(int)Math.min(32768,end-offset+1);if(truncate&&offset-start>=131072)break;out.write(data,(int)offset,count);offset+=count;if(length>1)try{Thread.sleep(mode.equals("slow")?5:2);}catch(InterruptedException e){Thread.currentThread().interrupt();break;}}
|
||||
}finally{active.decrementAndGet();}
|
||||
}finally{x.close();}
|
||||
}
|
||||
static File file()throws IOException{return Files.createTempFile("cmvr-native-transfer-",".apk").toFile();}
|
||||
static void success(String address,int requested,int expected)throws Exception {
|
||||
File file=file();List<Long> download=new ArrayList<>(),verify=new ArrayList<>();
|
||||
try {
|
||||
int connections=new CmvrPackageTransfer(address,Map.of("Authorization","Bearer test-token"),file,data.length,hash,requested,(phase,n,total,c)->{check(n<=total,"progress overflow");(phase.equals("downloading")?download:verify).add(n);}).run();
|
||||
check(connections==expected,"connection fallback");check(Arrays.equals(Files.readAllBytes(file.toPath()),data),"download bytes changed");
|
||||
for(List<Long> values:List.of(download,verify)){check(!values.isEmpty(),"missing progress");for(int i=1;i<values.size();i++)check(values.get(i)>=values.get(i-1),"progress regressed");check(values.get(values.size()-1)==data.length,"incomplete progress");}
|
||||
passed++;
|
||||
}finally{file.delete();}
|
||||
}
|
||||
static void rejected(String address,String expectedHash,Map<String,String> headers)throws Exception {
|
||||
File file=file();boolean rejected=false;
|
||||
try{new CmvrPackageTransfer(address,headers,file,data.length,expectedHash,4,(p,n,t,c)->{}).run();}catch(Exception e){rejected=true;}
|
||||
check(rejected&&!file.exists(),"bad download was left installable");passed++;
|
||||
}
|
||||
public static void main(String[] args)throws Exception {
|
||||
if(args.length>0&&args[0].equals("benchmark")){benchmark();return;}
|
||||
for(int i=0;i<data.length;i++)data[i]=(byte)(i*31+i/101);hash=hash(data);
|
||||
HttpServer server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0);ExecutorService requests=Executors.newCachedThreadPool();server.setExecutor(requests);
|
||||
for(String mode:List.of("range","plain","slow","retry","bad-range","redirect","forbidden"))server.createContext("/"+mode,x->serve(x,mode));server.start();String base="http://127.0.0.1:"+server.getAddress().getPort();
|
||||
try {
|
||||
success(base+"/range",4,4);check(maximum.get()>=2,"range requests did not overlap");
|
||||
success(base+"/plain",4,1);success(base+"/range",1,1);success(base+"/retry",4,4);check(retry.get(),"retry fixture did not run");
|
||||
rejected(base+"/range","0".repeat(64),Map.of("Authorization","Bearer test-token"));
|
||||
rejected(base+"/bad-range",hash,Map.of("Authorization","Bearer test-token"));
|
||||
rejected(base+"/redirect",hash,Map.of("Authorization","Bearer test-token"));check(redirected.get()==0,"followed credential redirect");
|
||||
rejected(base+"/range",hash,Map.of("Authorization","Bearer wrong"));
|
||||
File file=file();AtomicReference<CmvrPackageTransfer> ref=new AtomicReference<>();AtomicLong bytes=new AtomicLong();
|
||||
CmvrPackageTransfer job=new CmvrPackageTransfer(base+"/slow",Map.of("Authorization","Bearer test-token"),file,data.length,hash,4,(p,n,t,c)->{bytes.set(n);if(n>0)ref.get().cancel();});ref.set(job);
|
||||
boolean aborted=false;try{job.run();}catch(Exception e){aborted=true;}check(aborted&&!file.exists()&&bytes.get()<data.length,"cancellation failed");passed++;
|
||||
System.out.println("Native transfer test groups passed: "+passed+"; covered parallel ranges, fallback, retry, SHA-256, redirect, authorization, progress and cancellation");
|
||||
}finally{server.stop(0);requests.shutdownNow();}
|
||||
}
|
||||
static void benchmark()throws Exception {
|
||||
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));String address=in.readLine(),expectedHash=in.readLine();long size=Long.parseLong(in.readLine());String auth=in.readLine();
|
||||
for(int connections:new int[]{1,4,1,4,1,4}){File file=file();AtomicInteger events=new AtomicInteger();long began=System.nanoTime();try{int used=new CmvrPackageTransfer(address,Map.of("Authorization",auth),file,size,expectedHash,connections,(p,n,t,c)->events.incrementAndGet()).run();double elapsed=(System.nanoTime()-began)/1e9;System.out.println("{\"requested\":"+connections+",\"connections\":"+used+",\"seconds\":"+elapsed+",\"MiBps\":"+(size/1048576.0/elapsed)+",\"progressEvents\":"+events.get()+",\"sha256Verified\":true}");}finally{file.delete();}}
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,7 @@ import {modules} from '../src/core/modules.ts';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
|
||||
test('only dependency-sensitive mobile pages have concise operation guidance', () => {
|
||||
assert.deepEqual(modules.filter(m=>m.guide).map(m=>m.key), ['arrival','use','move','count','stock','purchase','pending','loans','check','production']);
|
||||
assert.deepEqual(modules.filter(m=>m.guide).map(m=>m.key), ['arrival','use','move','count','stock','purchase','pending','check','production']);
|
||||
for(const m of modules.filter(m=>m.guide)) {
|
||||
assert.ok(m.guide.length <= 80, `${m.key} should not become a manual`);
|
||||
assert.ok(!m.guide.includes('\n'));
|
||||
|
||||
34
mobile-app/tests/package-cache.test.mjs
Normal file
34
mobile-app/tests/package-cache.test.mjs
Normal file
@ -0,0 +1,34 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';
|
||||
import {cachedPackageNames,ignoredPackageMatches,savedPackage,verifyCachedPackage,reusablePackage,fileVerification} from '../src/core/package-cache.ts';
|
||||
const bytes=Buffer.alloc(700000,7),hash=createHash('sha256').update(bytes).digest('hex');
|
||||
const release={sha256:hash,size:bytes.length,versionCode:10,versionName:'1.0.2',environment:'dev',notes:'',downloadPath:`/system/mobile-release/${hash}/content`};
|
||||
const name=hash+'-123-abc.apk';
|
||||
test('a completed private file can reuse its result only with the same immutable identity and file metadata',()=>{
|
||||
const info={exists:true,size:release.size,modificationTime:1700000000000,creationTime:1699999999000},record=savedPackage(release,name,info);assert(reusablePackage(record,release,name,info));
|
||||
for(const changed of [{...info,size:info.size-1},{...info,modificationTime:info.modificationTime+1},{...info,creationTime:info.creationTime+1},{...info,exists:false},{...info,modificationTime:NaN}])assert.equal(reusablePackage(record,release,name,changed),false);
|
||||
for(const changed of [{...record,schema:undefined},{...record,sha256:'a'.repeat(64)},{...record,versionCode:11},{...record,environment:'prod'}])assert.equal(reusablePackage(changed,release,name,info),false);
|
||||
assert.equal(fileVerification({exists:true,size:1}),null);assert.equal(fileVerification({...info,modificationTime:0}),null);
|
||||
});
|
||||
test('finds both recorded and previously orphaned APKs without accepting arbitrary paths or other versions',()=>{
|
||||
const record=savedPackage(release,name),orphan=hash+'-456-def.apk';
|
||||
assert.deepEqual(cachedPackageNames(release,[orphan,'../'+name,'other.apk','a'.repeat(64)+'-123.apk'],record),[name,orphan]);
|
||||
assert.deepEqual(cachedPackageNames(release,[orphan],{...record,environment:'prod'}),[orphan]);
|
||||
assert.throws(()=>savedPackage(release,'file:///cache/'+name),/无效/);
|
||||
assert.equal(cachedPackageNames(release,Array.from({length:50},(_,i)=>hash+'-'+i+'.apk'),null).length,20);
|
||||
});
|
||||
test('cached files must pass fresh SHA-256 verification with bounded reads and progress',async()=>{
|
||||
let offset=0,largest=0;const progress=[];
|
||||
await verifyCachedPackage(release,async length=>{largest=Math.max(largest,length);const part=bytes.subarray(offset,offset+length);offset+=part.length;return part},new AbortController().signal,n=>progress.push(n));
|
||||
assert.equal(largest,256*1024);assert.equal(progress.at(-1),bytes.length);
|
||||
for(const bad of [bytes.subarray(0,bytes.length-1),Buffer.alloc(bytes.length,8),Buffer.alloc(bytes.length+1,7)]){
|
||||
let cursor=0;await assert.rejects(verifyCachedPackage(release,async n=>{const part=bad.subarray(cursor,cursor+n);cursor+=part.length;return part},new AbortController().signal,()=>{}),/校验|大小/);
|
||||
}
|
||||
});
|
||||
test('cancelling a local check never returns a reusable file',async()=>{
|
||||
const abort=new AbortController();await assert.rejects(verifyCachedPackage(release,async()=>{abort.abort();return bytes},abort.signal,()=>{}),/取消/);
|
||||
});
|
||||
test('ignoring a version requires matching environment, native version and immutable package hash',()=>{
|
||||
const record={versionCode:10,sha256:hash,environment:'dev'};assert(ignoredPackageMatches(record,release));
|
||||
for(const other of [{...release,versionCode:11},{...release,sha256:'b'.repeat(64)},{...release,environment:'prod'}])assert.equal(ignoredPackageMatches(record,other),false);
|
||||
assert.equal(ignoredPackageMatches(null,release),false);
|
||||
});
|
||||
70
mobile-app/tests/package-update-native-flow.test.mjs
Normal file
70
mobile-app/tests/package-update-native-flow.test.mjs
Normal file
@ -0,0 +1,70 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';import {createRequire} from 'node:module';import {readFileSync} from 'node:fs';import vm from 'node:vm';
|
||||
import * as core from '../src/core/package-update.ts';import * as native from '../src/core/native-package-download.ts';import {ApiClient} from '../src/core/network.ts';
|
||||
import * as cacheCore from '../src/core/package-cache.ts';import {createHash} from 'node:crypto';
|
||||
const require=createRequire(import.meta.url),ts=require('typescript');
|
||||
function setup(shared={files:new Map(),preferences:new Map()},scope='one',version=10){
|
||||
shared.metadata??=new Map();
|
||||
const bytes=Buffer.alloc(100,7),hash=createHash('sha256').update(bytes).digest('hex');
|
||||
const release={versionCode:version,versionName:'1.0.2',sha256:hash,size:100,notes:'',environment:'dev',downloadPath:'/system/mobile-release/'+hash+'/content'};
|
||||
const slots=[],effects=[];let cursor=0,result,listener,id,options,finish,fail,deleted=0,installed=0,cancelled=0,digests=0,reads=0,signatureChecks=0;
|
||||
const same=(a,b)=>a&&b&&a.length===b.length&&a.every((v,i)=>Object.is(v,b[i]));
|
||||
const react={useState:value=>{const i=cursor++;if(!(i in slots))slots[i]=typeof value==='function'?value():value;return[slots[i],next=>slots[i]=typeof next==='function'?next(slots[i]):next]},useRef:value=>{const i=cursor++;return slots[i]??={current:value}},useCallback:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))slots[i]={deps,value:fn};return slots[i].value},useEffect:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))effects.push(()=>{slots[i]?.cleanup?.();slots[i]={deps,cleanup:fn()}})}};
|
||||
const bridge={download:(requestId,value)=>{id=requestId;options=value;return new Promise((resolve,reject)=>{finish=()=>{shared.files.set(value.uri,bytes);resolve({uri:value.uri,sha256:value.sha256,size:value.size,connections:4})};fail=reject})},cancelDownload:()=>{cancelled++;fail?.(Error('cancelled'))},verify:async()=>{signatureChecks++;return true}};
|
||||
class File{constructor(_dir,name){this.name=name;this.uri='file:///cache/app-updates/'+name}get exists(){return shared.files.has(this.uri)}get size(){return shared.files.get(this.uri)?.length??0}create(){shared.files.set(this.uri,Buffer.alloc(0))}info(){if(!this.exists)return{exists:false};let meta=shared.metadata.get(this.uri);if(!meta){meta={modificationTime:1700000000000,creationTime:1700000000000};shared.metadata.set(this.uri,meta)}return{exists:true,size:this.size,...meta}}async digest(algorithm){assert.equal(algorithm,'SHA-256');digests++;return createHash('sha256').update(shared.files.get(this.uri)).digest('hex')}open(mode){if(mode!=='read')throw Error('JS file writing must not run on native path');let offset=0;return{readBytes:async n=>{reads++;const part=shared.files.get(this.uri).subarray(offset,offset+n);offset+=part.length;return part},close(){}}}delete(){shared.files.delete(this.uri);deleted++}async preview(){installed++}}
|
||||
class Directory{get exists(){return true}create(){}list(){return[...shared.files.keys()].map(uri=>new File(this,uri.split('/').at(-1)))}}
|
||||
const preferences={readPreference:async(scope,key)=>shared.preferences.get(scope+'|'+key)||null,savePreference:async(scope,key,value)=>shared.preferences.set(scope+'|'+key,value)};
|
||||
const fileSystem={File,Directory,Paths:{cache:'cache'},FileMode:{ReadOnly:'read'}};
|
||||
const cacheExports={};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/package-cache.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{exports:cacheExports,require:name=>({'expo-file-system':fileSystem,'./core/preferences':preferences,'./core/package-cache':cacheCore}[name])});
|
||||
const api=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>new Response(JSON.stringify({code:200,data:release}),{headers:{'Content-Type':'application/json'}}));api.authenticate('test');
|
||||
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Platform:{OS:'android'},NativeModules:{CmvrApkVerification:bridge},DeviceEventEmitter:{addListener:(_name,fn)=>{listener=fn;return{remove(){listener=null}}}},AppState:{addEventListener:()=>({remove(){}})}},'expo-constants':{default:{expoConfig:{extra:{environment:'dev'}}}},'expo-application':{nativeBuildVersion:'9'},'expo-file-system':fileSystem,'expo/fetch':{},'./core/package-update':core,'./core/native-package-download':native,'./core/preferences':preferences,'./core/package-cache':cacheCore,'./package-cache':cacheExports,'./ui':{},'./typography':{},'./UpdateNotes':{UpdateNotes:'UpdateNotes'}};
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/PackageUpdates.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText,exports={};vm.runInNewContext(code,{exports,require:name=>Object.hasOwn(mocks,name)?mocks[name]:require(name),AbortController,Date,Number,Math,setTimeout,clearTimeout});
|
||||
const render=()=>{cursor=0;result=exports.usePackageUpdates(api,scope,true);while(effects.length)effects.shift()();return result};
|
||||
return{render,api,release,shared,emit:(phase,bytes)=>listener?.({id,phase,bytes,total:100,connections:4}),finish:()=>finish(),options:()=>options,state:()=>({deleted,installed,cancelled,digests,reads,signatureChecks}),get:()=>result};
|
||||
}
|
||||
const settle=()=>new Promise(r=>setTimeout(r,5));
|
||||
test('update hook uses the native engine, renders real progress and installs only after native verification',async()=>{
|
||||
const h=setup();h.render();await settle();let c=h.render();assert.equal(c.release.versionCode,10);c.download();await settle();
|
||||
assert.equal(h.options().headers.Authorization,'Bearer test');h.emit('downloading',42);c=h.render();assert.equal(c.progress,42);assert.equal(c.transfer.connections,4);assert.equal(c.phase,'downloading');
|
||||
h.emit('verifying',80);c=h.render();assert.equal(c.phase,'verifying');assert.equal(c.verifyProgress,80);assert.equal(h.state().installed,0);
|
||||
h.finish();await settle();c=h.render();assert.equal(c.phase,'ready');assert.equal(c.progress,100);c.install();await settle();assert.equal(h.state().installed,1);assert.equal(h.state().deleted,0);
|
||||
});
|
||||
test('account change cancels the active native transfer and discards its partial file',async()=>{
|
||||
const h=setup();h.render();await settle();h.render().download();await settle();h.emit('downloading',42);h.api.clear();await settle();const c=h.render();assert.equal(c.phase,'idle');assert.ok(h.state().cancelled>0);assert.equal(h.state().deleted,1);assert.equal(h.state().installed,0);
|
||||
});
|
||||
test('completed download survives a full hook restart and goes straight to install without network download',async()=>{
|
||||
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();assert.equal(h.render().phase,'ready');
|
||||
const restarted=setup(h.shared);restarted.render();await settle();const c=restarted.render();assert.equal(c.phase,'ready');assert.equal(c.progress,100);assert.equal(restarted.options(),undefined);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);assert.equal(restarted.state().signatureChecks,0);c.install();await settle();assert.equal(restarted.state().installed,1);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().signatureChecks,1);
|
||||
});
|
||||
test('complete packages from the previous implementation are recovered even without a saved download record',async()=>{
|
||||
const h=setup();const name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.render();await settle();assert.equal(h.render().phase,'ready');assert.equal(h.options(),undefined);assert.equal(h.state().digests,1);assert.equal(h.state().reads,0);
|
||||
});
|
||||
test('old completion records migrate using one native hash, then restart without rereading the APK',async()=>{
|
||||
const h=setup(),name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.shared.preferences.set('one|downloaded-package',cacheCore.savedPackage(h.release,name));
|
||||
h.render();await settle();assert.equal(h.render().phase,'ready');assert.equal(h.state().digests,1);assert.equal(h.state().reads,0);assert.equal(h.shared.preferences.get('one|downloaded-package').schema,2);
|
||||
const restarted=setup(h.shared);restarted.render();await settle();assert.equal(restarted.render().phase,'ready');assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
|
||||
});
|
||||
test('changed metadata revalidates the file and corruption never bypasses the recorded completion',async()=>{
|
||||
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();h.render();const uri=h.options().uri;
|
||||
h.shared.metadata.get(uri).modificationTime++;
|
||||
const changed=setup(h.shared);changed.render();await settle();assert.equal(changed.render().phase,'ready');assert.equal(changed.state().digests,1);
|
||||
h.shared.files.set(uri,Buffer.alloc(100,8));h.shared.metadata.get(uri).modificationTime++;
|
||||
const corrupted=setup(h.shared);corrupted.render();await settle();assert.equal(corrupted.render().phase,'idle');assert.equal(corrupted.state().digests,1);assert.equal(corrupted.state().installed,0);
|
||||
});
|
||||
test('changing a ready file before installation is detected and never opens the installer',async()=>{
|
||||
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();const c=h.render(),uri=h.options().uri;
|
||||
h.shared.files.set(uri,Buffer.alloc(100,8));h.shared.metadata.get(uri).modificationTime++;c.install();await settle();assert.equal(h.render().phase,'idle');assert.equal(h.state().installed,0);assert.equal(h.state().signatureChecks,0);assert.match(h.render().error,/变化/);
|
||||
});
|
||||
test('truncated, corrupted or missing files never restore as ready',async()=>{
|
||||
for(const bad of [null,Buffer.alloc(99,7),Buffer.alloc(100,8)]){const h=setup();if(bad)h.shared.files.set('file:///cache/app-updates/'+h.release.sha256+'-123-abc.apk',bad);h.render();await settle();assert.equal(h.render().phase,'idle');assert.equal(h.state().installed,0);}
|
||||
});
|
||||
test('ignore persists across restarts, manual check still opens the version, newer versions notify again',async()=>{
|
||||
const h=setup();h.render();await settle();let c=h.render();assert.equal(c.visible,true);c.ignoreVersion();await settle();c=h.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);
|
||||
const restarted=setup(h.shared);restarted.render();await settle();c=restarted.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);c.check();await settle();c=restarted.render();assert.equal(c.visible,true);assert.equal(c.release.versionCode,10);
|
||||
const newer=setup(h.shared,'one',11);newer.render();await settle();assert.equal(newer.render().visible,true);assert.equal(newer.render().ignored,false);
|
||||
const otherUser=setup(h.shared,'two');otherUser.render();await settle();assert.equal(otherUser.render().visible,true);
|
||||
});
|
||||
test('ignoring a downloaded version does no file work on startup and manual check reuses its verification',async()=>{
|
||||
const h=setup();h.render();await settle();h.render().download();await settle();h.finish();await settle();h.render().ignoreVersion();await settle();
|
||||
const restarted=setup(h.shared);restarted.render();await settle();let c=restarted.render();assert.equal(c.visible,false);assert.equal(c.ignored,true);assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
|
||||
c.check();await settle();c=restarted.render();assert.equal(c.visible,true);assert.equal(c.phase,'ready');assert.equal(restarted.state().digests,0);assert.equal(restarted.state().reads,0);
|
||||
});
|
||||
@ -1,5 +1,5 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';
|
||||
import {newerPackage,packageVerifier,processPackageChunk,verifyInstalledPackage} from '../src/core/package-update.ts';import {ApiClient} from '../src/core/network.ts';
|
||||
import {newerPackage,packageVerifier,createPackageDownloadProcessor,verifyInstalledPackage} from '../src/core/package-update.ts';import {ApiClient} from '../src/core/network.ts';
|
||||
import {readFileSync} from 'node:fs';import {createRequire} from 'node:module';import vm from 'node:vm';
|
||||
const bytes=Buffer.from('isolated apk bytes'),hash=createHash('sha256').update(bytes).digest('hex');
|
||||
const release={versionCode:4,versionName:'1.2.0',sha256:hash,size:bytes.length,notes:'说明',environment:'dev',downloadPath:`/system/mobile-release/${hash}/content`};
|
||||
@ -13,14 +13,42 @@ test('only the complete byte-for-byte matching package is accepted',()=>{
|
||||
v=packageVerifier(release);v.write(Buffer.alloc(bytes.length,1));assert.throws(()=>v.finish(),/校验/);
|
||||
v=packageVerifier(release);assert.throws(()=>v.write(Buffer.alloc(bytes.length+1)),/大小/);
|
||||
});
|
||||
test('large buffered responses are processed incrementally with real byte progress and cancellation',async()=>{
|
||||
const data=Buffer.alloc(700000,7), parts=[], progress=[], abort=new AbortController();let total=0;
|
||||
await processPackageChunk(data,chunk=>parts.push(Buffer.from(chunk)),n=>{total+=n;progress.push(total)},abort.signal);
|
||||
assert.deepEqual(Buffer.concat(parts),data);assert.deepEqual(progress,[262144,524288,700000]);
|
||||
const cancelled=new AbortController();let written=0;
|
||||
await assert.rejects(processPackageChunk(data,chunk=>{written+=chunk.length},()=>cancelled.abort(),cancelled.signal),/取消/);
|
||||
assert.equal(written,262144);
|
||||
test('small network fragments are coalesced without a timer or render for every fragment',async()=>{
|
||||
const data=Buffer.alloc(700000,7),parts=[],progress=[],abort=new AbortController();let pauses=0;
|
||||
const processor=createPackageDownloadProcessor(chunk=>parts.push(Buffer.from(chunk)),n=>progress.push(n),abort.signal,{now:()=>0,pause:async()=>{pauses++}});
|
||||
for(let offset=0;offset<data.length;offset+=16384)await processor.push(data.subarray(offset,offset+16384));
|
||||
assert.equal(await processor.finish(),data.length);assert.deepEqual(Buffer.concat(parts),data);
|
||||
assert.equal(parts.length,3);assert.ok(parts.every(p=>p.length<=256*1024));assert.equal(pauses,0);
|
||||
assert.deepEqual(progress,[262144,700000]);assert.equal(await processor.finish(),data.length);assert.equal(parts.length,3);
|
||||
});
|
||||
test('processing yields after a CPU work budget, while progress rendering is independently throttled',async()=>{
|
||||
let time=0,writes=0,pauses=0;const progress=[];
|
||||
const processor=createPackageDownloadProcessor(()=>{time+=8;writes++},n=>progress.push(n),new AbortController().signal,{now:()=>time,pause:async()=>{pauses++}});
|
||||
// Idle network time must not force an extra UI delay for every incoming fragment.
|
||||
for(let i=0;i<8;i++){time+=1000;await processor.push(new Uint8Array(256*1024));}
|
||||
await processor.finish();assert.equal(writes,8);assert.equal(pauses,4);
|
||||
const fast=[];const burst=createPackageDownloadProcessor(()=>{},n=>fast.push(n),new AbortController().signal,{now:()=>0});
|
||||
await burst.push(new Uint8Array(2*1024*1024));await burst.finish();assert.equal(fast.length,2);assert.equal(fast.at(-1),2*1024*1024);
|
||||
});
|
||||
test('cancellation stops buffered writes and hashing before the installer can be reached',async()=>{
|
||||
const abort=new AbortController();let written=0;
|
||||
const processor=createPackageDownloadProcessor(chunk=>{written+=chunk.length},()=>abort.abort(),abort.signal);
|
||||
await assert.rejects(processor.push(new Uint8Array(700000)),/取消/);assert.equal(written,262144);
|
||||
await assert.rejects(processor.finish(),/取消/);
|
||||
const trailing=new AbortController();let flushed=false;
|
||||
const tail=createPackageDownloadProcessor(()=>{flushed=true},()=>{},trailing.signal);
|
||||
await tail.push(new Uint8Array(100));trailing.abort();await assert.rejects(tail.finish(),/取消/);assert.equal(flushed,false);
|
||||
});
|
||||
test('coalescing preserves final hash verification and never accepts truncated or changed content',async()=>{
|
||||
const data=Buffer.alloc(700000,7),expected=createHash('sha256').update(data).digest('hex');
|
||||
for(const mode of ['valid','truncated','changed']){
|
||||
const verifier=packageVerifier({size:data.length,sha256:expected});const p=createPackageDownloadProcessor(chunk=>verifier.write(chunk),()=>{},new AbortController().signal);
|
||||
const source=mode==='changed'?Buffer.alloc(data.length,8):mode==='truncated'?data.subarray(0,data.length-1):data;
|
||||
for(let offset=0;offset<source.length;offset+=16384)await p.push(source.subarray(offset,offset+16384));
|
||||
await p.finish();if(mode==='valid')assert.doesNotThrow(()=>verifier.finish());else assert.throws(()=>verifier.finish(),/校验/);
|
||||
}
|
||||
});
|
||||
|
||||
test('native package verification is mandatory before invoking Android installer',async()=>{
|
||||
await assert.rejects(verifyInstalledPackage(undefined,'file:///cache/one.apk',4),/无法验证/);
|
||||
await assert.rejects(verifyInstalledPackage({verify:async()=>false},'file:///cache/one.apk',4),/无法验证/);
|
||||
@ -39,9 +67,9 @@ test('switching account while checking does not lose the new check or show the o
|
||||
const same=(a,b)=>a&&b&&a.length===b.length&&a.every((v,i)=>Object.is(v,b[i]));
|
||||
const react={useState:value=>{const i=cursor++;if(!(i in slots))slots[i]=typeof value==='function'?value():value;return [slots[i],next=>{slots[i]=typeof next==='function'?next(slots[i]):next}]},useRef:value=>{const i=cursor++;return slots[i]??={current:value}},useCallback:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))slots[i]={deps,value:fn};return slots[i].value},useEffect:(fn,deps)=>{const i=cursor++;if(!same(slots[i]?.deps,deps))effects.push(()=>{slots[i]?.cleanup?.();slots[i]={deps,cleanup:fn()}})}};
|
||||
const api={request:()=>new Promise(resolve=>pending.push(resolve))};
|
||||
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Platform:{OS:'android'},AppState:{addEventListener:()=>({remove(){}})}},'expo-constants':{default:{expoConfig:{extra:{environment:'dev'}}}},'expo-application':{nativeBuildVersion:'3'},'expo-file-system':{},'expo/fetch':{},'./core/package-update':{newerPackage,packageVerifier},'./ui':{},'./typography':{}};
|
||||
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Platform:{OS:'android'},AppState:{addEventListener:()=>({remove(){}})}},'expo-constants':{default:{expoConfig:{extra:{environment:'dev'}}}},'expo-application':{nativeBuildVersion:'3'},'expo-file-system':{},'expo/fetch':{},'./core/package-update':{newerPackage,packageVerifier},'./core/native-package-download':{},'./core/preferences':{readPreference:async()=>null},'./core/package-cache':{ignoredPackageMatches:()=>false},'./package-cache':{restorePackage:async()=>null},'./ui':{},'./typography':{},'./UpdateNotes':{UpdateNotes:'UpdateNotes'}};
|
||||
const code=ts.transpileModule(readFileSync(new URL('../src/PackageUpdates.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText,exports={};
|
||||
vm.runInNewContext(code,{exports,require:name=>Object.hasOwn(mocks,name)?mocks[name]:require(name),AbortController,Date,Number,Math});
|
||||
vm.runInNewContext(code,{exports,require:name=>Object.hasOwn(mocks,name)?mocks[name]:require(name),AbortController,Date,Number,Math,setTimeout,clearTimeout});
|
||||
function render(){cursor=0;result=exports.usePackageUpdates(api,scope,true);while(effects.length)effects.shift()();return result;}
|
||||
render();assert.equal(pending.length,1);scope='user-two';render();assert.equal(pending.length,2);
|
||||
pending[0]({data:release});await new Promise(r=>setImmediate(r));render();assert.equal(result.release,null);
|
||||
|
||||
@ -21,7 +21,8 @@ test('publisher signs the exact body, hashes assets, isolates environment, and r
|
||||
assert.equal(verify('RSA-SHA256',body,new X509Certificate(await readFile(certificateFile)).publicKey,Buffer.from(/sig="([^"]+)"/.exec(sig)[1],'base64')),true);
|
||||
assert.equal(first.launchAsset.hash,createHash('sha256').update('test compiled bundle').digest('base64url'));
|
||||
assert.equal(first.assets[0].fileExtension,'.png');assert.match(first.assets[0].url,/^http:\/\/192\.168\.28\.10\/assets\/[a-f0-9]{64}$/);
|
||||
const second=await publishUpdate(options);assert.notEqual(second.id,first.id);assert.equal(second.launchAsset.hash,first.launchAsset.hash);
|
||||
await writeFile(path.join(exportDir,'update-notes.json'),JSON.stringify(['隐藏批次号','更新界面更简洁']));
|
||||
const second=await publishUpdate(options);assert.notEqual(second.id,first.id);assert.equal(second.launchAsset.hash,first.launchAsset.hash);assert.deepEqual(second.metadata.releaseNotes,['隐藏批次号','更新界面更简洁']);
|
||||
assert.equal(JSON.parse(await readFile(path.join(options.root,'dev/android/native-test/current.json'))).id,second.id);
|
||||
await assert.rejects(publishUpdate({...options,environment:'prod'}),/environment mismatch/);
|
||||
await assert.rejects(publishUpdate({...options,runtimeVersion:'incompatible'}),/runtime mismatch/);
|
||||
|
||||
@ -5,17 +5,18 @@ import {createRequire} from 'node:module';
|
||||
import vm from 'node:vm';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
const compiled=ts.transpileModule(readFileSync(new URL('../src/screens/ArrivalListParts.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
|
||||
const result={};vm.runInNewContext(compiled,{exports:result,require:name=>({react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Pressable:'Pressable'},'../typography':{Text:'Text',TextInput:'TextInput'},'../ui':{Icon:'Icon',useTheme:()=>({accent:'blue',muted:'gray',text:'black'})},'../core/modules':{},'../core/arrival-layout':{}}[name]||require(name))});
|
||||
const result={};vm.runInNewContext(compiled,{exports:result,require:name=>({react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Pressable:'Pressable'},'../typography':{Text:'Text',TextInput:'TextInput'},'../ui':{Icon:'Icon',useTheme:()=>({accent:'blue',muted:'gray',text:'black'})},'../core/modules':{},'./ItemIdentity':{},'../core/record-presentation':{},'../core/arrival-layout':{}}[name]||require(name))});
|
||||
test('only-mine control toggles and exposes its state to accessibility',()=>{
|
||||
const values=[];const off=result.OnlyMineToggle({value:false,onChange:v=>values.push(v)});assert.equal(off.props.accessibilityState.checked,false);off.props.onPress();
|
||||
const on=result.OnlyMineToggle({value:true,onChange:v=>values.push(v)});assert.equal(on.props.accessibilityState.checked,true);on.props.onPress();assert.deepEqual(values,[true,false]);
|
||||
assert.equal(result.OnlyMineToggle({value:false,onChange(){},label:'只看本人发起的待入库来源'}).props.accessibilityLabel,'只看本人发起的待入库来源');
|
||||
});
|
||||
test('purchase filter is retained in account-scoped cache and sent for every result page',()=>{
|
||||
const app=readFileSync(new URL('../src/screens/BusinessList.tsx',import.meta.url),'utf8');
|
||||
assert.match(app,/scope\+'\|'\+module\.key\+'\|'\+JSON\.stringify\(initialQuery\)/);
|
||||
assert.match(app,/useState\(cached\.current\?\.onlyMine\?\?false\)/);
|
||||
assert.match(app,/queue:arrivalQueue,compact:compactAmounts,onlyMine/);
|
||||
assert.match(app,/\['arrival','purchase'\]\.includes\(module\.key\)&&onlyMine\?\{onlyMine:true\}/);
|
||||
assert.match(app,/\['arrival','purchase','pending'\]\.includes\(module\.key\)&&onlyMine\?\{onlyMine:true\}/);
|
||||
assert.match(app,/load\(page\+1,appliedQuery\.current,true\)/);
|
||||
assert.match(app,/function clearListForFilter\(\)\{setSelected\(\[\]\);setRows\(\[\]\);setTotal\(0\);setPage\(1\);offset\.current=0/);
|
||||
assert.match(app,/function changeArrivalQueue\(value:[^}]+clearListForFilter\(\);setArrivalQueue\(value\)/);
|
||||
|
||||
48
mobile-app/tests/record-presentation.test.mjs
Normal file
48
mobile-app/tests/record-presentation.test.mjs
Normal file
@ -0,0 +1,48 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';import {createRequire} from 'node:module';import {readFileSync} from 'node:fs';import vm from 'node:vm';
|
||||
import * as presentation from '../src/core/record-presentation.ts';import {modules,recordDisplay} from '../src/core/modules.ts';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
test('primary identity reads stock and purchase aliases without losing zero quantities, model or brand',()=>{
|
||||
assert.deepEqual(presentation.itemIdentity({productName:'电机',spec:'M-20',brand:'品牌甲'}),{name:'电机',spec:'M-20',brand:'品牌甲',batchName:'—',batchNo:'—',supplier:'—'});
|
||||
const item=presentation.itemIdentity({materialName:'',productName:'电机',materialParams:'',productSpec:'M-20',productBrand:'品牌乙',purchaseBatchName:'机器人关节采购',purchaseBatchNo:'CG01',supplierName:'供应商甲'},true);
|
||||
assert.equal(item.name,'电机');assert.equal(item.spec,'M-20');assert.equal(item.brand,'品牌乙');assert.equal(item.batchName,'机器人关节采购');assert.equal(item.supplier,'供应商甲');
|
||||
assert.equal(presentation.recordQuantity(0),'0');assert.equal(presentation.recordQuantity('1234567.2500'),'1,234,567.25');assert.equal(presentation.recordQuantity(null),'—');
|
||||
});
|
||||
test('compact font roles have a clear hierarchy and layouts adapt without multiplying native text scale',()=>{
|
||||
assert.equal(presentation.recordType.title.fontSize,14);assert.equal(presentation.recordType.body.fontSize,12.5);assert.equal(presentation.recordType.quantity.fontSize,16);
|
||||
for(const width of [320,360,393,480])for(const scale of [1,1.22,1.6,2]){const layout=presentation.recordLayout(width,scale);if((width-52)/scale<215)assert(layout.stackedDetails);assert(layout.labelWidth>=52*scale);}
|
||||
});
|
||||
test('money permissions are preserved in secondary details and stock location remains visible',()=>{
|
||||
const purchase=modules.find(m=>m.key==='purchase');assert(!presentation.recordFields(purchase,false,false).secondary.some(([key])=>key==='finalUnitPrice'));assert(presentation.recordFields(purchase,false,true).secondary.some(([key])=>key==='finalUnitPrice'));
|
||||
assert(!presentation.recordFields(purchase,true,true).secondary.some(([key])=>key==='actualAmount'));
|
||||
assert.deepEqual(presentation.recordFields(modules.find(m=>m.key==='stock'),false,false).primary.map(([key])=>key),['projectName','areaName']);
|
||||
assert.equal(presentation.recordFields(modules.find(m=>m.key==='check'),false,false).quantityKey,'realNum');
|
||||
});
|
||||
function compile(name,imports){const exports={};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/screens/'+name,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText,{exports,require:name=>Object.hasOwn(imports,name)?imports[name]:require(name)});return exports;}
|
||||
function render({width=393,fontScale=1,reading=1,more=false}={}){
|
||||
const theme={bg:'#f4f6fb',card:'#fff',text:'#1f3048',muted:'#607089',line:'#e6ebf3',accent:'#2b61df',soft:'#edf2ff'};
|
||||
const imports={react:{...React,useState:()=>[more,()=>{}]},'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Pressable:'Pressable',useWindowDimensions:()=>({width,fontScale})},'../typography':{Text:'Text',useReadingScale:()=>reading},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>theme},'../core/modules':{recordDisplay},'../core/record-presentation':presentation};
|
||||
const identity=compile('ItemIdentity.tsx',imports);imports['./ItemIdentity']=identity;const card=compile('RecordCard.tsx',imports);
|
||||
function flatten(element){const out=[];function walk(node){if(node==null||typeof node==='boolean')return;if(typeof node==='string'||typeof node==='number'){out.push(node);return}if(typeof node.type==='function'){walk(node.type(node.props));return}out.push(node);React.Children.toArray(node.props?.children).forEach(walk)}walk(element);return out}
|
||||
return {identity,card,flatten};
|
||||
}
|
||||
test('real stock and purchase cards show all key fields without expanding and keep long names unrestricted',()=>{
|
||||
for(const width of [320,393,480])for(const fontScale of [1,1.6]){
|
||||
const {card,flatten}=render({width,fontScale}),item={productName:'人形机器人高精度关节电机',materialName:'人形机器人高精度关节电机',spec:'MOTOR-LONG-EXACT-SPEC',materialParams:'MOTOR-LONG-EXACT-SPEC',brand:'品牌甲',materialBrand:'品牌甲',stockNum:12,quantity:12,unit:'个',projectName:'研发项目',areaName:'A-01',purchaseBatchName:'二季度机器人采购',purchaseBatchNo:'CG-2026-001',supplierName:'设备供应商有限公司',purchaseStatus:3};
|
||||
for(const key of ['stock','purchase']){const all=flatten(card.RecordCard({module:modules.find(m=>m.key===key),item,compactAmounts:false,canViewQuotes:false}));const text=all.filter(x=>typeof x!=='object').join(' ');
|
||||
for(const value of ['人形机器人高精度关节电机','MOTOR-LONG-EXACT-SPEC','品牌甲','12','个'])assert(text.includes(value),key+'/'+value);
|
||||
if(key==='purchase')for(const value of ['二季度机器人采购','设备供应商有限公司','部分到货'])assert(text.includes(value),value);
|
||||
assert(!text.includes('CG-2026-001'));const model=all.find(x=>x.type==='Text'&&x.props.children==='MOTOR-LONG-EXACT-SPEC');assert.equal(model.props.style.fontSize,11.5);
|
||||
const title=all.find(x=>x.type==='Text'&&x.props.style?.fontSize===14);assert(title);assert.equal(title.props.numberOfLines,undefined);assert(all.filter(x=>x.type==='Text').every(x=>x.props.style.fontSize<=16));
|
||||
}
|
||||
}
|
||||
});
|
||||
test('batch numbers are hidden even when a batch name is missing or secondary fields expand',()=>{
|
||||
const {card,flatten}=render({more:true});for(const key of ['purchase','pending','in']){
|
||||
const all=flatten(card.RecordCard({module:modules.find(m=>m.key===key),item:{materialName:'物品',productName:'物品',purchaseBatchNo:'CG-HIDDEN-001'},compactAmounts:false,canViewQuotes:true}));
|
||||
assert(!all.filter(x=>typeof x!=='object').join(' ').includes('CG-HIDDEN-001'));
|
||||
}
|
||||
});
|
||||
test('expanded purchase details still never render quoted money for an ordinary user',()=>{
|
||||
const {card,flatten}=render({more:true}),all=flatten(card.RecordCard({module:modules.find(m=>m.key==='purchase'),item:{materialName:'测试物品',quantity:1,finalUnitPrice:'987654.321',actualUnitPrice:12},compactAmounts:false,canViewQuotes:false}));
|
||||
const text=all.filter(x=>typeof x!=='object').join(' ');assert(!text.includes('987654.321'));assert(text.includes('12'));
|
||||
});
|
||||
@ -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','AppUpdates.tsx','AppUpdateDialog.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/ArrivalListParts.tsx','screens/ServerConnection.tsx','screens/BusinessList.tsx','screens/BatchOperation.tsx','screens/NoticeContent.tsx','screens/FileLibrary.tsx','controls/Choice.tsx','controls/DateField.tsx']){
|
||||
for(const file of ['App.tsx','AppUpdates.tsx','AppUpdateDialog.tsx','VersionUpdates.tsx','UpdateNotes.tsx','PackageUpdates.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/ArrivalListParts.tsx','screens/ServerConnection.tsx','screens/BusinessList.tsx','screens/BatchOperation.tsx','screens/NoticeContent.tsx','screens/FileLibrary.tsx','controls/Choice.tsx','controls/DateField.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);
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
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';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
const imports={'./typography':{Text:'Text'},react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Modal:'Modal',View:'View',Text:'Text',ScrollView:'ScrollView'},'./ui':{Button:'Button',Icon:'Icon',Note:'Note',useTheme:()=>({})}};
|
||||
const imports={'./typography':{Text:'Text'},'./UpdateNotes':{UpdateNotes:'UpdateNotes'},react:React,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Modal:'Modal',View:'View',Text:'Text',ScrollView:'ScrollView'},'./ui':{Button:'Button',Icon:'Icon',Note:'Note',useTheme:()=>({})}};
|
||||
const module={exports:{}};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/AppUpdateDialog.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText,{module,exports:module.exports,require:n=>imports[n]||require(n)});
|
||||
function render(patch={}){const called=[];const tree=module.exports.AppUpdateDialog({view:{state:'ready',visible:true,restarting:false,error:'',...patch},later:()=>called.push('later'),restart:()=>called.push('restart')});const nodes=[];function walk(n){if(!n||typeof n!=='object')return;nodes.push(n);React.Children.toArray(n.props?.children).forEach(walk);}walk(tree);return {tree,nodes,called};}
|
||||
test('the update popup waits for readiness and exposes explicit postpone/restart actions',()=>{
|
||||
|
||||
51
mobile-app/tests/version-updates.test.mjs
Normal file
51
mobile-app/tests/version-updates.test.mjs
Normal file
@ -0,0 +1,51 @@
|
||||
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 {updateNotes,manifestUpdateNotes} from '../src/core/update-notes.ts';
|
||||
import {checkVersionUpdate} from '../src/core/version-update.ts';
|
||||
import {createUpdateController} from '../src/core/updates.ts';
|
||||
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
|
||||
|
||||
test('release notes become clean bullet items without damaging semantic versions or duplicating existing bullets',()=>{
|
||||
assert.deepEqual(updateNotes('更新说明:\n1. 升级至 1.0.4\n2、改善下载进度\n• 修复布局\n• 修复布局'),['升级至 1.0.4','改善下载进度','修复布局']);
|
||||
assert.deepEqual(updateNotes('优化下载;缩小字号;完善更新提示'),['优化下载','缩小字号','完善更新提示']);
|
||||
assert.deepEqual(updateNotes(['• 第一项','- 第二项']),['第一项','第二项']);assert.deepEqual(updateNotes(null),[]);assert.deepEqual(updateNotes({text:'错误格式'}),[]);
|
||||
assert.deepEqual(manifestUpdateNotes({metadata:{releaseNotes:['优化界面']}}),['优化界面']);assert.deepEqual(manifestUpdateNotes({metadata:null}),[]);
|
||||
});
|
||||
test('hot update notes come from the actually fetched release, never a changed check response',async()=>{
|
||||
let view;const controller=createUpdateController({isEnabled:true,checkForUpdateAsync:async()=>({isAvailable:true,manifest:{metadata:{releaseNotes:['过时版本']}}}),fetchUpdateAsync:async()=>({isNew:true,manifest:{metadata:{releaseNotes:['实际下载版本']}}}),reloadAsync:async()=>{}},v=>view=v);
|
||||
await controller.check();assert.deepEqual(view.notes,['实际下载版本']);assert.equal(view.state,'ready');assert.equal(view.visible,true);
|
||||
});
|
||||
test('one check prefers an installable version, can reopen ignored versions and falls back to the application update',async()=>{
|
||||
for(const [available,result,expected]of [[true,{release:{versionName:'1.0.4'},error:''},['package','defer']],[true,{release:null,error:''},['package','application']],[false,null,['application']],[true,{release:null,error:'离线'},['package']],[true,undefined,['package']]]){
|
||||
const calls=[];const answer=await checkVersionUpdate({available,check:async()=>{calls.push('package');return result}},{check:async()=>{calls.push('application')},later:()=>calls.push('defer')});assert.deepEqual(calls,expected);assert.equal(answer.error,result?.error||'');
|
||||
}
|
||||
});
|
||||
function compile(name,imports){const exports={};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/'+name,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText,{exports,require:n=>Object.hasOwn(imports,n)?imports[n]:require(n)});return exports}
|
||||
function components(){
|
||||
const imports={react:{...React,useState:value=>[value,()=>{}],useRef:value=>({current:value})},'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Modal:'Modal',ScrollView:'ScrollView'},'expo-application':{nativeApplicationVersion:'1.0.3'},'expo-constants':{default:{expoConfig:{version:'9.9.9'}}},'./typography':{Text:'Text'},'./ui':{Button:'Button',Card:'Card',Heading:'Heading',Icon:'Icon',Note:'Note',useTheme:()=>({})},'./core/update-notes':{updateNotes}};
|
||||
const notes=compile('UpdateNotes.tsx',imports);imports['./UpdateNotes']=notes;
|
||||
Object.assign(imports,{'./core/package-update':{},'./core/native-package-download':{},'./core/preferences':{},'./core/package-cache':{},'./package-cache':{},'expo-file-system':{},'expo/fetch':{}});
|
||||
const packages=compile('PackageUpdates.tsx',imports);imports['./PackageUpdates']=packages;imports['./AppUpdates']={AppUpdateDialog:'AppUpdateDialog'};imports['./core/version-update']={checkVersionUpdate};
|
||||
const version=compile('VersionUpdates.tsx',imports);
|
||||
function flatten(tree){const all=[];function walk(n){if(n==null||typeof n==='boolean')return;if(typeof n!=='object'){all.push(n);return}if(typeof n.type==='function'){walk(n.type(n.props));return}all.push(n);React.Children.toArray(n.props.children).forEach(walk)}walk(tree);return all}
|
||||
return{version,packages,notes,flatten};
|
||||
}
|
||||
const controls=()=>({release:{versionName:'1.0.4',versionCode:12,size:27000000,notes:'优化布局;修复下载进度'},visible:true,available:true,checked:true,phase:'idle',progress:42,verifyProgress:70,transfer:{bytes:12000000,total:27000000,bytesPerSecond:8000000,remainingSeconds:2,connections:4},error:'',ignored:false,check:async()=>{},later(){},ignoreVersion(){},download(){},install(){}});
|
||||
test('a single dialog waits for both checks and dismissing a package also defers a pending hot update',()=>{
|
||||
const {version}=components(),calls=[],packages={...controls(),later:()=>calls.push('package-later'),ignoreVersion:()=>calls.push('ignore')},updates={later:()=>calls.push('application-later'),view:{visible:true}};
|
||||
assert.equal(version.VersionUpdateDialog({enabled:false,packages,updates}),null);assert.equal(version.VersionUpdateDialog({enabled:true,packages:{...packages,checked:false},updates}),null);
|
||||
const chosen=version.VersionUpdateDialog({enabled:true,packages,updates});chosen.props.control.later();assert.deepEqual(calls,['application-later','package-later']);chosen.props.control.ignoreVersion();assert.deepEqual(calls.slice(2),['application-later','ignore']);
|
||||
assert.equal(version.VersionUpdateDialog({enabled:true,packages:{...packages,visible:false},updates}).type,'AppUpdateDialog');
|
||||
});
|
||||
test('settings expose one version entry, one check button and the installed native version',()=>{
|
||||
const {version,flatten}=components(),all=flatten(version.VersionUpdateStatus({packages:controls(),updates:{enabled:true,view:{state:'current'},text:'已是最新版本'}}));
|
||||
assert.equal(all.filter(n=>n.type==='Heading'&&n.props.children==='版本更新').length,1);assert.deepEqual(all.filter(n=>n.type==='Button').map(n=>n.props.title),['检查更新']);const text=all.filter(n=>typeof n!=='object').join(' ');assert(text.includes('1.0.3'));assert(!text.includes('9.9.9'));
|
||||
});
|
||||
test('download popup contains real progress and bullet notes, hides transfer internals and keeps cancel available',()=>{
|
||||
const {packages,flatten}=components();for(const phase of ['downloading','verifying']){
|
||||
const all=flatten(packages.PackageUpdateDialog({control:{...controls(),phase}})),text=all.filter(n=>typeof n!=='object').join(' ');
|
||||
assert(!/并行|测速|MB\/s|路下载|通道/.test(text));assert(text.includes('1.0.3 → 1.0.4'));assert(text.includes('优化布局'));assert(text.includes('修复下载进度'));
|
||||
assert.equal(all.find(n=>n.props?.accessibilityRole==='progressbar').props.accessibilityValue.now,phase==='downloading'?42:70);
|
||||
assert.deepEqual(all.filter(n=>n.type==='Button').map(n=>n.props.title),['取消下载']);assert.equal(all.filter(n=>n.type==='View'&&n.props.style?.width===4).length,2);
|
||||
}
|
||||
const calls=[],all=flatten(packages.PackageUpdateDialog({control:{...controls(),phase:'ready',install:()=>calls.push('install')}}));all.find(n=>n.type==='Button'&&n.props.title==='立即安装').props.onPress();assert.deepEqual(calls,['install']);assert(!all.some(n=>n.props?.accessibilityRole==='progressbar'));
|
||||
});
|
||||
@ -13,6 +13,7 @@ import com.ruoyi.project.domain.ProjectLoan;
|
||||
import com.ruoyi.common.utils.poi.ExcelUtil;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@org.springframework.boot.autoconfigure.condition.ConditionalOnProperty(name="features.project-loans", havingValue="true")
|
||||
@RestController @RequestMapping("/project/loans") public class ProjectLoanController extends BaseController {
|
||||
@Autowired private ProjectLoanService service;
|
||||
public record Borrow(Long lenderProjectId,Long borrowerProjectId,Long itemId,Long fromAreaId,Long toAreaId,BigDecimal quantity,String key,String remark,java.time.LocalDate date){}
|
||||
|
||||
@ -0,0 +1,14 @@
|
||||
package com.ruoyi.web.controller.system;
|
||||
import com.ruoyi.common.annotation.Log;
|
||||
import com.ruoyi.common.core.domain.AjaxResult;
|
||||
import com.ruoyi.common.enums.BusinessType;
|
||||
import com.ruoyi.system.service.impl.MobilePackageService;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@RestController @RequestMapping("/system/mobile-release/packages")
|
||||
public class MobilePackageController {
|
||||
private final MobilePackageService packages;
|
||||
public MobilePackageController(MobilePackageService packages){this.packages=packages;}
|
||||
@GetMapping public AjaxResult list(@RequestParam(defaultValue="")String keyword,@RequestParam(defaultValue="1")int page,@RequestParam(defaultValue="20")int size){return AjaxResult.success(packages.page(keyword,page,size));}
|
||||
@PostMapping("/migrate-library") @Log(title="整理App安装包",businessType=BusinessType.UPDATE) public AjaxResult migrate(){return AjaxResult.success(packages.migrateLibrary());}
|
||||
@DeleteMapping("/{id}") @Log(title="删除App安装包",businessType=BusinessType.DELETE) public AjaxResult remove(@PathVariable String id){packages.remove(id);return AjaxResult.success();}
|
||||
}
|
||||
@ -14,5 +14,10 @@ public class MobileReleaseController {
|
||||
public record Publish(String fileId,String notes){}
|
||||
@PostMapping @Log(title="发布App安装包",businessType=BusinessType.UPDATE)
|
||||
public AjaxResult publish(@RequestBody Publish value){return AjaxResult.success(releases.publish(value.fileId(),value.notes()));}
|
||||
@GetMapping("/{hash}/content") public ResponseEntity<StreamingResponseBody> content(@PathVariable String hash){var file=releases.open(hash);return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/vnd.android.package-archive")).contentLength(file.size()).cacheControl(CacheControl.noStore()).header("Content-Disposition","attachment; filename=cmvr-update.apk").header("X-Content-Type-Options","nosniff").body(out->{try(var in=file.input()){in.transferTo(out);}});}
|
||||
public ResponseEntity<StreamingResponseBody> content(String hash){return content(hash,null);}
|
||||
@GetMapping("/{hash}/content") public ResponseEntity<StreamingResponseBody> content(@PathVariable String hash,@RequestHeader(value="Range",required=false) String range){
|
||||
var response=ResponseEntity.status(range==null?HttpStatus.OK:HttpStatus.PARTIAL_CONTENT).contentType(MediaType.parseMediaType("application/vnd.android.package-archive")).cacheControl(CacheControl.noStore()).header("Accept-Ranges","bytes").header("Content-Disposition","attachment; filename=cmvr-update.apk").header("X-Content-Type-Options","nosniff");
|
||||
if(range!=null){var file=releases.openRange(hash,range);return response.contentLength(file.length()).header("Content-Range","bytes "+file.start()+"-"+(file.start()+file.length()-1)+"/"+file.size()).body(out->{try(var in=file.input()){in.transferTo(out);}});}
|
||||
var file=releases.open(hash);return response.contentLength(file.size()).body(out->{try(var in=file.input()){in.transferTo(out);}});
|
||||
}
|
||||
}
|
||||
|
||||
@ -127,11 +127,17 @@ public class PurchaseRequestController extends BaseController
|
||||
public void inquiryExport(Long id,String version,HttpServletResponse response)throws Exception {
|
||||
inquiryExport(id,version,null,response);
|
||||
}
|
||||
public record InquiryExportSelection(java.util.List<Long> rowIds) { }
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:export,warehouse:purchase:manage')")
|
||||
@PostMapping("/sheet/{id}/inquiry-export") @Log(title="导出供应商询价单",businessType=BusinessType.EXPORT)
|
||||
public void inquiryExport(@PathVariable Long id,@org.springframework.web.bind.annotation.RequestParam String version,@org.springframework.web.bind.annotation.RequestParam(required=false) String selectedColumns,HttpServletResponse response)throws Exception {
|
||||
public void inquiryExport(Long id,String version,String selectedColumns,HttpServletResponse response)throws Exception {
|
||||
inquiryExport(id,version,selectedColumns,null,response);
|
||||
}
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:export,warehouse:purchase:manage')")
|
||||
@PostMapping("/sheet/{id}/inquiry-export") @Log(title="导出供应商询价单",businessType=BusinessType.EXPORT,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public void inquiryExport(@PathVariable Long id,@org.springframework.web.bind.annotation.RequestParam String version,@org.springframework.web.bind.annotation.RequestParam(required=false) String selectedColumns,@RequestBody(required=false) InquiryExportSelection selection,HttpServletResponse response)throws Exception {
|
||||
var sheet=sheetService.load(id);
|
||||
if(!java.util.Objects.equals(version,sheet.getVersion()))throw new com.ruoyi.common.exception.ServiceException("采购清单已变化,请刷新后重新导出询价单");
|
||||
if(selection!=null)sheet=SupplierInquiryExport.selected(sheet,selection.rowIds());
|
||||
boolean compactAmounts=PurchaseQuoteAccess.allowed()&&amountDisplaySettings.enabled();
|
||||
if(compactAmounts)sheet.setRows(sheet.getRows().stream().filter(row->row.getFinalUnitPrice()==null||row.getFinalUnitPrice().signum()!=0).toList());
|
||||
sheet=PurchaseQuoteAccess.view(sheet);
|
||||
@ -153,6 +159,8 @@ public class PurchaseRequestController extends BaseController
|
||||
|
||||
@Autowired
|
||||
private IPurchaseBatchService purchaseBatchService;
|
||||
@Autowired
|
||||
private com.ruoyi.warehouse.mapper.PurchaseBatchMapper purchaseBatchMapper;
|
||||
|
||||
@Autowired
|
||||
private IPurchaseArrivalService purchaseArrivalService;
|
||||
@ -363,9 +371,26 @@ public class PurchaseRequestController extends BaseController
|
||||
batch.setCreateBy(Boolean.TRUE.equals(batch.getOnlyMine()) ? com.ruoyi.common.utils.SecurityUtils.getUsername() : null);
|
||||
if(PurchaseQuoteAccess.allowed())com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(batch);
|
||||
else batch.getParams().remove("amountDisplay");
|
||||
var summary = purchaseBatchMapper.selectPurchaseBatchTotals(batch);
|
||||
if (!PurchaseQuoteAccess.allowed() && summary != null) {
|
||||
var actualOnly = new java.util.HashMap<String, Object>();
|
||||
actualOnly.put("actualTotalAmount", summary.get("actualTotalAmount"));
|
||||
summary = actualOnly;
|
||||
}
|
||||
startPage();
|
||||
var rows=purchaseBatchService.selectPurchaseBatchList(batch);
|
||||
var result=getDataTable(rows);result.setRows(rows.stream().map(PurchaseQuoteAccess::view).toList());return result;
|
||||
var result=getDataTable(rows); result.setSummary(summary); result.setRows(rows.stream().map(PurchaseQuoteAccess::view).toList()); return result;
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
@Log(title = "采购批次备注", businessType = BusinessType.UPDATE)
|
||||
@PutMapping("/batch/{id}/remark")
|
||||
public AjaxResult updateBatchRemark(@PathVariable Long id, @RequestBody java.util.Map<String, String> body)
|
||||
{
|
||||
String remark = body.getOrDefault("remark", "");
|
||||
if (remark == null) remark = "";
|
||||
if (remark.length() > 500) return error("备注不能超过500字");
|
||||
return toAjax(purchaseBatchMapper.updateBatchRemark(id, remark, com.ruoyi.common.utils.SecurityUtils.getUsername()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
|
||||
@ -22,6 +22,14 @@ public final class SupplierInquiryExport {
|
||||
return !Boolean.TRUE.equals(row.getHistorical()) && !Integer.valueOf(5).equals(row.getPurchaseStatus())
|
||||
&& (row.getReceivedQuantity() == null || row.getReceivedQuantity().signum() <= 0);
|
||||
}
|
||||
public static PurchaseSheet selected(PurchaseSheet purchase,List<Long> rowIds) {
|
||||
if(rowIds==null || rowIds.isEmpty() || rowIds.size()>2000 || rowIds.stream().anyMatch(id->id==null||id<=0))
|
||||
throw new ServiceException("请选择1至2000条采购明细后导出");
|
||||
var ids=new LinkedHashSet<>(rowIds);
|
||||
var rows=purchase.getRows().stream().filter(row->ids.contains(row.getId())).toList();
|
||||
if(rows.size()!=ids.size())throw new ServiceException("所选明细不属于当前批次或已被删除,请刷新后重新选择");
|
||||
var result=new PurchaseSheet();result.setBatch(purchase.getBatch());result.setVersion(purchase.getVersion());result.setRows(rows);return result;
|
||||
}
|
||||
public static List<Item> items(PurchaseSheet sheet) {
|
||||
Map<String,List<PurchaseRequest>> groups = new LinkedHashMap<>();
|
||||
for (var row : sheet.getRows()) {
|
||||
@ -77,18 +85,17 @@ public final class SupplierInquiryExport {
|
||||
if(!COLUMN_KEYS.contains(key)) throw new ServiceException("询价单导出列无效,请重新选择");
|
||||
selected.add(key);
|
||||
}
|
||||
if(!selected.contains("quoteUnitPrice")) throw new ServiceException("报价单价是回填必需列,请保留");
|
||||
}
|
||||
var items = items(purchase);
|
||||
if (items.isEmpty()) throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填");
|
||||
var book = new XSSFWorkbook(); var sheet = book.createSheet("供应商询价单"); sheet.setDisplayGridlines(false);
|
||||
var font = book.createFont(); font.setFontName("Arial"); font.setFontHeightInPoints((short)11);
|
||||
var body = book.createCellStyle(); body.setFont(font); body.setVerticalAlignment(VerticalAlignment.CENTER); body.setWrapText(true);
|
||||
var body = book.createCellStyle(); body.setFont(font); body.setAlignment(HorizontalAlignment.CENTER); body.setVerticalAlignment(VerticalAlignment.CENTER); body.setWrapText(true);
|
||||
var titleFont = book.createFont(); titleFont.setFontName("Arial"); titleFont.setFontHeightInPoints((short)16); titleFont.setBold(true);
|
||||
var title = book.createCellStyle(); title.setFont(titleFont);
|
||||
var title = book.createCellStyle(); title.cloneStyleFrom(body);title.setFont(titleFont);
|
||||
var headerFont = book.createFont(); headerFont.setFontName("Arial"); headerFont.setColor(IndexedColors.WHITE.getIndex()); headerFont.setBold(true);
|
||||
var headerStyle = book.createCellStyle(); headerStyle.cloneStyleFrom(body); headerStyle.setFont(headerFont); headerStyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerStyle.setAlignment(HorizontalAlignment.CENTER);
|
||||
var numeric = book.createCellStyle(); numeric.cloneStyleFrom(body); numeric.setAlignment(HorizontalAlignment.RIGHT); numeric.setDataFormat(book.createDataFormat().getFormat("#,##0.00####"));
|
||||
var numeric = book.createCellStyle(); numeric.cloneStyleFrom(body); numeric.setDataFormat(book.createDataFormat().getFormat("#,##0.00####"));
|
||||
var wholeQuantity = book.createCellStyle(); wholeQuantity.cloneStyleFrom(numeric);wholeQuantity.setDataFormat(book.createDataFormat().getFormat("#,##0"));
|
||||
var fractionalQuantity = book.createCellStyle(); fractionalQuantity.cloneStyleFrom(numeric);fractionalQuantity.setDataFormat(book.createDataFormat().getFormat("#,##0.####"));
|
||||
var amount = book.createCellStyle(); amount.cloneStyleFrom(numeric); amount.setDataFormat(book.createDataFormat().getFormat("#,##0.00"));
|
||||
@ -100,7 +107,7 @@ public final class SupplierInquiryExport {
|
||||
context.createCell(0).setCellValue("采购批次"); context.createCell(1).setCellValue(purchase.getBatch().getBatchNo());
|
||||
String supplier=clean(purchase.getBatch().getSupplierName());if(supplier.isEmpty())supplier=purchase.getRows().stream().map(row->clean(row.getSupplierName())).filter(value->!value.isEmpty()).findFirst().orElse("待定");
|
||||
context.createCell(3).setCellValue("供应商"); context.createCell(4).setCellValue(supplier);
|
||||
sheet.createRow(3).createCell(0).setCellValue("填写说明:仅填写黄色报价单价,未报价留空。请保留物品信息及隐藏匹配列,填写后将本文件回传。"+(includeActualAmounts?"实际金额仅供参考,未填齐时留空,不随报价回传修改。":""));
|
||||
sheet.createRow(3).createCell(0).setCellValue((selected.contains("quoteUnitPrice")?"填写说明:仅填写黄色报价单价,未报价留空。请保留物品信息及隐藏匹配列,填写后将本文件回传。":"说明:本次未导出报价单价填写列;如需报价回填,请重新导出时勾选报价单价。")+(includeActualAmounts?"实际金额仅供参考,未填齐时留空,不随报价回传修改。":""));
|
||||
sheet.getRow(3).setHeightInPoints(22);
|
||||
String[] headers = includeActualAmounts?new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","实际单价(元)","实际金额(元)","采购链接","采购批次","物品编码","清单校验","备注"}:new String[]{"序号","物品名称","规格型号","品牌","单位","采购数量","报价单价(元)","报价金额(元)","采购链接","采购批次","物品编码","清单校验","备注"};
|
||||
int[] widths = includeActualAmounts?new int[]{8,26,40,18,9,14,18,18,18,18,38,20,20,68,38}:new int[]{8,26,40,18,9,14,18,18,38,20,20,68,38};
|
||||
@ -115,7 +122,7 @@ public final class SupplierInquiryExport {
|
||||
row.getCell(0).setCellValue(index-5);setText(row.getCell(1),item.name());setText(row.getCell(2),item.spec());
|
||||
setText(row.getCell(3),item.brand());setText(row.getCell(4),item.unit());row.getCell(5).setCellValue(item.quantity().doubleValue());row.getCell(5).setCellStyle(item.quantity().stripTrailingZeros().scale()<=0?wholeQuantity:fractionalQuantity);
|
||||
row.getCell(6).setCellStyle(input);
|
||||
if(selected.contains("quoteAmount"))row.getCell(7).setCellFormula("IF(ISNUMBER(G"+(index+1)+"),ROUND(F"+(index+1)+"*G"+(index+1)+",2),\"\")");row.getCell(7).setCellStyle(amount);
|
||||
if(selected.contains("quoteUnitPrice")&&selected.contains("quoteAmount"))row.getCell(7).setCellFormula("IF(ISNUMBER(G"+(index+1)+"),ROUND(F"+(index+1)+"*G"+(index+1)+",2),\"\")");row.getCell(7).setCellStyle(amount);
|
||||
if(includeActualAmounts) {
|
||||
row.getCell(8).setCellStyle(numeric);row.getCell(9).setCellStyle(amount);
|
||||
if(selected.contains("actualUnitPrice")){if(item.mixedActualPrices())setText(row.getCell(8),"多种实际单价");else if(item.actualUnitPrice()!=null)row.getCell(8).setCellValue(item.actualUnitPrice().doubleValue());}
|
||||
@ -123,6 +130,7 @@ public final class SupplierInquiryExport {
|
||||
}
|
||||
if(selected.contains("link"))setText(row.getCell(linkColumn),item.link());if(selected.contains("remark"))setText(row.getCell(remarkColumn),item.remark());row.getCell(batchColumn).setCellValue(purchase.getBatch().getBatchNo());row.getCell(codeColumn).setCellValue(item.productCode());row.getCell(snapshotColumn).setCellValue(item.snapshot());
|
||||
for(int c=batchColumn;c<=snapshotColumn;c++)row.getCell(c).setCellStyle(text);
|
||||
var idsCell=row.createCell(headers.length);idsCell.setCellValue(item.rowIds().stream().map(String::valueOf).collect(java.util.stream.Collectors.joining(",")));idsCell.setCellStyle(text);
|
||||
index++;
|
||||
}
|
||||
var helper=sheet.getDataValidationHelper();
|
||||
@ -130,11 +138,15 @@ public final class SupplierInquiryExport {
|
||||
validation.setEmptyCellAllowed(true);validation.setShowErrorBox(true);validation.createErrorBox("请填写有效单价","报价单价需为非负数,最多6位小数;不报价请留空。");sheet.addValidationData(validation);
|
||||
sheet.createFreezePane(2,6);sheet.setAutoFilter(new CellRangeAddress(5,index-1,0,remarkColumn));
|
||||
for(int c=batchColumn;c<=snapshotColumn;c++)sheet.setColumnHidden(c,true);
|
||||
var idsHeader=head.createCell(headers.length);idsHeader.setCellValue("采购明细标识");idsHeader.setCellStyle(headerStyle);sheet.setColumnHidden(headers.length,true);
|
||||
for(int c=1;c<keys.length;c++)if(!keys[c].isEmpty()&&!selected.contains(keys[c]))sheet.setColumnHidden(c,true);
|
||||
if(includeActualAmounts && selected.contains("actualAmount")) {
|
||||
var total=sheet.createRow(index);total.setHeightInPoints(28);int labelColumn=selected.contains("actualUnitPrice")?8:selected.contains("quoteAmount")?7:6;total.createCell(labelColumn).setCellValue("实际金额合计");total.getCell(labelColumn).setCellStyle(body);
|
||||
var total=sheet.createRow(index);total.setHeightInPoints(36);int labelColumn=selected.contains("actualUnitPrice")?8:selected.contains("quoteAmount")?7:selected.contains("quoteUnitPrice")?6:selected.contains("name")?1:0;total.createCell(labelColumn).setCellValue("实际金额合计");total.getCell(labelColumn).setCellStyle(body);
|
||||
total.createCell(9).setCellFormula("IF(COUNT(J7:J"+index+")="+items.size()+",SUM(J7:J"+index+"),\"\")");total.getCell(9).setCellStyle(amount);index++;
|
||||
}
|
||||
for(int r:List.of(2,3))for(var cell:sheet.getRow(r))cell.setCellStyle(body);
|
||||
sheet.addMergedRegion(new CellRangeAddress(1,1,0,remarkColumn));
|
||||
sheet.addMergedRegion(new CellRangeAddress(3,3,0,remarkColumn));sheet.getRow(3).setHeightInPoints(44);
|
||||
sheet.setRepeatingRows(new CellRangeAddress(5,5,-1,-1));sheet.getPrintSetup().setLandscape(true);sheet.getPrintSetup().setPaperSize(PrintSetup.A3_PAPERSIZE);sheet.getPrintSetup().setFitWidth((short)1);sheet.getPrintSetup().setFitHeight((short)0);sheet.setFitToPage(true);
|
||||
book.setPrintArea(0,0,remarkColumn,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);
|
||||
return book;
|
||||
|
||||
@ -28,9 +28,21 @@ public final class SupplierQuoteImport {
|
||||
String batch=text(row,columns.get("采购批次"),formatter);if(batch.isEmpty())batch=contextBatch;
|
||||
var item=new LinkedHashMap<String,Object>();item.put("line",n+1);item.put("productCode",code);item.put("name",name);item.put("spec",text(row,columns.get("规格型号"),formatter));item.put("brand",text(row,columns.get("品牌"),formatter));item.put("unit",text(row,columns.get("单位"),formatter));item.put("price",rawPrice);item.put("rowIds",List.of());item.put("unitPrice",null);item.put("skipped",rawPrice.isEmpty());
|
||||
String error=null;
|
||||
var matches=current.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList();
|
||||
var candidates=current;
|
||||
if(columns.containsKey("采购明细标识")) {
|
||||
try {
|
||||
var ids=Arrays.stream(text(row,columns.get("采购明细标识"),formatter).split(",",-1)).map(String::trim).map(Long::valueOf).toList();
|
||||
if(new HashSet<>(ids).size()!=ids.size())throw new IllegalArgumentException();
|
||||
var subset=SupplierInquiryExport.selected(sheet,ids);
|
||||
if(subset.getRows().stream().anyMatch(value->!SupplierInquiryExport.eligible(value)))throw new IllegalArgumentException();
|
||||
candidates=SupplierInquiryExport.items(subset);
|
||||
if(candidates.size()!=1)throw new IllegalArgumentException();
|
||||
}catch(Exception invalid){error="所选采购明细已变化或匹配信息缺失,请重新导出询价单";candidates=List.of();}
|
||||
}
|
||||
var matches=candidates.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList();
|
||||
SupplierInquiryExport.Item match=matches.size()==1?matches.get(0):null;
|
||||
if(!Objects.equals(batch,sheet.getBatch().getBatchNo()))error="采购批次不一致,请回传当前批次的询价单";
|
||||
if(error!=null) { /* Keep the selection error; never widen to the whole batch. */ }
|
||||
else if(!Objects.equals(batch,sheet.getBatch().getBatchNo()))error="采购批次不一致,请回传当前批次的询价单";
|
||||
else if(match==null)error=matches.size()>1?"存在同名物品,请保留原表隐藏列,或补全品牌、规格和单位":"当前批次找不到可回填的物品,或该物品已入库、为历史/取消明细";
|
||||
else {
|
||||
item.put("productCode",match.productCode());item.put("name",match.name());item.put("spec",match.spec());item.put("brand",match.brand());item.put("unit",match.unit());item.put("quantity",match.quantity());item.put("previousPrice",match.previousPrice());item.put("rowIds",match.rowIds());
|
||||
@ -76,7 +88,7 @@ public final class SupplierQuoteImport {
|
||||
case "报价单价(元)","报价单价(元)","报价单价","最终单价" -> "最终单价";
|
||||
case "物品名称","物品","名称" -> "物品名称";
|
||||
case "规格型号","规格","型号" -> "规格型号";
|
||||
case "品牌","单位","采购批次","物品编码","采购数量","清单校验" -> name.replace(" ","");
|
||||
case "品牌","单位","采购批次","物品编码","采购数量","清单校验","采购明细标识" -> name.replace(" ","");
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
@ -311,7 +311,7 @@ public class AssistantModelClient {
|
||||
switch(verb) {
|
||||
case "入库","办理入库","确认入库" -> {action="receipt.receive";question="可以,我来帮你办理入库。你要入库哪项物品、多少数量,放到哪个库区?可以先说物品名称或采购批次;如果还没选好,也可以说‘查看待入库’,我先帮你找。已有信息后可分几次补充,确认前不会改变库存。";}
|
||||
case "到货","登记到货" -> {action="arrival.register";question="可以,我来帮你登记到货。请告诉我到货的物品和本次数量,也可以上传到货单;批次、供应商和规格知道多少说多少,我会先匹配采购明细,再请你核对。登记到货不会自动验收或入库。";}
|
||||
case "领用","出库","项目领用" -> {action="material.issue";question="可以,我来帮你办理领用出库。请告诉我物品、本次数量和所属项目,知道库区也可以一起说;不清楚库存位置可以先查询库存,已经提供的信息不用重复填写。";}
|
||||
case "领用","出库","项目领用" -> {action="material.issue";question="可以,我来帮你办理物料领用。请告诉我物品、本次数量和所属项目,知道库区也可以一起说;不清楚库存位置可以先查询库存,已经提供的信息不用重复填写。";}
|
||||
case "移库","办理移库" -> {action="stock.move";question="可以,我来帮你移库。请告诉我物品、数量,以及从哪个库区移到哪个库区;项目或来源不确定时我会先匹配核对,不会直接变动库存。";}
|
||||
case "盘点","库存盘点" -> {action="stockCheck.create";question="可以,我来帮你登记盘点。请告诉我项目、库区、物品和实际盘点数量;不清楚账面库存可以先查库存,盘点信息可以逐步补充,确认前不会更改库存。";}
|
||||
default -> {return null;}
|
||||
|
||||
@ -1024,6 +1024,8 @@ public class BusinessActionRegistry {
|
||||
private Action action(String key) { Action action=actions.get(key); if(action==null)throw new ServiceException("助手暂不支持该业务操作"); return action; }
|
||||
|
||||
private void register(String key,String label,String description,Class<?> controller,String method,String args,boolean query,Map<String,Object> fixed,Field...fields) {
|
||||
if (key.startsWith("loan.")) return;
|
||||
fields = Arrays.stream(fields).filter(f -> !Set.of("purchasePurpose", "loanId").contains(f.key())).toArray(Field[]::new);
|
||||
List<Method> matches=Arrays.stream(controller.getMethods()).filter(m->m.getName().equals(method)).toList();
|
||||
if(matches.size()!=1)throw new IllegalStateException("Ambiguous action method: "+controller.getName()+"."+method);
|
||||
Method target=matches.get(0); List<String> bindings=args.isBlank()?List.of():List.of(args.split(","));
|
||||
@ -1112,6 +1114,7 @@ public class BusinessActionRegistry {
|
||||
}
|
||||
|
||||
private void export(String key,String label,Class<?> controller,String method,String args,String from) {
|
||||
if(key.startsWith("loan."))return;
|
||||
Field[] fields=from==null?new Field[0]:action(from).fields().stream().filter(field->!Set.of("pageNum","pageSize").contains(field.key())).toArray(Field[]::new);
|
||||
register(key,label,"按当前账号的原页面导出权限和指定筛选生成真实Excel文件,不修改业务;不提供任何数据库或接口执行入口",controller,method,args,true,Map.of(),queryFields(fields));
|
||||
}
|
||||
|
||||
@ -33,7 +33,7 @@ public class ResumableUploadService {
|
||||
@Transactional public Info start(Start input) {
|
||||
if(input==null)throw new ServiceException("请选择文件");
|
||||
int max=targets.authorize(input.target()); requireStorage();
|
||||
String name=Set.of("fileLibrary","noticeAttachment").contains(input.target().purpose())?com.ruoyi.system.service.impl.ManagedFileService.safeName(input.name()):validateName(input.name()); requireHash(input.sha256()); targets.validateName(input.target(),name);
|
||||
String name=Set.of("fileLibrary","noticeAttachment","appRelease").contains(input.target().purpose())?com.ruoyi.system.service.impl.ManagedFileService.safeName(input.name()):validateName(input.name()); requireHash(input.sha256()); targets.validateName(input.target(),name);
|
||||
if(input.size()<=0 || input.size()>max)throw new ServiceException("附件为空或超过当前业务大小限制");
|
||||
long owner=SecurityUtils.getUserId();
|
||||
// Serializes same-owner init/quota checks across tabs AND backend instances.
|
||||
@ -92,7 +92,7 @@ public class ResumableUploadService {
|
||||
int size=((Number)row.get("byte_size")).intValue(), total=total(size);
|
||||
var chunks=db.queryForList("select chunk_index,sha256 from sys_file_upload_chunk where upload_id=? order by chunk_index",id);
|
||||
if(chunks.size()!=total)throw new ServiceException("文件尚未传完,请继续上传剩余分片");
|
||||
if(Set.of("projectDocument","projectArchiveDocument","fileLibrary","noticeAttachment").contains(target.purpose())) {
|
||||
if(Set.of("projectDocument","projectArchiveDocument","fileLibrary","noticeAttachment","appRelease").contains(target.purpose())) {
|
||||
Object result=completeProjectFile(target,id,row,chunks,size);
|
||||
db.update("update sys_file_upload set status='DONE',result_json=? where id=?",encode(result),id);
|
||||
row.put("status","DONE");row.put("result_json",encode(result));return info(row);
|
||||
|
||||
@ -35,6 +35,7 @@ public class UploadTargets {
|
||||
@Autowired private ObjectMapper json;
|
||||
@Autowired private com.ruoyi.common.storage.BusinessFileStorage storage;
|
||||
@Autowired private com.ruoyi.system.service.impl.ManagedFileService managedFiles;
|
||||
@Autowired private com.ruoyi.system.service.impl.MobilePackageService mobilePackages;
|
||||
|
||||
public int authorize(Target target) {
|
||||
if (target == null || target.purpose() == null) throw new ServiceException("请选择附件所属业务");
|
||||
@ -44,6 +45,7 @@ public class UploadTargets {
|
||||
if(user==null || !"0".equals(user.getStatus()) || !"0".equals(user.getDelFlag())) throw new ServiceException("登录状态已失效,请重新登录",401);
|
||||
login.setUser(user); login.setDeptId(user.getDeptId()); login.setPermissions(currentPermissions.getMenuPermission(user));
|
||||
switch (target.purpose()) {
|
||||
case "appRelease" -> {plain(target,false);return mobilePackages.authorize();}
|
||||
case "fileLibrary", "noticeAttachment" -> {
|
||||
plain(target,false);return managedFiles.authorizeUpload(target.purpose().equals("noticeAttachment"));
|
||||
}
|
||||
@ -75,6 +77,7 @@ public class UploadTargets {
|
||||
}
|
||||
}
|
||||
public void validateName(Target target, String name) {
|
||||
if("appRelease".equals(target.purpose())){com.ruoyi.system.service.impl.MobilePackageService.validateName(name);return;}
|
||||
if(Set.of("fileLibrary","noticeAttachment").contains(target.purpose())){com.ruoyi.system.service.impl.ManagedFileService.safeName(name);return;}
|
||||
String extension=name.substring(name.lastIndexOf('.')+1).toLowerCase(Locale.ROOT);
|
||||
Set<String> standard=Set.of("pdf","png","jpg","jpeg","doc","docx","xls","xlsx","txt","zip");
|
||||
@ -93,6 +96,7 @@ public class UploadTargets {
|
||||
public Object finish(Target target, String id, MultipartFile file) {
|
||||
authorize(target);
|
||||
return switch(target.purpose()) {
|
||||
case "appRelease" -> mobilePackages.upload(id,file);
|
||||
case "fileLibrary", "noticeAttachment" -> managedFiles.upload(target.purpose().equals("noticeAttachment"),id,file);
|
||||
case "projectArchiveDocument" -> archiveDocuments.upload(target.targetId(),id,file);
|
||||
case "projectDocument" -> projectDocuments.upload(target.targetId(),id,file);
|
||||
@ -110,6 +114,7 @@ public class UploadTargets {
|
||||
Object id=meta.get("id"); if (id==null) return false;
|
||||
Long owner=SecurityUtils.getUserId();
|
||||
boolean active=switch(target.purpose()) {
|
||||
case "appRelease" -> mobilePackages.alive(id.toString());
|
||||
case "fileLibrary", "noticeAttachment" -> managedFiles.alive(target.purpose().equals("noticeAttachment"),id.toString());
|
||||
case "projectArchiveDocument" -> archiveDocuments.alive(target.targetId(),id.toString());
|
||||
case "projectDocument" -> projectDocuments.alive(target.targetId(),id.toString());
|
||||
@ -121,7 +126,7 @@ public class UploadTargets {
|
||||
default -> false;
|
||||
};
|
||||
if(!active)return false;
|
||||
String area=switch(target.purpose()){case "fileLibrary","noticeAttachment"->"managed-file";case "projectArchiveDocument"->"project-archive";case "projectDocument"->"project-workspace";case "product"->"product";case "purchase"->"purchase";case "supplier"->"supplier-license";case "feedback"->"feedback";default->"assistant";};
|
||||
String area=switch(target.purpose()){case "fileLibrary","noticeAttachment","appRelease"->"managed-file";case "projectArchiveDocument"->"project-archive";case "projectDocument"->"project-workspace";case "product"->"product";case "purchase"->"purchase";case "supplier"->"supplier-license";case "feedback"->"feedback";default->"assistant";};
|
||||
try{return storage.exists(area+"/"+id+".bin",null);}catch(java.io.IOException error){throw new ServiceException("文件存储暂时不可用,请稍后继续");}
|
||||
}
|
||||
private boolean assistantAlive(Object id) { try { return !assistant.available(null,id).isEmpty(); } catch(ServiceException expired) { return false; } }
|
||||
|
||||
@ -85,7 +85,7 @@ class BusinessControllerContractTest {
|
||||
}
|
||||
private static void set(Object target,String field,Object value){ReflectionTestUtils.setField(target,field,value);}
|
||||
private static void authenticate(Set<String> permissions) {
|
||||
var user=new SysUser();user.setUserId(101L);user.setUserName("contract-user");
|
||||
var user=new SysUser();user.setUserId(101L);user.setUserName("contract-user"); var procurementRole = new com.ruoyi.common.core.domain.entity.SysRole(); procurementRole.setRoleKey("purchase_manager"); procurementRole.setStatus("0"); procurementRole.setDelFlag("0"); user.setRoles(java.util.List.of(procurementRole));
|
||||
var login=new LoginUser(101L,1L,user,permissions);
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null,List.of()));
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
package com.ruoyi.projectdev;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.InRecord;
|
||||
import com.ruoyi.warehouse.mapper.InRecordMapper;
|
||||
import com.ruoyi.warehouse.service.impl.PendingReceiptService;
|
||||
import com.ruoyi.warehouse.util.PendingReceiptScope;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
|
||||
import org.apache.ibatis.session.Configuration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
class PendingOnlyMineTest {
|
||||
@Test void sourceCreatorFilterIsBoundToTheLoginAndMatchesPurchaseProductionAndOtherSources()throws Exception{
|
||||
try(var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("me");var q=new InRecord();q.setOnlyMine(true);q.getParams().put("onlyMineUser","another");PendingReceiptScope.bind(q);assertEquals("me",q.getParams().get("onlyMineUser"));
|
||||
var c=new Configuration();c.getTypeAliasRegistry().registerAlias("InRecord",InRecord.class);Path root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve("ruoyi-system")))root=root.getParent();try(var in=Files.newInputStream(root.resolve("ruoyi-system/src/main/resources/mapper/warehouse/InRecordMapper.xml"))){new XMLMapperBuilder(in,c,"in-record",c.getSqlFragments()).parse();}
|
||||
String sql=c.getMappedStatement("com.ruoyi.warehouse.mapper.InRecordMapper.selectInRecordList").getBoundSql(q).getSql().replaceAll("\\s+"," ");String predicate=sql.substring(sql.indexOf("and (case"),sql.indexOf("end)")+4).substring(4);
|
||||
var db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""));db.execute("create table purchase_request(id bigint,create_by varchar(64))");db.execute("create table production_task(id bigint,create_by varchar(64))");db.execute("create table in_record(id bigint,purchase_request_id bigint,production_task_id bigint,operator varchar(64))");db.execute("insert into purchase_request values(1,'me'),(2,'other')");db.execute("insert into production_task values(3,'me'),(4,'other')");db.execute("insert into in_record values(1,1,null,'other'),(2,2,null,'me'),(3,null,3,'other'),(4,null,4,'me'),(5,null,null,'me')");
|
||||
assertEquals(List.of(1L,3L,5L),db.queryForList("select ir.id from in_record ir left join purchase_request purchase on purchase.id=ir.purchase_request_id where "+predicate+" order by ir.id",Long.class,"me","me","me"));
|
||||
q.setOnlyMine(false);PendingReceiptScope.bind(q);assertFalse(q.getParams().containsKey("onlyMineUser"));assertFalse(c.getMappedStatement("com.ruoyi.warehouse.mapper.InRecordMapper.selectInRecordList").getBoundSql(q).getSql().contains("task.create_by"));
|
||||
}
|
||||
}
|
||||
@Test void groupCountsAndExpandedDetailsUseTheSamePersonalFilter(){
|
||||
var db=mock(JdbcTemplate.class);when(db.queryForObject(anyString(),eq(Long.class),any(Object[].class))).thenReturn(0L);var mapper=mock(InRecordMapper.class);when(mapper.selectInRecordList(any())).thenReturn(List.of());var service=new PendingReceiptService();ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"records",mapper);
|
||||
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::getUsername).thenReturn("me");var q=new InRecord();q.setOnlyMine(true);q.getParams().put("onlyMineUser","spoofed");service.page(q,2,20);service.group("B:7",q);assertEquals("me",q.getParams().get("onlyMineUser"));verify(mapper).selectInRecordList(q);for(var call:mockingDetails(db).getInvocations()){assertTrue(((String)call.getArgument(0)).contains("pr.create_by"));assertTrue(Arrays.asList(call.getArguments()).contains("me"));}}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
package com.ruoyi.projectdev;
|
||||
|
||||
import com.ruoyi.project.service.ProjectLoanService;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.math.BigDecimal;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectLoansDisabledTest {
|
||||
@Test void disabledWritesStopBeforeTouchingInventory() {
|
||||
var service = new ProjectLoanService();
|
||||
// No repositories are injected: each operation must stop before any inventory access.
|
||||
assertDisabled(() -> service.borrow(1L, 2L, 3L, 4L, 5L, BigDecimal.ONE, "test", ""));
|
||||
assertDisabled(() -> service.returnStock(1L, 4L, 5L, BigDecimal.ONE, "test"));
|
||||
assertDisabled(() -> service.revokeLoan(1L, "test"));
|
||||
assertDisabled(() -> service.revokeStockReturn(1L, "test", "test"));
|
||||
}
|
||||
private void assertDisabled(org.junit.jupiter.api.function.Executable operation) {
|
||||
assertEquals("借用与归还功能已停用", assertThrows(ServiceException.class, operation).getMessage());
|
||||
}
|
||||
}
|
||||
@ -40,7 +40,7 @@ class PurchaseNamedImportTest
|
||||
@BeforeEach
|
||||
void setup()
|
||||
{
|
||||
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setUserId(7L);user.setUserName("import-manager");
|
||||
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setUserId(7L);user.setUserName("import-manager"); var procurementRole = new com.ruoyi.common.core.domain.entity.SysRole(); procurementRole.setRoleKey("purchase_manager"); procurementRole.setStatus("0"); procurementRole.setDelFlag("0"); user.setRoles(java.util.List.of(procurementRole));
|
||||
var login=new com.ruoyi.common.core.domain.model.LoginUser(7L,1L,user,java.util.Set.of("warehouse:purchase:manage"));
|
||||
org.springframework.security.core.context.SecurityContextHolder.getContext().setAuthentication(new org.springframework.security.authentication.UsernamePasswordAuthenticationToken(login,null));
|
||||
projectRows.add(project(1L, "P001", "机器人项目"));
|
||||
|
||||
@ -30,7 +30,7 @@ class ManagedFileTest {
|
||||
db.execute("create table sys_notice(notice_id int primary key,status varchar(1))");db.execute("insert into sys_notice values(10,'0'),(20,'1')");
|
||||
Path root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve("sql")))root=root.getParent();String sql=Files.readString(root.resolve("sql/projectdev/20261028_notice_files.sql"));sql=sql.substring(0,sql.indexOf("INSERT INTO sys_menu")).replaceAll("(?m)^--.*$","").replace(" ENGINE=InnoDB DEFAULT CHARSET=utf8mb4","");for(String statement:sql.split(";"))if(!statement.isBlank())db.execute(statement);
|
||||
objects=new HashMap<>();storage=mock(BusinessFileStorage.class);when(storage.isEnabled()).thenReturn(true);when(storage.exists(anyString(),isNull())).thenAnswer(c->objects.containsKey(c.getArgument(0)));when(storage.openStream(anyString())).thenAnswer(c->{var bytes=objects.get(c.getArgument(0));if(bytes==null)throw new FileNotFoundException();return new ByteArrayInputStream(bytes);});doAnswer(c->{objects.put(c.getArgument(0),((InputStream)c.getArgument(1)).readAllBytes());return null;}).when(storage).saveStream(anyString(),any(),anyLong(),anyString());doAnswer(c->{objects.remove(c.getArgument(0));return null;}).when(storage).discardFailedUpload(anyString(),isNull());
|
||||
files=new ManagedFileService(db,storage);grants=new HashSet<>(Set.of("system:file:list","system:file:upload","system:file:download","system:file:remove","system:notice:add","system:notice:edit"));security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenAnswer(c->actor);security.when(SecurityUtils::getUsername).thenAnswer(c->"user"+actor);security.when(SecurityUtils::isAdmin).thenAnswer(c->actor==1);security.when(()->SecurityUtils.hasPermi(anyString())).thenAnswer(c->grants.contains(c.getArgument(0)));
|
||||
db.execute("create table sys_mobile_package(file_id varchar(36) primary key)");files=new ManagedFileService(db,storage);grants=new HashSet<>(Set.of("system:file:list","system:file:upload","system:file:download","system:file:remove","system:notice:add","system:notice:edit"));security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenAnswer(c->actor);security.when(SecurityUtils::getUsername).thenAnswer(c->"user"+actor);security.when(SecurityUtils::isAdmin).thenAnswer(c->actor==1);security.when(()->SecurityUtils.hasPermi(anyString())).thenAnswer(c->grants.contains(c.getArgument(0)));
|
||||
}
|
||||
@AfterEach void close(){security.close();}
|
||||
MockMultipartFile document(String name){return new MockMultipartFile("file",name,"application/octet-stream","isolated file bytes".getBytes());}
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
package com.ruoyi.system;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.storage.BusinessFileStorage;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.service.impl.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.*;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class MobilePackageManagementTest {
|
||||
JdbcTemplate db;ManagedFileService files;MobilePackageService packages;MobileReleaseService releases;TransactionTemplate tx;MockedStatic<SecurityUtils> security;Map<String,byte[]> objects;long actor=1;Path root;
|
||||
static final String ID="11111111-1111-4111-8111-111111111111";
|
||||
@BeforeEach void init()throws Exception{
|
||||
root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve("sql")))root=root.getParent();
|
||||
var ds=new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa","");db=new JdbcTemplate(ds);tx=new TransactionTemplate(new DataSourceTransactionManager(ds));
|
||||
db.execute("create table sys_user(user_id bigint primary key,nick_name varchar(64))");db.execute("insert into sys_user values(1,'管理员'),(2,'同事')");
|
||||
db.execute("create table sys_config(config_name varchar(100),config_key varchar(100),config_value varchar(500),config_type varchar(1),create_by varchar(64),create_time timestamp,update_by varchar(64),update_time timestamp)");
|
||||
db.execute("create table sys_managed_file(id varchar(36) primary key,file_kind varchar(16),name varchar(180),byte_size bigint,sha256 varchar(64),owner_id bigint,create_by varchar(64),create_time timestamp default current_timestamp,deleted int default 0,delete_time timestamp)");
|
||||
db.execute("create table sys_mobile_package(file_id varchar(36) primary key,environment varchar(8),version_code bigint,version_name varchar(32),runtime varchar(64),notes varchar(140) default '',published_at timestamp)");
|
||||
objects=new HashMap<>();var storage=mock(BusinessFileStorage.class);when(storage.isEnabled()).thenReturn(true);when(storage.exists(anyString(),isNull())).thenAnswer(c->objects.containsKey(c.getArgument(0)));when(storage.openStream(anyString())).thenAnswer(c->new ByteArrayInputStream(Objects.requireNonNull(objects.get(c.getArgument(0)))));doAnswer(c->{objects.put(c.getArgument(0),((InputStream)c.getArgument(1)).readAllBytes());return null;}).when(storage).saveStream(anyString(),any(),anyLong(),anyString());
|
||||
files=new ManagedFileService(db,storage);releases=new MobileReleaseService(db,storage,new ObjectMapper(),new StandardEnvironment());packages=new MobilePackageService(db,storage,files,releases,tx);security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenAnswer(c->actor==1);security.when(SecurityUtils::getUserId).thenAnswer(c->actor);security.when(SecurityUtils::getUsername).thenAnswer(c->actor==1?"admin":"worker");security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(true);
|
||||
}
|
||||
@AfterEach void close(){security.close();}
|
||||
MockMultipartFile apk()throws Exception{Path source=root.resolve(".codex-tmp/releases/cmvr-wms-dev-1.0.5-v13.apk");Assumptions.assumeTrue(Files.exists(source));return new MockMultipartFile("file","development.apk","application/octet-stream",Files.readAllBytes(source));}
|
||||
@Test void roleOrMenuPermissionsCannotGrantReleaseAdministration(){actor=2;assertThrows(ServiceException.class,packages::authorize);assertThrows(ServiceException.class,()->packages.page("",1,20));assertThrows(ServiceException.class,packages::migrateLibrary);assertThrows(ServiceException.class,()->packages.remove(ID));assertThrows(ServiceException.class,()->files.uploadApp(ID,new MockMultipartFile("file","x.apk","application/octet-stream",new byte[]{1})));}
|
||||
@Test void validatedAppUploadIsSeparatedFromSharedFilesAndCannotBeReadByOrdinaryUsers()throws Exception{
|
||||
var source=apk();tx.executeWithoutResult(s->packages.upload(ID,source));assertEquals(0L,files.page("",false,1,20).get("total"));assertEquals(1L,packages.page("",1,20).get("total"));assertTrue(packages.alive(ID));assertFalse(files.alive(false,ID));
|
||||
actor=2;assertThrows(ServiceException.class,()->files.open(ID));assertThrows(ServiceException.class,()->files.remove(ID));assertNull(releases.latest());
|
||||
}
|
||||
@Test void legacyMigrationOnlyMovesVerifiedOwnPackagesAndKeepsPublishedDownloadCompatible()throws Exception{
|
||||
files.upload(false,ID,apk());String other="22222222-2222-4222-8222-222222222222";files.upload(false,other,new MockMultipartFile("file","other.apk","application/octet-stream",new byte[]{1,2}));
|
||||
var migrated=packages.migrateLibrary();assertEquals(1,migrated.get("moved"));assertEquals(1,((List<?>)migrated.get("skipped")).size());assertEquals(1L,files.page("",false,1,20).get("total"));
|
||||
var release=tx.execute(s->releases.publish(ID,"独立管理安装包"));assertEquals("1.0.5",release.get("versionName"));assertThrows(ServiceException.class,()->packages.remove(ID));assertEquals(0,packages.migrateLibrary().get("moved"));
|
||||
actor=2;assertEquals(release.get("sha256"),releases.latest().get("sha256"));try(var in=releases.open(release.get("sha256").toString()).input()){assertEquals(release.get("size"),Long.valueOf(in.readAllBytes().length));}assertThrows(ServiceException.class,()->files.open(ID));
|
||||
}
|
||||
@Test void invalidOrWrongKindUploadsCannotBecomePackages()throws Exception{assertThrows(ServiceException.class,()->MobilePackageService.validateName("x.pdf"));assertThrows(ServiceException.class,()->packages.upload(ID,new MockMultipartFile("file","x.apk","application/octet-stream",new byte[]{1})));assertEquals(0L,packages.page("",1,20).get("total"));assertThrows(ServiceException.class,()->releases.publish(ID,""));}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
package com.ruoyi.system;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.storage.BusinessFileStorage;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.service.impl.MobileReleaseService;
|
||||
import com.ruoyi.web.controller.system.MobileReleaseController;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
class MobileReleaseRangeTest {
|
||||
@Test void ordinaryAuthenticatedUsersGetExactlyTheRequestedBytesAndHeaders()throws Exception {
|
||||
var db=mock(JdbcTemplate.class);var storage=mock(BusinessFileStorage.class);String hash="a".repeat(64);var json=new ObjectMapper();
|
||||
when(db.queryForList(anyString(),eq("mobile.release.dev"))).thenReturn(List.of(Map.of("config_value",json.writeValueAsString(Map.of("h",hash,"v",9,"n","1.0.2","s",100,"r","b".repeat(40))))));
|
||||
when(storage.openRange(anyString(),eq(20L),eq(10L))).thenReturn(new ByteArrayInputStream(new byte[]{20,21,22,23,24,25,26,27,28,29}));
|
||||
var service=new MobileReleaseService(db,storage,json,new StandardEnvironment());var controller=new MobileReleaseController(service);
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(SecurityUtils::getUserId).thenReturn(2L);
|
||||
var response=controller.content(hash,"bytes=20-29");assertEquals(206,response.getStatusCode().value());assertEquals("bytes 20-29/100",response.getHeaders().getFirst("Content-Range"));assertEquals("bytes",response.getHeaders().getFirst("Accept-Ranges"));assertEquals(10,response.getHeaders().getContentLength());
|
||||
var out=new ByteArrayOutputStream();response.getBody().writeTo(out);assertArrayEquals(new byte[]{20,21,22,23,24,25,26,27,28,29},out.toByteArray());
|
||||
for(String range:List.of("bytes=0-100","bytes=100-100","bytes=2-1","bytes=-1","bytes=0-1,4-5","bytes=0-","bytes=999999999999999999-1"))assertThrows(ServiceException.class,()->controller.content(hash,range),range);
|
||||
assertThrows(ServiceException.class,()->controller.content("c".repeat(64),"bytes=0-1"));
|
||||
verify(storage,times(1)).openRange(anyString(),anyLong(),anyLong());verify(storage,never()).openStream(anyString());
|
||||
security.when(SecurityUtils::getUserId).thenThrow(new ServiceException("not logged in",401));assertThrows(ServiceException.class,()->controller.content(hash,"bytes=0-1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -18,19 +18,19 @@ import static org.mockito.Mockito.*;
|
||||
class MobileReleaseTest {
|
||||
static final String PROD="96ab3e7afc5f60668693feec01140bcf13611f73ed9e76fa806bf9657f3d939b";
|
||||
JdbcTemplate db;BusinessFileStorage storage;MobileReleaseService service;MockedStatic<SecurityUtils> security;boolean admin=true;
|
||||
@BeforeEach void init(){db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));db.execute("create table sys_config(config_name varchar(100),config_key varchar(100),config_value varchar(500),config_type varchar(1),create_by varchar(64),create_time timestamp,update_by varchar(64),update_time timestamp)");db.execute("create table sys_managed_file(id varchar(36),file_kind varchar(16),deleted int,name varchar(180),byte_size bigint,sha256 varchar(64))");storage=mock(BusinessFileStorage.class);service=new MobileReleaseService(db,storage,new ObjectMapper(),new StandardEnvironment());security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenReturn(2L);security.when(SecurityUtils::getUsername).thenReturn("admin");security.when(SecurityUtils::isAdmin).thenAnswer(v->admin);}
|
||||
@BeforeEach void init(){db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa",""));db.execute("create table sys_config(config_name varchar(100),config_key varchar(100),config_value varchar(500),config_type varchar(1),create_by varchar(64),create_time timestamp,update_by varchar(64),update_time timestamp)");db.execute("create table sys_managed_file(id varchar(36),file_kind varchar(16),deleted int,name varchar(180),byte_size bigint,sha256 varchar(64))");db.execute("create table sys_mobile_package(file_id varchar(36),environment varchar(8),notes varchar(140),published_at timestamp)");storage=mock(BusinessFileStorage.class);service=new MobileReleaseService(db,storage,new ObjectMapper(),new StandardEnvironment());security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenReturn(2L);security.when(SecurityUtils::getUsername).thenReturn("admin");security.when(SecurityUtils::isAdmin).thenAnswer(v->admin);}
|
||||
@AfterEach void close(){security.close();}
|
||||
@Test void onlySuperAdminCanPublishAndAnonymousGetsNoMetadata(){admin=false;assertThrows(ServiceException.class,()->service.publish("11111111-1111-4111-8111-111111111111",""));verifyNoInteractions(storage);security.when(SecurityUtils::getUserId).thenThrow(new ServiceException("not logged in",401));assertThrows(ServiceException.class,service::latest);assertThrows(ServiceException.class,()->service.open("x"));}
|
||||
@Test void invalidConfigAndOlderDownloadFailClosed(){assertNull(service.latest());db.update("insert into sys_config(config_key,config_value) values(?,?)","mobile.release.dev","{\"v\":3,\"h\":\"fake\",\"s\":20}");assertThrows(ServiceException.class,service::latest);verifyNoInteractions(storage);}
|
||||
@Test void publishedObjectIsIndependentOfOriginalAndAvailableToOrdinaryUser()throws Exception{
|
||||
Path root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk")))root=root.getParent();Path apk=root.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk");Assumptions.assumeTrue(Files.isRegularFile(apk));byte[] bytes=Files.readAllBytes(apk);String hash=HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));String id="11111111-1111-4111-8111-111111111111";
|
||||
db.update("insert into sys_managed_file values(?,'LIBRARY',0,'production.apk',?,?)",id,bytes.length,hash);var objects=new HashMap<String,byte[]>();objects.put("managed-file/"+id+".bin",bytes);
|
||||
db.update("insert into sys_managed_file values(?,'LIBRARY',0,'production.apk',?,?)",id,bytes.length,hash);db.update("insert into sys_mobile_package(file_id,environment,notes) values(?,'prod','')",id);var objects=new HashMap<String,byte[]>();objects.put("managed-file/"+id+".bin",bytes);
|
||||
when(storage.openStream(anyString())).thenAnswer(c->new java.io.ByteArrayInputStream(Objects.requireNonNull(objects.get(c.getArgument(0)))));when(storage.exists(anyString(),isNull())).thenAnswer(c->objects.containsKey(c.getArgument(0)));doAnswer(c->{objects.put(c.getArgument(0),((java.io.InputStream)c.getArgument(1)).readAllBytes());return null;}).when(storage).saveStream(anyString(),any(),anyLong(),anyString());
|
||||
var env=new StandardEnvironment();env.setActiveProfiles("prod");service=new MobileReleaseService(db,storage,new ObjectMapper(),env);var result=service.publish(id,"修复");assertEquals(2L,result.get("versionCode"));objects.remove("managed-file/"+id+".bin");admin=false;assertEquals(hash,service.latest().get("sha256"));try(var in=service.open(hash).input()){assertArrayEquals(bytes,in.readAllBytes());}assertThrows(ServiceException.class,()->service.open("0".repeat(64)));assertThrows(ServiceException.class,()->service.publish(id,""));
|
||||
}
|
||||
@Test void minioWriteFailureCannotPublishBrokenMetadata()throws Exception{
|
||||
Path root=Path.of(System.getProperty("user.dir"));if(!Files.exists(root.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk")))root=root.getParent();Path apk=root.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk");Assumptions.assumeTrue(Files.isRegularFile(apk));byte[] bytes=Files.readAllBytes(apk);String hash=HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));String id="11111111-1111-4111-8111-111111111111";
|
||||
db.update("insert into sys_managed_file values(?,'LIBRARY',0,'production.apk',?,?)",id,bytes.length,hash);when(storage.openStream(anyString())).thenAnswer(c->new java.io.ByteArrayInputStream(bytes));when(storage.exists(anyString(),isNull())).thenReturn(false);doThrow(new java.io.IOException("simulated storage failure")).when(storage).saveStream(anyString(),any(),anyLong(),anyString());
|
||||
db.update("insert into sys_managed_file values(?,'LIBRARY',0,'production.apk',?,?)",id,bytes.length,hash);db.update("insert into sys_mobile_package(file_id,environment,notes) values(?,'prod','')",id);when(storage.openStream(anyString())).thenAnswer(c->new java.io.ByteArrayInputStream(bytes));when(storage.exists(anyString(),isNull())).thenReturn(false);doThrow(new java.io.IOException("simulated storage failure")).when(storage).saveStream(anyString(),any(),anyLong(),anyString());
|
||||
var env=new StandardEnvironment();env.setActiveProfiles("prod");service=new MobileReleaseService(db,storage,new ObjectMapper(),env);assertThrows(ServiceException.class,()->service.publish(id,""));assertEquals(0,db.queryForObject("select count(*) from sys_config",Integer.class));
|
||||
}
|
||||
@Test void signedProductionPackageCannotBeRepurposedAsDevelopmentOrTampered()throws Exception{
|
||||
|
||||
@ -26,6 +26,7 @@ class PurchaseDocumentsTest {
|
||||
when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->call.getArgument(0,String.class).startsWith("select id from ")?List.of(Map.of("id",1)):List.of());
|
||||
try(var security=mockStatic(SecurityUtils.class)) {
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
|
||||
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
var groups=service.list("batch",1L);assertEquals(6,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty()));
|
||||
assertEquals(List.of("REQUEST","QUOTE","CONTRACT","ACCEPTANCE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList());
|
||||
assertEquals("OTHER",service.list("detail",1L).get(0).kind());
|
||||
|
||||
@ -28,6 +28,9 @@ class PurchaseOnlyMineControllerTest {
|
||||
var controller = new PurchaseRequestController();
|
||||
var purchases = mock(IPurchaseRequestService.class);
|
||||
var batches = mock(IPurchaseBatchService.class);
|
||||
var batchMapper = mock(com.ruoyi.warehouse.mapper.PurchaseBatchMapper.class);
|
||||
ReflectionTestUtils.setField(controller, "purchaseBatchMapper", batchMapper);
|
||||
when(batchMapper.selectPurchaseBatchTotals(any())).thenReturn(new java.util.HashMap<>(java.util.Map.of("actualTotalAmount", 100, "totalAmount", 200, "unpricedCount", 0)));
|
||||
ReflectionTestUtils.setField(controller, "purchaseRequestService", purchases);
|
||||
ReflectionTestUtils.setField(controller, "purchaseBatchService", batches);
|
||||
when(purchases.selectPurchaseRequestList(any())).thenReturn(List.of());
|
||||
@ -37,7 +40,10 @@ class PurchaseOnlyMineControllerTest {
|
||||
mvc.perform(get(endpoint).param("onlyMine", "true").param("createBy", "other-user")).andReturn();
|
||||
}
|
||||
verify(purchases, times(3)).selectPurchaseRequestList(argThat(q -> Boolean.TRUE.equals(q.getOnlyMine()) && "current-user".equals(q.getCreateBy())));
|
||||
mvc.perform(get("/warehouse/purchase/batch/list").param("onlyMine", "true").param("createBy", "other-user")).andReturn();
|
||||
var batchResult = mvc.perform(get("/warehouse/purchase/batch/list").param("onlyMine", "true").param("createBy", "other-user")).andReturn();
|
||||
var json = new com.fasterxml.jackson.databind.ObjectMapper().readTree(batchResult.getResponse().getContentAsString());
|
||||
assertEquals(100, json.path("summary").path("actualTotalAmount").asInt());
|
||||
assertFalse(json.path("summary").has("totalAmount"));
|
||||
verify(batches).selectPurchaseBatchList(argThat(q -> Boolean.TRUE.equals(q.getOnlyMine()) && "current-user".equals(q.getCreateBy())));
|
||||
mvc.perform(get("/warehouse/purchase/filtered").param("onlyMine", "false").param("createBy", "other-user")).andReturn();
|
||||
verify(purchases).selectPurchaseRequestList(argThat(q -> Boolean.FALSE.equals(q.getOnlyMine()) && q.getCreateBy() == null));
|
||||
|
||||
@ -91,6 +91,7 @@ class PurchaseQuoteAccessTest {
|
||||
}
|
||||
@Test void httpDetailSheetListTotalsAndBatchResponsesApplyTheSamePolicy() throws Exception {
|
||||
var controller=new PurchaseRequestController();var purchases=mock(IPurchaseRequestService.class);var sheets=mock(PurchaseSheetService.class);var batches=mock(IPurchaseBatchService.class);
|
||||
ReflectionTestUtils.setField(controller,"purchaseBatchMapper",mock(com.ruoyi.warehouse.mapper.PurchaseBatchMapper.class));
|
||||
ReflectionTestUtils.setField(controller,"purchaseRequestService",purchases);ReflectionTestUtils.setField(controller,"sheetService",sheets);ReflectionTestUtils.setField(controller,"purchaseBatchService",batches);
|
||||
when(purchases.selectPurchaseRequestById(1L)).thenReturn(source);when(purchases.selectPurchaseRequestList(any())).thenReturn(List.of(source));
|
||||
var batch=new PurchaseBatch();batch.setId(2L);batch.setTotalAmount(source.getEstimatedAmount());batch.setActualTotalAmount(source.getActualAmount());
|
||||
|
||||
@ -62,13 +62,13 @@ class SupplierInquiryRoundTripTest {
|
||||
var purchase=purchase();var result=preview(exported(purchase,book->{var tab=book.getSheetAt(0);for(var row:tab)for(int c=11;c<=13;c++)if(row.getCell(c)!=null)row.getCell(c).setBlank();tab.getRow(6).getCell(6).setCellValue(8.5);}),purchase);assertTrue(ready(result.get(0)));assertEquals(List.of(1L,2L),result.get(0).get("rowIds"));
|
||||
}
|
||||
@Test void sameNameWithoutModelCannotChooseArbitrarily()throws Exception {
|
||||
var purchase=purchase();var result=preview(exported(purchase,book->{var tab=book.getSheetAt(0);for(var row:tab)for(int c:List.of(2,3,4,11,12,13))if(row.getCell(c)!=null)row.getCell(c).setBlank();tab.getRow(6).getCell(6).setCellValue(3);}),purchase);assertFalse(ready(result.get(0)));assertTrue(result.get(0).get("error").toString().contains("同名"));
|
||||
var purchase=purchase();var result=preview(exported(purchase,book->{var tab=book.getSheetAt(0);for(var row:tab)for(int c:List.of(2,3,4,11,12,13,15))if(row.getCell(c)!=null)row.getCell(c).setBlank();tab.getRow(6).getCell(6).setCellValue(3);}),purchase);assertFalse(ready(result.get(0)));assertTrue(result.get(0).get("error").toString().contains("同名"));
|
||||
}
|
||||
@Test void existingInboundInOneProjectDoesNotBlockOtherUnreceivedProjectLines()throws Exception {
|
||||
var purchase=purchase();purchase.getRows().get(0).setReceivedQuantity(BigDecimal.ONE);var items=SupplierInquiryExport.items(purchase);assertEquals(List.of(2L),items.get(0).rowIds());assertEquals(new BigDecimal("2"),items.get(0).quantity());var result=preview(exported(purchase,book->book.getSheetAt(0).getRow(6).getCell(6).setCellValue(9)),purchase);assertEquals(List.of(2L),result.get(0).get("rowIds"));assertTrue(ready(result.get(0)));
|
||||
}
|
||||
@Test void duplicatePricesAreBothBlockedAndInvalidNumberFormatsDoNotBecomeOtherValues()throws Exception {
|
||||
var purchase=purchase();var result=preview(exported(purchase,book->{var tab=book.getSheetAt(0);tab.getRow(6).getCell(6).setCellValue(1);tab.getRow(7).getCell(6).setCellValue(2);for(int c:List.of(1,2,3,4,5,11,12,13))tab.getRow(7).getCell(c).setCellValue(new DataFormatter().formatCellValue(tab.getRow(6).getCell(c)));}),purchase);assertTrue(result.stream().allMatch(row->row.get("error")!=null));
|
||||
var purchase=purchase();var result=preview(exported(purchase,book->{var tab=book.getSheetAt(0);tab.getRow(6).getCell(6).setCellValue(1);tab.getRow(7).getCell(6).setCellValue(2);for(int c:List.of(1,2,3,4,5,11,12,13,15))tab.getRow(7).getCell(c).setCellValue(new DataFormatter().formatCellValue(tab.getRow(6).getCell(c)));}),purchase);assertTrue(result.stream().allMatch(row->row.get("error")!=null));
|
||||
for(String value:List.of("1,5","-1","1.1234567","9999999999999","NaN","无限")){var invalid=preview(exported(purchase,book->book.getSheetAt(0).getRow(6).getCell(6).setCellValue(value)),purchase);assertFalse(ready(invalid.get(0)),value);}
|
||||
}
|
||||
@Test void ordinaryExcelPriceFormulaCanBeEvaluatedWithoutTrustingCachedValues()throws Exception {
|
||||
@ -137,7 +137,7 @@ class SupplierInquiryRoundTripTest {
|
||||
if(includeActual){assertEquals(CellType.BLANK,tab.getRow(6).getCell(8).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(9).getCellType());}
|
||||
tab.getRow(6).getCell(6).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0)));
|
||||
}
|
||||
assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"name"));
|
||||
try(var book=SupplierInquiryExport.workbook(purchase,true,"name")){assertTrue(book.getSheetAt(0).isColumnHidden(6));assertEquals(CellType.BLANK,book.getSheetAt(0).getRow(6).getCell(7).getCellType());}
|
||||
assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"quoteUnitPrice,bogus"));
|
||||
}
|
||||
|
||||
@ -154,4 +154,37 @@ class SupplierInquiryRoundTripTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void selectedRowsOnlyContributeTheirQuantityRemarksAndActualAmountsAndRoundTrip() throws Exception {
|
||||
var purchase=purchase();purchase.getRows().get(0).setRemark("已选备注");purchase.getRows().get(1).setRemark("未选备注");purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN));
|
||||
var selected=SupplierInquiryExport.selected(purchase,List.of(1L));
|
||||
try(var book=SupplierInquiryExport.workbook(selected);var bytes=new ByteArrayOutputStream()) {
|
||||
var tab=book.getSheetAt(0);assertEquals(1,tab.getRow(6).getCell(5).getNumericCellValue());assertEquals(10,tab.getRow(6).getCell(9).getNumericCellValue());assertEquals("已选备注",tab.getRow(6).getCell(14).getStringCellValue());assertEquals("1",tab.getRow(6).getCell(15).getStringCellValue());assertTrue(tab.isColumnHidden(15));
|
||||
tab.getRow(6).getCell(6).setCellValue(8);book.write(bytes);var result=preview(bytes.toByteArray(),purchase);assertEquals(1,result.size());assertTrue(ready(result.get(0)));assertEquals(List.of(1L),result.get(0).get("rowIds"));
|
||||
}
|
||||
assertEquals(3,purchase.getRows().size());assertThrows(ServiceException.class,()->SupplierInquiryExport.selected(purchase,List.of()));assertThrows(ServiceException.class,()->SupplierInquiryExport.selected(purchase,List.of(999L)));
|
||||
}
|
||||
@Test void missingOrChangedSelectionMetadataNeverWidensQuoteImport() throws Exception {
|
||||
var purchase=purchase();var selected=SupplierInquiryExport.selected(purchase,List.of(1L));
|
||||
for(String ids:List.of("","2","999","1,2","1,1")) {
|
||||
var result=preview(exported(selected,book->{var row=book.getSheetAt(0).getRow(6);row.getCell(6).setCellValue(8);row.getCell(15).setCellValue(ids);}),purchase);
|
||||
assertFalse(ready(result.get(0)),ids);assertNotNull(result.get(0).get("error"));
|
||||
}
|
||||
}
|
||||
@Test void exportedCellsAreCenteredAndQuoteInputIsOptional() throws Exception {
|
||||
var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN));
|
||||
try(var book=SupplierInquiryExport.workbook(purchase,true,"name,actualAmount")) {
|
||||
var tab=book.getSheetAt(0);assertTrue(tab.isColumnHidden(6));assertTrue(tab.isColumnHidden(7));assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType());assertFalse(tab.isColumnHidden(1));assertEquals("实际金额合计",tab.getRow(8).getCell(1).getStringCellValue());
|
||||
for(var row:tab)for(var cell:row){assertEquals(HorizontalAlignment.CENTER,cell.getCellStyle().getAlignment());assertEquals(VerticalAlignment.CENTER,cell.getCellStyle().getVerticalAlignment());}
|
||||
}
|
||||
}
|
||||
@Test void controllerExportsOnlySubmittedIdsAndRejectsForeignIds() throws Exception {
|
||||
var purchase=purchase();var controller=new PurchaseRequestController();var service=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.PurchaseSheetService.class);var settings=org.mockito.Mockito.mock(com.ruoyi.warehouse.service.impl.AmountDisplaySettings.class);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(controller,"sheetService",service);org.springframework.test.util.ReflectionTestUtils.setField(controller,"amountDisplaySettings",settings);org.mockito.Mockito.when(service.load(1L)).thenReturn(purchase);
|
||||
try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.warehouse.util.PurchaseQuoteAccess.class,org.mockito.Mockito.CALLS_REAL_METHODS)) {
|
||||
security.when(com.ruoyi.warehouse.util.PurchaseQuoteAccess::allowed).thenReturn(true);
|
||||
var response=new org.springframework.mock.web.MockHttpServletResponse();controller.inquiryExport(1L,"snapshot-1","name,quantity",new PurchaseRequestController.InquiryExportSelection(List.of(2L)),response);
|
||||
try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){assertEquals(2,book.getSheetAt(0).getRow(6).getCell(5).getNumericCellValue());assertNull(book.getSheetAt(0).getRow(7));assertTrue(book.getSheetAt(0).isColumnHidden(6));}
|
||||
assertThrows(ServiceException.class,()->controller.inquiryExport(1L,"snapshot-1","name",new PurchaseRequestController.InquiryExportSelection(List.of(999L)),new org.springframework.mock.web.MockHttpServletResponse()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +46,7 @@ class AssistantBlackboxRegressionTest {
|
||||
var receipt=table(registry,"receipt.query",Map.of("inNum",10,"receiptUnitCost",5,"businessDate","2026-10-17"));
|
||||
assertEquals("入库数量",labels(receipt).get("inNum"));assertEquals("入库单价",labels(receipt).get("receiptUnitCost"));assertEquals("入库日期",labels(receipt).get("businessDate"));
|
||||
assertEquals("采购日期",labels(table(registry,"batch.query",Map.of("businessDate","2026-10-17"))).get("businessDate"));
|
||||
assertEquals("借用日期",labels(table(registry,"loan.query",Map.of("businessDate","2026-10-17"))).get("businessDate"));
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class, () -> registry.prepare("loan.query",List.of(Map.of())));
|
||||
assertEquals("差异原因",labels(table(registry,"stockCheck.query",Map.of("reason","盘盈1"))).get("reason"));
|
||||
var budget=table(registry,"budget.query",Map.of("budgetAmount",0,"committedAmount",0,"spentAmount",200,"availableAmount",-200));
|
||||
assertFalse(labels(budget).containsKey("committedAmount"));assertEquals("已锁定采购费用",labels(budget).get("spentAmount"));
|
||||
|
||||
@ -34,13 +34,14 @@ class AssistantBusinessContractTest {
|
||||
}
|
||||
|
||||
@Test void everyRegisteredActionHasBusinessSpecificRulesAndExcludesCollaborationControllers() throws Exception {
|
||||
assertTrue(actions().keySet().stream().noneMatch(k -> k.startsWith("loan.")));
|
||||
var checked = new LinkedHashSet<String>();
|
||||
for (var action : actions().values()) {
|
||||
assertFalse(AssistantBusinessRules.rules(action.key()).isEmpty(), action.key() + " has no business contract");
|
||||
assertFalse(action.controller().getName().contains(".project.manage."), action.key());
|
||||
checked.add(action.key().split("\\.")[0]);
|
||||
}
|
||||
assertTrue(checked.containsAll(Set.of("project", "budget", "stock", "receipt", "loan", "stockCheck",
|
||||
assertTrue(checked.containsAll(Set.of("project", "budget", "stock", "receipt", "stockCheck",
|
||||
"material", "product", "projectProduct", "bom", "cost", "production", "item", "supplier", "area", "expenseCategory",
|
||||
"purchase", "batch", "arrival", "user", "role", "notice", "feedback")));
|
||||
}
|
||||
|
||||
@ -52,7 +52,7 @@ class AssistantPurchaseSheetContractTest {
|
||||
long generatedId=1000;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
SysUser user=new SysUser();user.setUserId(7L);user.setUserName("purchase-contract");
|
||||
SysUser user=new SysUser();user.setUserId(7L);user.setUserName("purchase-contract"); var procurementRole = new com.ruoyi.common.core.domain.entity.SysRole(); procurementRole.setRoleKey("purchase_manager"); procurementRole.setStatus("0"); procurementRole.setDelFlag("0"); user.setRoles(java.util.List.of(procurementRole));
|
||||
LoginUser login=new LoginUser(7L,1L,user,Set.of("*:*:*"));
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null));
|
||||
when(guard.refresh()).thenReturn(login);when(guard.allows(any())).thenReturn(true);
|
||||
@ -106,7 +106,7 @@ class AssistantPurchaseSheetContractTest {
|
||||
|
||||
@Test void newItemPreviewUsesRealResolverButDoesNotCreateAnything() {
|
||||
var row=ready("purchase.create",List.of(raw("r1"))).get(0);
|
||||
assertEquals("CREATE",kind(row));assertNull(row.get("productId"));assertEquals("SELF",row.get("purchasePurpose"));
|
||||
assertEquals("CREATE",kind(row));assertNull(row.get("productId"));assertFalse(row.containsKey("purchasePurpose"));
|
||||
verify(products).previewImport(anyList());verify(products,never()).insertProductInfo(any());verify(products,never()).updateProductInfo(any());verifyNoInteractions(controller);
|
||||
}
|
||||
@Test void unrelatedUnresolvedReferencesDoNotTurnValidNewItemsIntoFormatErrors() {
|
||||
|
||||
@ -273,22 +273,10 @@ class AssistantReadOnlyRegistryTest {
|
||||
var changed=registry.prepare("dictionary.update",List.of(Map.of("id",2L,"dictType","wms_item_category","status","1")));
|
||||
assertEquals(false,changed.get("ready"));assertTrue(changed.get("errors").toString().contains("不能修改字典项所属类型"));
|
||||
}
|
||||
@Test void loanReturnResolutionPreservesParentLoanAndUsesRealIdentifiersOnly() {
|
||||
Map<String,Object> first=Map.of("id",1L,"code","JY001","loanNo","JY001","loanId",11L,"name","螺丝","businessKey","LOAN-RETURN:return-1","eventNo","LS2026100001","quantity",1,"active",true);
|
||||
Map<String,Object> other=Map.of("id",2L,"code","JY002","loanNo","JY002","loanId",22L,"name","螺丝","businessKey","LOAN-RETURN:return-2","eventNo","LS2026100002","quantity",1,"active",true);
|
||||
when(database.queryForList(anyString(),any(Object[].class))).thenReturn(List.of(first,other));
|
||||
for(String identity:List.of("LOAN-RETURN:return-1","LS2026100001")) {
|
||||
var preview=registry.prepare("loan.revokeReturn",List.of(Map.of("id",Map.of("keyword",identity,"loanNo","JY001"),"reason","登记有误")));
|
||||
assertEquals(true,preview.get("ready"),preview.toString());var row=AssistantConversationService.maps(preview.get("rows")).get(0);
|
||||
assertEquals(1L,row.get("id"));assertEquals(11L,row.get("loanId"));assertEquals("LOAN-RETURN:return-1",row.get("originalReturnKey"));
|
||||
}
|
||||
var wrongParent=registry.prepare("loan.revokeReturn",List.of(Map.of("id",Map.of("id",1L,"loanNo","JY002","loanId",11L),"reason","登记有误")));
|
||||
assertEquals(false,wrongParent.get("ready"));
|
||||
when(database.queryForList(anyString(),any(Object[].class))).thenReturn(List.of(first));
|
||||
assertEquals(false,registry.prepare("loan.revokeReturn",List.of(Map.of("id",Map.of("keyword","GH001","loanNo","JY001"),"reason","登记有误"))).get("ready"));
|
||||
var unsupported=registry.prepare("loan.revokeReturn",List.of(Map.of("id",Map.of("keyword","LS2026100001","loanNo","JY001","unregisteredParent","X"),"reason","登记有误")));
|
||||
assertEquals(false,unsupported.get("ready"));assertTrue(unsupported.get("errors").toString().contains("不支持限定条件"));
|
||||
@Test void disabledLoanReturnsCannotBePreparedByAssistant() {
|
||||
assertThrows(com.ruoyi.common.exception.ServiceException.class, () -> registry.prepare("loan.revokeReturn",List.of(Map.of("id",1L))));
|
||||
}
|
||||
|
||||
@Test void queryColumnsPrioritizeBusinessIdentityAndRetainRemarksAndAuditFields() {
|
||||
var areas=mock(com.ruoyi.web.controller.warehouse.WarehouseAreaController.class);when(context.getBean(com.ruoyi.web.controller.warehouse.WarehouseAreaController.class)).thenReturn(areas);
|
||||
var stock=mock(com.ruoyi.web.controller.warehouse.StockInfoController.class);when(context.getBean(com.ruoyi.web.controller.warehouse.StockInfoController.class)).thenReturn(stock);
|
||||
|
||||
@ -94,7 +94,7 @@ class BusinessActionRegistryTest {
|
||||
private BusinessActionRegistry registry;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
SysUser user=new SysUser();user.setUserId(101L);user.setUserName("registry-test");
|
||||
SysUser user=new SysUser();user.setUserId(101L);user.setUserName("registry-test"); var procurementRole = new com.ruoyi.common.core.domain.entity.SysRole(); procurementRole.setRoleKey("purchase_manager"); procurementRole.setStatus("0"); procurementRole.setDelFlag("0"); user.setRoles(java.util.List.of(procurementRole));
|
||||
LoginUser login=new LoginUser(101L,1L,user,Set.of("*:*:*"));
|
||||
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null));
|
||||
when(guard.refresh()).thenReturn(login);when(guard.allows(any())).thenReturn(true);
|
||||
|
||||
@ -17,6 +17,9 @@ public class TableDataInfo implements Serializable
|
||||
|
||||
/** 列表数据 */
|
||||
private List<?> rows;
|
||||
private java.util.Map<String, Object> summary;
|
||||
public java.util.Map<String, Object> getSummary() { return summary; }
|
||||
public void setSummary(java.util.Map<String, Object> summary) { this.summary = summary; }
|
||||
|
||||
/** 消息状态码 */
|
||||
private int code;
|
||||
|
||||
@ -109,6 +109,14 @@ public class BusinessFileStorage {
|
||||
catch(Exception error){throw failure("文件读取失败,请稍后重试",error);}
|
||||
}
|
||||
|
||||
/** Authenticated caller supplies a bounded byte range; MinIO reads only those bytes. */
|
||||
public InputStream openRange(String key,long offset,long length) throws IOException {
|
||||
checked(key);
|
||||
if(!isEnabled()||offset<0||length<1||length>250L*1024*1024)throw new IOException("文件下载范围无效");
|
||||
try{return client.getObject(GetObjectArgs.builder().bucket(properties.getBucketName()).object(key).offset(offset).length(length).build());}
|
||||
catch(Exception e){throw failure("文件读取失败,请稍后重试",e);}
|
||||
}
|
||||
|
||||
public byte[] read(String key, Path legacyPath, int maxBytes) throws IOException {
|
||||
checked(key);
|
||||
if (maxBytes < 1 || maxBytes > 100 * 1024 * 1024) throw new IllegalArgumentException("文件大小限制无效");
|
||||
|
||||
@ -26,7 +26,7 @@ import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
return borrow(lender,borrower,item,fromArea,toArea,quantity,key,remark,null);
|
||||
}
|
||||
@Transactional public ProjectLoan borrow(Long lender,Long borrower,Long item,Long fromArea,Long toArea,BigDecimal quantity,String key,String remark,java.time.LocalDate date){
|
||||
journal.lockInventory();key=key(key);if(Objects.equals(lender,borrower)) throw error("借出和借入项目不能相同");
|
||||
loansDisabled(); journal.lockInventory();key=key(key);if(Objects.equals(lender,borrower)) throw error("借出和借入项目不能相同");
|
||||
projects.requireProjectAccess(lender);projects.requireProjectAccess(borrower);
|
||||
String no="LOAN-"+UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8));
|
||||
ProjectLoan duplicate=mapper.byNo(no);
|
||||
@ -41,7 +41,7 @@ import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
@Transactional public ProjectLoan returnStock(Long id,Long fromArea,Long toArea,BigDecimal quantity,String key){
|
||||
return returnStock(id,fromArea,toArea,quantity,key,null,null);
|
||||
}
|
||||
@Transactional public ProjectLoan returnStock(Long id,Long fromArea,Long toArea,BigDecimal quantity,String key,java.time.LocalDate date,String remark){
|
||||
@Transactional public ProjectLoan returnStock(Long id,Long fromArea,Long toArea,BigDecimal quantity,String key,java.time.LocalDate date,String remark){ loansDisabled();
|
||||
journal.lockInventory();key="LOAN-RETURN:"+key(key);ProjectLoan loan=get(id);
|
||||
if(mapper.returnByKey(key)==null) requireRemaining(loan,quantity);
|
||||
var out=journal.append(InventoryCostJournal.details(event(loan.getBorrowerProjectId(),loan.getItemId(),fromArea,"ISSUE",quantity,null,null,key+":out"),date,remark));
|
||||
@ -55,10 +55,11 @@ import static com.ruoyi.warehouse.service.impl.InventoryCostJournal.event;
|
||||
registerReturn(loan,receipt.getQuantity(),"PURCHASE-RETURN:"+receipt.getId(),"PURCHASE",null,receipt.getId());
|
||||
}
|
||||
@Transactional public void revokePurchaseReceipt(Long eventId){journal.lockInventory();Long id=mapper.returnLoanForEvent(eventId);if(id!=null){get(id);mapper.deactivateReturn(eventId);}}
|
||||
@Transactional public void revokeLoan(Long id,String reason){journal.lockInventory();ProjectLoan loan=get(id);if(!Boolean.TRUE.equals(loan.getActive())) return;if(reason==null||reason.isBlank()||reason.length()>300)throw error("请填写撤销原因,最多300字");if(loan.getReturnedQuantity().subtract(loan.getHistoricalReturned()==null?BigDecimal.ZERO:loan.getHistoricalReturned()).signum()>0) throw error("请先撤销系统内归还记录");if(loan.getInEventId()!=null){journal.voidLastEvent(loan.getInEventId(),reason);journal.voidLastEvent(loan.getOutEventId(),reason);}mapper.deactivate(id);}
|
||||
@Transactional public void revokeStockReturn(Long loanId,String key,String reason){journal.lockInventory();get(loanId);Map<String,Object> row=mapper.returnByKey(key);if(row==null||!Objects.equals(((Number)row.get("loanId")).longValue(),loanId)||!"STOCK".equals(row.get("returnType"))) throw error("库存归还记录不存在;采购归还请从入库入口撤销");Long in=((Number)row.get("inEventId")).longValue(),out=((Number)row.get("outEventId")).longValue();journal.voidLastEvent(in,reason);journal.voidLastEvent(out,reason);mapper.deactivateReturn(in);}
|
||||
@Transactional public void revokeLoan(Long id,String reason){loansDisabled();journal.lockInventory();ProjectLoan loan=get(id);if(!Boolean.TRUE.equals(loan.getActive())) return;if(reason==null||reason.isBlank()||reason.length()>300)throw error("请填写撤销原因,最多300字");if(loan.getReturnedQuantity().subtract(loan.getHistoricalReturned()==null?BigDecimal.ZERO:loan.getHistoricalReturned()).signum()>0) throw error("请先撤销系统内归还记录");if(loan.getInEventId()!=null){journal.voidLastEvent(loan.getInEventId(),reason);journal.voidLastEvent(loan.getOutEventId(),reason);}mapper.deactivate(id);}
|
||||
@Transactional public void revokeStockReturn(Long loanId,String key,String reason){loansDisabled();journal.lockInventory();get(loanId);Map<String,Object> row=mapper.returnByKey(key);if(row==null||!Objects.equals(((Number)row.get("loanId")).longValue(),loanId)||!"STOCK".equals(row.get("returnType"))) throw error("库存归还记录不存在;采购归还请从入库入口撤销");Long in=((Number)row.get("inEventId")).longValue(),out=((Number)row.get("outEventId")).longValue();journal.voidLastEvent(in,reason);journal.voidLastEvent(out,reason);mapper.deactivateReturn(in);}
|
||||
private void registerReturn(ProjectLoan loan,BigDecimal quantity,String key,String type,Long outId,Long inId){Map<String,Object> existing=mapper.returnByKey(key);if(existing!=null){if(!Objects.equals(((Number)existing.get("loanId")).longValue(),loan.getId())||!Objects.equals(((Number)existing.get("inEventId")).longValue(),inId)||((BigDecimal)existing.get("quantity")).compareTo(quantity)!=0) throw error("重复归还内容不一致");if(((Number)existing.get("active")).intValue()!=1) throw error("该归还已撤销");return;}requireRemaining(loan,quantity);mapper.insertReturn(loan.getId(),quantity,key,type,outId,inId,SecurityUtils.getUsername());}
|
||||
private void requireRemaining(ProjectLoan loan,BigDecimal quantity){if(!Boolean.TRUE.equals(loan.getActive())||quantity==null||quantity.signum()<=0||quantity.stripTrailingZeros().scale()>4||quantity.compareTo(loan.getOutstandingQuantity())>0) throw error("归还数量必须大于0且不能超过未还数量:"+loan.getOutstandingQuantity());}
|
||||
private String key(String key){if(StringUtils.isBlank(key)||key.length()>100) throw error("业务标识不能为空或超长");return key;}
|
||||
private ServiceException error(String message){return new ServiceException(message);}
|
||||
private void loansDisabled(){throw error("借用与归还功能已停用");}
|
||||
}
|
||||
|
||||
@ -24,15 +24,18 @@ public class ManagedFileService {
|
||||
public int authorizeUpload(boolean notice){require(notice?new String[]{"system:notice:add","system:notice:edit"}:new String[]{"system:file:upload","system:file:manage"});return MAX_BYTES;}
|
||||
public Map<String,Object> page(String keyword,boolean mine,int page,int size){
|
||||
require("system:file:list","system:file:manage");page=Math.max(1,page);size=Math.max(1,Math.min(100,size));String key=Objects.toString(keyword,"").trim();if(key.length()>180)throw new ServiceException("搜索内容过长");
|
||||
String where=" where f.file_kind='LIBRARY' and f.deleted=0"+(mine?" and f.owner_id=?":"")+" and (f.name like ? escape '!' or f.create_by like ? escape '!' or u.nick_name like ? escape '!')";
|
||||
String where=" where f.file_kind='LIBRARY' and f.deleted=0 and not exists(select 1 from sys_mobile_package mp where mp.file_id=f.id)"+(mine?" and f.owner_id=?":"")+" and (f.name like ? escape '!' or f.create_by like ? escape '!' or u.nick_name like ? escape '!')";
|
||||
var args=new ArrayList<Object>();if(mine)args.add(actor());String like="%"+key.replace("!","!!").replace("%","!%").replace("_","!_")+"%";args.addAll(List.of(like,like,like));
|
||||
long total=db.queryForObject("select count(*) from sys_managed_file f left join sys_user u on u.user_id=f.owner_id"+where,Long.class,args.toArray());args.add(size);args.add((long)(page-1)*size);
|
||||
var rows=db.queryForList(select()+where+" order by f.create_time desc,f.id desc limit ? offset ?",args.toArray()).stream().map(this::info).toList();
|
||||
return Map.of("rows",rows,"total",total,"page",page,"size",size,"maxBytes",MAX_BYTES,"canUpload",has("system:file:upload","system:file:manage"));
|
||||
}
|
||||
@Transactional public ManagedFileInfo upload(boolean notice,String id,MultipartFile file){
|
||||
authorizeUpload(notice);uuid(id);if(file==null||file.isEmpty()||file.getSize()>MAX_BYTES)throw new ServiceException("请选择非空文件,单个不超过1GB");if(!storage.isEnabled())throw new ServiceException("文件存储暂未开启");
|
||||
String name=safeName(file.getOriginalFilename()),kind=notice?"NOTICE":"LIBRARY",sha;
|
||||
@Transactional public ManagedFileInfo upload(boolean notice,String id,MultipartFile file){authorizeUpload(notice);if(!notice&&isApp(id))throw new ServiceException("请在App版本管理中维护安装包");return save(notice?"NOTICE":"LIBRARY",id,file);}
|
||||
@Transactional public ManagedFileInfo uploadApp(String id,MultipartFile file){requireAppAdmin();return save("LIBRARY",id,file);}
|
||||
public boolean appAlive(String id){requireAppAdmin();uuid(id);return db.queryForObject("select count(*) from sys_managed_file where id=? and owner_id=? and deleted=0",Long.class,id,actor())==1&&isApp(id);}
|
||||
private ManagedFileInfo save(String kind,String id,MultipartFile file){
|
||||
uuid(id);if(file==null||file.isEmpty()||file.getSize()>MAX_BYTES)throw new ServiceException("请选择非空文件,单个不超过1GB");if(!storage.isEnabled())throw new ServiceException("文件存储暂未开启");
|
||||
String name=safeName(file.getOriginalFilename()),sha;
|
||||
try(var in=file.getInputStream()){sha=digest(in,file.getSize());}catch(Exception error){throw new ServiceException("文件校验失败,请重新选择原文件");}
|
||||
var prior=db.queryForList(select()+" where f.id=? for update",id);
|
||||
if(!prior.isEmpty()){var row=prior.get(0);if(number(row,"owner_id")!=actor()||!kind.equals(row.get("file_kind"))||!sha.equals(row.get("sha256"))||!name.equals(row.get("name"))||number(row,"deleted")!=0)throw new ServiceException("文件上传标识已被使用");return info(row);}
|
||||
@ -45,7 +48,7 @@ public class ManagedFileService {
|
||||
return info(db.queryForList(select()+" where f.id=?",id).get(0));
|
||||
}catch(Exception error){if(ours)storage.discardFailedUpload(key,null);if(error instanceof ServiceException business)throw business;throw new ServiceException("文件保存尚未完成,已上传分片会保留,请重试");}
|
||||
}
|
||||
public boolean alive(boolean notice,String id){uuid(id);String kind=notice?"NOTICE":"LIBRARY";return db.queryForObject("select count(*) from sys_managed_file f where f.id=? and f.owner_id=? and f.file_kind=? and f.deleted=0"+(notice?" and not exists(select 1 from sys_notice_attachment a where a.file_id=f.id)":""),Long.class,id,actor(),kind)==1;}
|
||||
public boolean alive(boolean notice,String id){uuid(id);if(!notice&&isApp(id))return false;String kind=notice?"NOTICE":"LIBRARY";return db.queryForObject("select count(*) from sys_managed_file f where f.id=? and f.owner_id=? and f.file_kind=? and f.deleted=0"+(notice?" and not exists(select 1 from sys_notice_attachment a where a.file_id=f.id)":""),Long.class,id,actor(),kind)==1;}
|
||||
public List<ManagedFileInfo> noticeFiles(long notice){
|
||||
readableNotice(notice);return db.queryForList(select()+" join sys_notice_attachment a on a.file_id=f.id where a.notice_id=? and f.deleted=0 order by a.sort_order,f.id",notice).stream().map(this::info).toList();
|
||||
}
|
||||
@ -62,13 +65,15 @@ public class ManagedFileService {
|
||||
public record Download(String name,long size,InputStream input){}
|
||||
public Download open(String id){
|
||||
uuid(id);var rows=db.queryForList(select()+" where f.id=? and f.deleted=0",id);if(rows.isEmpty())throw missing();var row=rows.get(0);
|
||||
if("LIBRARY".equals(row.get("file_kind")))require("system:file:download","system:file:manage");
|
||||
if(isApp(id))requireAppAdmin();
|
||||
else if("LIBRARY".equals(row.get("file_kind")))require("system:file:download","system:file:manage");
|
||||
else{var links=db.queryForList("select notice_id from sys_notice_attachment where file_id=?",Long.class,id);if(!links.isEmpty())readableNotice(links.get(0));else if(number(row,"owner_id")!=actor()||!has("system:notice:add","system:notice:edit"))throw missing();}
|
||||
try{return new Download(row.get("name").toString(),number(row,"byte_size"),storage.openStream(key(id)));}catch(IOException error){throw new ServiceException("文件暂时无法读取,请稍后重试");}
|
||||
}
|
||||
@Transactional public void remove(String id){
|
||||
uuid(id);var rows=db.queryForList("select * from sys_managed_file where id=? and deleted=0 for update",id);if(rows.isEmpty())throw missing();var row=rows.get(0);
|
||||
if("NOTICE".equals(row.get("file_kind"))){authorizeUpload(true);if(number(row,"owner_id")!=actor()||db.queryForObject("select count(*) from sys_notice_attachment where file_id=?",Long.class,id)>0)throw new ServiceException("已保存的公告附件请在公告编辑中移除");}
|
||||
if(isApp(id))requireAppAdmin();
|
||||
else if("NOTICE".equals(row.get("file_kind"))){authorizeUpload(true);if(number(row,"owner_id")!=actor()||db.queryForObject("select count(*) from sys_notice_attachment where file_id=?",Long.class,id)>0)throw new ServiceException("已保存的公告附件请在公告编辑中移除");}
|
||||
else{require("system:file:remove","system:file:manage");if(number(row,"owner_id")!=actor()&&!has("system:file:manage"))throw new ServiceException("只能删除本人上传的文件",403);}
|
||||
db.update("update sys_managed_file set deleted=1,delete_time=current_timestamp where id=?",id);
|
||||
if(TransactionSynchronizationManager.isSynchronizationActive())TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCommit(){storage.discardFailedUpload(key(id),null);}});
|
||||
@ -92,4 +97,6 @@ public class ManagedFileService {
|
||||
private static void require(String... permissions){if(!has(permissions))throw new ServiceException("当前账号未开通该文件操作权限",403);}
|
||||
private static ServiceException missing(){return new ServiceException("文件或公告不存在,或当前账号无权访问",404);}
|
||||
private static void uuid(String id){if(id==null||!id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))throw missing();}
|
||||
private static void requireAppAdmin(){if(!SecurityUtils.isAdmin())throw new ServiceException("仅超级管理员可以管理App版本",403);}
|
||||
private boolean isApp(String id){return db.queryForObject("select count(*) from sys_mobile_package where file_id=?",Long.class,id)>0;}
|
||||
}
|
||||
|
||||
@ -0,0 +1,62 @@
|
||||
package com.ruoyi.system.service.impl;
|
||||
|
||||
import com.ruoyi.common.exception.ServiceException;
|
||||
import com.ruoyi.common.storage.BusinessFileStorage;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.system.domain.ManagedFileInfo;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/** Installation artifacts are private administration records, separate from shared documents. */
|
||||
@Service
|
||||
public class MobilePackageService {
|
||||
public static final int MAX_BYTES=250*1024*1024;
|
||||
private final JdbcTemplate db;private final BusinessFileStorage storage;private final ManagedFileService files;private final MobileReleaseService releases;private final TransactionTemplate tx;
|
||||
public MobilePackageService(JdbcTemplate db,BusinessFileStorage storage,ManagedFileService files,MobileReleaseService releases,TransactionTemplate tx){this.db=db;this.storage=storage;this.files=files;this.releases=releases;this.tx=tx;}
|
||||
public int authorize(){admin();return MAX_BYTES;}
|
||||
public static void validateName(String name){ManagedFileService.safeName(name);if(!name.toLowerCase(Locale.ROOT).endsWith(".apk"))throw new ServiceException("请选择本系统的APK安装包");}
|
||||
@Transactional public ManagedFileInfo upload(String id,MultipartFile file){
|
||||
admin();if(file==null||file.isEmpty()||file.getSize()>MAX_BYTES)throw new ServiceException("请选择不超过250MB的APK安装包");validateName(file.getOriginalFilename());
|
||||
Path temp=null;try{
|
||||
temp=Files.createTempFile("cmvr-app-package-",".apk");try(var in=file.getInputStream()){copy(in,temp,file.getSize(),null);}
|
||||
var parsed=releases.inspectPackage(temp);var result=files.uploadApp(id,file);register(id,parsed);return result;
|
||||
}catch(ServiceException e){throw e;}catch(Exception e){throw new ServiceException("安装包校验失败,请检查签名、版本和所属环境");}finally{discard(temp);}
|
||||
}
|
||||
public boolean alive(String id){admin();return files.appAlive(id)&&db.queryForObject("select count(*) from sys_mobile_package where file_id=? and environment=?",Long.class,id,releases.environment())==1;}
|
||||
public Map<String,Object> page(String keyword,int page,int size){
|
||||
admin();page=Math.max(1,page);size=Math.max(1,Math.min(100,size));String key=Objects.toString(keyword,"").trim();if(key.length()>180)throw new ServiceException("搜索内容过长");
|
||||
var latest=releases.latest();String hash=latest==null?"":latest.get("sha256").toString();long version=latest==null?0:((Number)latest.get("versionCode")).longValue();String like="%"+key.replace("!","!!").replace("%","!%").replace("_","!_")+"%";
|
||||
String where=" from sys_mobile_package p join sys_managed_file f on f.id=p.file_id where f.file_kind='LIBRARY' and f.deleted=0 and p.environment=? and (f.name like ? escape '!' or p.version_name like ? escape '!')";
|
||||
long total=db.queryForObject("select count(*)"+where,Long.class,releases.environment(),like,like);
|
||||
var rows=db.queryForList("select f.id,f.name,f.byte_size,f.sha256,f.create_by,f.create_time,p.version_code,p.version_name,p.runtime,p.notes,p.published_at"+where+" order by p.version_code desc,f.create_time desc,f.id desc limit ? offset ?",releases.environment(),like,like,size,(long)(page-1)*size).stream().map(row->{var value=new LinkedHashMap<String,Object>();value.put("id",row.get("id"));value.put("name",row.get("name"));value.put("size",row.get("byte_size"));value.put("versionName",row.get("version_name"));value.put("versionCode",row.get("version_code"));value.put("notes",row.get("notes"));value.put("uploadedBy",row.get("create_by"));value.put("uploadedAt",row.get("create_time"));value.put("publishedAt",row.get("published_at"));boolean current=hash.equals(row.get("sha256"));value.put("current",current);value.put("canPublish",!current&&((Number)row.get("version_code")).longValue()>version);value.put("canDownload",true);return value;}).toList();
|
||||
long legacy=db.queryForObject("select count(*) from sys_managed_file where file_kind='LIBRARY' and deleted=0 and not exists(select 1 from sys_mobile_package mp where mp.file_id=sys_managed_file.id) and lower(name) like '%.apk'",Long.class);
|
||||
var result=new LinkedHashMap<String,Object>();result.put("rows",rows);result.put("total",total);result.put("environment",releases.environment());result.put("current",latest);result.put("legacyCount",legacy);return result;
|
||||
}
|
||||
@Transactional public void remove(String id){admin();var current=releases.latest();var rows=db.queryForList("select f.sha256 from sys_managed_file f join sys_mobile_package p on p.file_id=f.id where f.id=? and f.file_kind='LIBRARY' and p.environment=? and f.deleted=0 for update",id,releases.environment());if(rows.isEmpty())throw new ServiceException("安装包不存在",404);if(current!=null&&Objects.equals(current.get("sha256"),rows.get(0).get("sha256")))throw new ServiceException("当前发布的安装包不可删除");files.remove(id);}
|
||||
/** Only packages with this system's signature, application ID and environment can move. */
|
||||
public Map<String,Object> migrateLibrary(){
|
||||
admin();var candidates=db.queryForList("select id,name from sys_managed_file where file_kind='LIBRARY' and deleted=0 and not exists(select 1 from sys_mobile_package mp where mp.file_id=sys_managed_file.id) and lower(name) like '%.apk' order by create_time,id limit 50");int moved=0;var skipped=new ArrayList<Map<String,String>>();
|
||||
for(var row:candidates){try{Boolean done=tx.execute(status->adopt(row.get("id").toString()));if(Boolean.TRUE.equals(done))moved++;}catch(Exception e){skipped.add(Map.of("name",row.get("name").toString(),"reason",e instanceof ServiceException?e.getMessage():"文件暂时无法读取"));}}
|
||||
return Map.of("moved",moved,"skipped",skipped);
|
||||
}
|
||||
private boolean adopt(String id){
|
||||
var rows=db.queryForList("select * from sys_managed_file where id=? and file_kind='LIBRARY' and deleted=0 for update",id);if(rows.isEmpty())return false;var row=rows.get(0);Path temp=null;
|
||||
try{long size=((Number)row.get("byte_size")).longValue();if(size<1||size>MAX_BYTES)throw new ServiceException("文件超过安装包大小限制");temp=Files.createTempFile("cmvr-app-migrate-",".apk");try(var in=storage.openStream("managed-file/"+id+".bin")){copy(in,temp,size,row.get("sha256").toString());}var parsed=releases.inspectPackage(temp);register(id,parsed);return true;
|
||||
}catch(ServiceException e){throw e;}catch(Exception e){throw new ServiceException("不是当前环境可用的本系统安装包");}finally{discard(temp);}
|
||||
}
|
||||
private void register(String id,Map<String,Object> parsed){
|
||||
if(db.queryForObject("select count(*) from sys_mobile_package where file_id=?",Long.class,id)>0)return;
|
||||
db.update("insert into sys_mobile_package(file_id,environment,version_code,version_name,runtime) values(?,?,?,?,?)",id,releases.environment(),parsed.get("v"),parsed.get("n"),parsed.get("r"));
|
||||
var latest=releases.latest();if(latest!=null&&db.queryForObject("select count(*) from sys_managed_file where id=? and sha256=?",Long.class,id,latest.get("sha256"))==1)db.update("update sys_mobile_package set notes=?,published_at=(select coalesce(update_time,create_time) from sys_config where config_key=?) where file_id=?",latest.get("notes"),"mobile.release."+releases.environment(),id);
|
||||
}
|
||||
private static void copy(InputStream input,Path path,long expected,String hash)throws Exception{var digest=MessageDigest.getInstance("SHA-256");long total=0;try(var output=Files.newOutputStream(path)){byte[] bytes=new byte[65536];for(int n;(n=input.read(bytes))!=-1;){total+=n;if(total>expected||total>MAX_BYTES)throw new ServiceException("安装包大小不匹配");digest.update(bytes,0,n);output.write(bytes,0,n);}}if(total!=expected||hash!=null&&!hash.equals(HexFormat.of().formatHex(digest.digest())))throw new ServiceException("安装包完整性校验失败");}
|
||||
private static void discard(Path path){if(path!=null)try{Files.deleteIfExists(path);}catch(IOException ignored){}}
|
||||
private static void admin(){if(!SecurityUtils.isAdmin())throw new ServiceException("仅超级管理员可以管理App版本",403);}
|
||||
}
|
||||
@ -23,10 +23,12 @@ public class MobileReleaseService {
|
||||
private final JdbcTemplate db;private final BusinessFileStorage storage;private final ObjectMapper json;private final String environment,key,signer;
|
||||
public MobileReleaseService(JdbcTemplate db,BusinessFileStorage storage,ObjectMapper json,Environment env){this.db=db;this.storage=storage;this.json=json;environment=env.matchesProfiles("prod")?"prod":"dev";key="mobile.release."+environment;signer=env.getProperty("mobile.release."+environment+".signing-sha256",environment.equals("prod")?"96ab3e7afc5f60668693feec01140bcf13611f73ed9e76fa806bf9657f3d939b":"fac61745dc0903786fb9ede62a962b399f7348f0bb6f899b8332667591033b9c");}
|
||||
public Map<String,Object> latest(){SecurityUtils.getUserId();var value=stored(false);return value.isEmpty()?null:view(value);}
|
||||
public String environment(){return environment;}
|
||||
public Map<String,Object> inspectPackage(Path path)throws Exception{return inspect(path,environment,json,signer);}
|
||||
@Transactional public Map<String,Object> publish(String id,String notes){
|
||||
admin();if(notes==null)notes="";notes=notes.trim();if(notes.length()>140)throw new ServiceException("更新说明最多140个字");
|
||||
if(id==null||!id.matches("[a-f0-9-]{36}"))throw new ServiceException("请选择文件库中的APK安装包");
|
||||
var rows=db.queryForList("select * from sys_managed_file where id=? and file_kind='LIBRARY' and deleted=0 for update",id);
|
||||
if(id==null||!id.matches("[a-f0-9-]{36}"))throw new ServiceException("请选择App版本管理中的安装包");
|
||||
var rows=db.queryForList("select f.* from sys_managed_file f join sys_mobile_package p on p.file_id=f.id where f.id=? and f.file_kind='LIBRARY' and f.deleted=0 and p.environment=? for update",id,environment);
|
||||
if(rows.isEmpty())throw new ServiceException("安装包不存在或已删除");var source=rows.get(0);long size=((Number)source.get("byte_size")).longValue();String hash=Objects.toString(source.get("sha256"),"");
|
||||
if(!source.get("name").toString().toLowerCase(Locale.ROOT).endsWith(".apk")||size<1||size>MAX||!hash.matches("[a-f0-9]{64}"))throw new ServiceException("请选择不超过250MB的APK安装包");
|
||||
Path temp=null;
|
||||
@ -41,11 +43,25 @@ public class MobileReleaseService {
|
||||
String object=object(value);if(!storage.exists(object,null))try(var in=Files.newInputStream(temp)){storage.saveStream(object,in,size,"application/vnd.android.package-archive");}else try(var in=storage.openStream(object)){var check=MessageDigest.getInstance("SHA-256");long n=0;byte[] buf=new byte[65536];for(int c;(c=in.read(buf))!=-1;){n+=c;if(n>size)throw new IOException();check.update(buf,0,c);}if(n!=size||!hash.equals(HexFormat.of().formatHex(check.digest())))throw new ServiceException("已有安装包对象校验失败,请联系管理员");}
|
||||
if(prior.isEmpty())db.update("insert into sys_config(config_name,config_key,config_value,config_type,create_by,create_time) values(?,?,?,'N',?,current_timestamp)","App安装包版本("+environment+")",key,encoded,SecurityUtils.getUsername());
|
||||
else db.update("update sys_config set config_value=?,update_by=?,update_time=current_timestamp where config_key=?",encoded,SecurityUtils.getUsername(),key);
|
||||
db.update("update sys_mobile_package set notes=?,published_at=current_timestamp where file_id=?",notes,id);
|
||||
return view(value);
|
||||
}catch(ServiceException e){throw e;}catch(Exception e){throw new ServiceException("安装包解析或发布失败,请检查文件和MinIO服务后重试");}
|
||||
finally{if(temp!=null)try{Files.deleteIfExists(temp);}catch(IOException ignored){}}
|
||||
}
|
||||
public record Download(long size,InputStream input){}
|
||||
public record RangedDownload(long size,long start,long length,InputStream input){}
|
||||
public RangedDownload openRange(String hash,String range){
|
||||
SecurityUtils.getUserId();var value=stored(false);
|
||||
if(value.isEmpty()||!Objects.equals(hash,value.get("h")))throw new ServiceException("版本已变更,请重新检查更新",409);
|
||||
long size=number(value,"s"),start,end;
|
||||
try {
|
||||
if(range==null||!range.matches("bytes=[0-9]{1,12}-[0-9]{1,12}"))throw new IllegalArgumentException();
|
||||
String[] bounds=range.substring(6).split("-",-1);start=Long.parseLong(bounds[0]);end=Long.parseLong(bounds[1]);
|
||||
if(start<0||end<start||start>=size||end>=size)throw new IllegalArgumentException();
|
||||
}catch(Exception invalid){throw new ServiceException("安装包下载范围无效,请重新检查更新",416);}
|
||||
try{return new RangedDownload(size,start,end-start+1,storage.openRange(object(value),start,end-start+1));}
|
||||
catch(IOException e){throw new ServiceException("安装包暂时无法下载,请稍后重试");}
|
||||
}
|
||||
public Download open(String hash){SecurityUtils.getUserId();var value=stored(false);if(value.isEmpty()||!Objects.equals(hash,value.get("h")))throw new ServiceException("版本已变更,请重新检查更新",409);try{return new Download(number(value,"s"),storage.openStream(object(value)));}catch(IOException e){throw new ServiceException("安装包暂时无法下载,请稍后重试");}}
|
||||
private Map<String,Object> stored(boolean lock){var rows=db.queryForList("select config_value from sys_config where config_key=?"+(lock?" for update":""),key);if(rows.isEmpty())return Map.of();if(rows.size()!=1)throw new ServiceException("App版本配置重复,请联系管理员");try{var value=json.readValue(rows.get(0).get("config_value").toString(),Map.class);if(!Objects.toString(value.get("h"),"").matches("[a-f0-9]{64}")||number(value,"v")<1||number(value,"s")<1||number(value,"s")>MAX||!Objects.toString(value.get("r"),"").matches("[a-f0-9]{40,64}")||!(value.get("n") instanceof String name)||name.isBlank()||name.length()>32||!(value.getOrDefault("note","") instanceof String note)||note.length()>140)throw new IllegalArgumentException();return value;}catch(Exception e){throw new ServiceException("App版本配置无效,请联系管理员");}}
|
||||
private Map<String,Object> view(Map<String,Object> v){return Map.of("versionCode",number(v,"v"),"versionName",v.get("n"),"sha256",v.get("h"),"size",number(v,"s"),"notes",v.getOrDefault("note",""),"runtime",v.get("r"),"environment",environment,"downloadPath","/system/mobile-release/"+v.get("h")+"/content");}
|
||||
|
||||
@ -145,7 +145,8 @@ public class SysMenuServiceImpl implements ISysMenuService
|
||||
}
|
||||
else
|
||||
{
|
||||
menus = menuMapper.selectMenuTreeByUserId(userId);
|
||||
menus = new java.util.ArrayList<>(menuMapper.selectMenuTreeByUserId(userId));
|
||||
menus.removeIf(menu -> "system/mobileRelease/index".equals(menu.getComponent()) || "system:mobile-release:manage".equals(menu.getPerms()));
|
||||
}
|
||||
return getChildPerms(menus, MENU_ROOT_ID);
|
||||
}
|
||||
|
||||
@ -11,6 +11,9 @@ import com.ruoyi.common.core.domain.BaseEntity;
|
||||
public class InRecord extends BaseEntity
|
||||
{
|
||||
private static final long serialVersionUID = 1L;
|
||||
private Boolean onlyMine;
|
||||
public Boolean getOnlyMine(){return onlyMine;}
|
||||
public void setOnlyMine(Boolean value){onlyMine=value;}
|
||||
@Excel(name="业务日期",dateFormat="yyyy-MM-dd")
|
||||
private java.time.LocalDate businessDate;
|
||||
public java.time.LocalDate getBusinessDate(){return businessDate;}
|
||||
|
||||
@ -7,6 +7,7 @@ import com.ruoyi.warehouse.domain.PurchaseBatch;
|
||||
public interface PurchaseBatchMapper
|
||||
{
|
||||
List<PurchaseBatch> selectPurchaseBatchList(PurchaseBatch batch);
|
||||
java.util.Map<String, Object> selectPurchaseBatchTotals(PurchaseBatch batch);
|
||||
List<PurchaseBatch> selectPurchaseBatchOptions(@Param("keyword") String keyword);
|
||||
List<PurchaseBatch> selectPurchaseBatchFilterOptions(@Param("keyword") String keyword);
|
||||
PurchaseBatch selectPurchaseBatchById(Long id);
|
||||
@ -14,6 +15,7 @@ public interface PurchaseBatchMapper
|
||||
PurchaseBatch selectPurchaseBatchByNo(String batchNo);
|
||||
int insertPurchaseBatch(PurchaseBatch batch);
|
||||
int updatePurchaseBatch(PurchaseBatch batch);
|
||||
int updateBatchRemark(@Param("id") Long id, @Param("remark") String remark, @Param("username") String username);
|
||||
int countRequestsByBatchId(Long batchId);
|
||||
List<Long> selectBatchProjectIds(Long batchId);
|
||||
int countBatchDocuments(Long batchId);
|
||||
|
||||
@ -44,6 +44,7 @@ public class InRecordServiceImpl implements IInRecordService
|
||||
@Override
|
||||
public List<InRecord> selectInRecordList(InRecord inRecord)
|
||||
{
|
||||
com.ruoyi.warehouse.util.PendingReceiptScope.bind(inRecord);
|
||||
return inRecordMapper.selectInRecordList(inRecord);
|
||||
}
|
||||
|
||||
|
||||
@ -76,6 +76,6 @@ import com.ruoyi.warehouse.service.*;
|
||||
private static BigDecimal zero(BigDecimal value){return value==null?BigDecimal.ZERO:value;}
|
||||
private static String hash(Row row){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(com.alibaba.fastjson2.JSON.toJSONString(row).getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
private Long insert(String sql,Object... values){var holder=new GeneratedKeyHolder();db.update(connection->{var statement=connection.prepareStatement(sql,java.sql.Statement.RETURN_GENERATED_KEYS);for(int i=0;i<values.length;i++)statement.setObject(i+1,values[i]);return statement;},holder);return Objects.requireNonNull(holder.getKey()).longValue();}
|
||||
private static void permission(String kind){if(SecurityUtils.isAdmin())return;boolean use=SecurityUtils.hasPermi("project:inventory:use");boolean allowed=switch(kind){case "STOCK"->use&&SecurityUtils.hasPermi("warehouse:in:add")&&SecurityUtils.hasPermi("warehouse:in:confirm");case "LOAN"->use;case "PURCHASE"->SecurityUtils.hasPermi("warehouse:purchase:import")||SecurityUtils.hasPermi("warehouse:purchase:manage");default->false;};if(!allowed)throw fail("没有对应初始化业务权限");}
|
||||
private static void permission(String kind){if("LOAN".equals(kind))throw fail("借用与归还功能已停用");if(SecurityUtils.isAdmin())return;boolean use=SecurityUtils.hasPermi("project:inventory:use");boolean allowed=switch(kind){case "STOCK"->use&&SecurityUtils.hasPermi("warehouse:in:add")&&SecurityUtils.hasPermi("warehouse:in:confirm");case "LOAN"->use;case "PURCHASE"->SecurityUtils.hasPermi("warehouse:purchase:import")||SecurityUtils.hasPermi("warehouse:purchase:manage");default->false;};if(!allowed)throw fail("没有对应初始化业务权限");}
|
||||
private static ServiceException fail(String message){return new ServiceException(message);}
|
||||
}
|
||||
|
||||
@ -11,7 +11,9 @@ import com.ruoyi.warehouse.mapper.InRecordMapper;
|
||||
@Autowired private JdbcTemplate db;
|
||||
@Autowired private InRecordMapper records;
|
||||
public Map<String,Object> page(InRecord q,int page,int size){
|
||||
com.ruoyi.warehouse.util.PendingReceiptScope.bind(q);
|
||||
var args=new ArrayList<Object>();var where=new StringBuilder(" where ir.in_status=0");
|
||||
if(Boolean.TRUE.equals(q.getOnlyMine())){where.append(" and (case when ir.purchase_request_id is not null then pr.create_by=? when ir.production_task_id is not null then exists(select 1 from production_task task where task.id=ir.production_task_id and task.create_by=?) else ir.operator=? end)");args.addAll(Collections.nCopies(3,q.getParams().get("onlyMineUser")));}
|
||||
where.append(" and ").append(com.ruoyi.warehouse.util.AmountDisplayPolicy.visibleSql("case when ir.purchase_request_id is not null then pr.final_unit_price else ir.receipt_unit_cost end"));
|
||||
if(q.getPurchaseBatchId()!=null){where.append(" and pr.purchase_batch_id=?");args.add(q.getPurchaseBatchId());}if(q.getProductionTaskId()!=null){where.append(" and ir.production_task_id=?");args.add(q.getProductionTaskId());}
|
||||
if(q.getSourceProjectId()!=null){where.append(" and ir.source_project_id=?");args.add(q.getSourceProjectId());}if(q.getSupplierId()!=null){where.append(" and pb.supplier_id=?");args.add(q.getSupplierId());}
|
||||
@ -26,6 +28,7 @@ import com.ruoyi.warehouse.mapper.InRecordMapper;
|
||||
long itemTotal=db.queryForObject("select coalesce(sum(recordCount),0) from ("+sql+") grouped",Long.class,args.toArray());return Map.of("rows",db.queryForList(sql+" order by title limit ? offset ?",values.toArray()),"total",total,"itemTotal",itemTotal);
|
||||
}
|
||||
public List<InRecord> group(String key,InRecord q){
|
||||
com.ruoyi.warehouse.util.PendingReceiptScope.bind(q);
|
||||
com.ruoyi.warehouse.util.AmountDisplayPolicy.forView(q);
|
||||
if(key==null||!key.matches("[BPO]:[0-9]{1,18}"))throw new ServiceException("来源编号无效");long id=Long.parseLong(key.substring(2));q.setInStatus(0);
|
||||
if(key.startsWith("B:"))q.setPurchaseBatchId(id);else if(key.startsWith("P:"))q.setProductionTaskId(id);else {var row=records.selectInRecordById(id);if(row==null||!Integer.valueOf(0).equals(row.getInStatus()))return List.of();q.setInNo(row.getInNo());return records.selectInRecordList(q).stream().filter(r->java.util.Objects.equals(r.getId(),id)).toList();}
|
||||
|
||||
@ -576,6 +576,8 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
if (StringUtils.isBlank(request.getPurchasePurpose())) request.setPurchasePurpose("SELF");
|
||||
if ("SELF".equals(request.getPurchasePurpose())) request.setLoanId(null);
|
||||
else if ("REPAY".equals(request.getPurchasePurpose())) {
|
||||
var previousPurpose = request.getId() == null ? null : purchaseRequestMapper.selectPurchaseRequestById(request.getId(), null);
|
||||
if (previousPurpose == null || !"REPAY".equals(previousPurpose.getPurchasePurpose()) || !java.util.Objects.equals(previousPurpose.getLoanId(), request.getLoanId())) throw new ServiceException("借用与归还功能已停用,不能新增归还借用采购");
|
||||
var loan=loans.validatePurchase(request.getLoanId(),request.getProjectId(),request.getProductId());
|
||||
BigDecimal already=request.getId()==null?BigDecimal.ZERO:taskDatabase.queryForObject("select coalesce(sum(in_num),0) from in_record where purchase_request_id=? and in_status=1 and receipt_root=0",BigDecimal.class,request.getId());
|
||||
if(request.getQuantity().subtract(already).compareTo(loan.getOutstandingQuantity())>0)throw new ServiceException("归还采购数量超过待归还数量,多出部分请拆为自用采购");
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
package com.ruoyi.warehouse.util;
|
||||
import com.ruoyi.common.utils.SecurityUtils;
|
||||
import com.ruoyi.warehouse.domain.InRecord;
|
||||
/** Personal filtering follows the creator of the source, never a client-supplied account. */
|
||||
public final class PendingReceiptScope {
|
||||
private PendingReceiptScope(){}
|
||||
public static void bind(InRecord query){if(Boolean.TRUE.equals(query.getOnlyMine()))query.getParams().put("onlyMineUser",SecurityUtils.getUsername());else query.getParams().remove("onlyMineUser");}
|
||||
}
|
||||
@ -71,6 +71,11 @@
|
||||
<include refid="selectInRecordVo"/>
|
||||
<where>
|
||||
not (ir.receipt_root=1 and ir.in_status=1)
|
||||
<if test="onlyMine == true">
|
||||
and (case when ir.purchase_request_id is not null then purchase.create_by = #{params.onlyMineUser}
|
||||
when ir.production_task_id is not null then exists(select 1 from production_task task where task.id=ir.production_task_id and task.create_by = #{params.onlyMineUser})
|
||||
else ir.operator = #{params.onlyMineUser} end)
|
||||
</if>
|
||||
<if test="params.amountDisplay == true">and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or case when ir.purchase_request_id is not null then purchase.final_unit_price else ir.receipt_unit_cost end is null or case when ir.purchase_request_id is not null then purchase.final_unit_price else ir.receipt_unit_cost end<>0)</if>
|
||||
<if test="inNo != null and inNo != ''">and ir.in_no like concat('%', #{inNo}, '%')</if>
|
||||
<if test="keyword != null and keyword != ''">and convert(concat_ws(' ',ir.in_no,ir.source_no,purchase.purchase_batch_no,pi.product_name,pi.brand,pi.spec) using utf8mb4) collate utf8mb4_unicode_ci like convert(concat('%',#{keyword},'%') using utf8mb4) collate utf8mb4_unicode_ci</if>
|
||||
|
||||
@ -25,7 +25,7 @@
|
||||
<result property="updateTime" column="update_time"/>
|
||||
</resultMap>
|
||||
|
||||
<select id="selectPurchaseBatchList" parameterType="PurchaseBatch" resultMap="PurchaseBatchResult">
|
||||
<sql id="batchListQuery">
|
||||
select pb.id, pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
|
||||
pb.create_by, pb.create_time, pb.update_by, pb.update_time, count(pr.id) as request_count,
|
||||
group_concat(distinct pj.project_name order by pj.project_name separator '、') project_names,
|
||||
@ -65,7 +65,9 @@
|
||||
<if test='progress == "open"'>having open_count>0</if>
|
||||
<if test='progress == "completed"'>having open_count=0</if>
|
||||
order by pb.id desc
|
||||
</select>
|
||||
</sql>
|
||||
<select id="selectPurchaseBatchList" parameterType="PurchaseBatch" resultMap="PurchaseBatchResult"><include refid="batchListQuery"/></select>
|
||||
<select id="selectPurchaseBatchTotals" parameterType="PurchaseBatch" resultType="map">select sum(actual_total_amount) as actualTotalAmount, sum(total_amount) as totalAmount, sum(unpriced_count) as unpricedCount from (<include refid="batchListQuery"/>) totals</select>
|
||||
|
||||
<select id="selectPurchaseBatchOptions" parameterType="String" resultMap="PurchaseBatchResult">
|
||||
select pb.id,pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name, pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
|
||||
@ -110,6 +112,7 @@
|
||||
values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate(),#{supplierId},#{businessDate})
|
||||
</insert>
|
||||
|
||||
<update id="updateBatchRemark">update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id}</update>
|
||||
<update id="updatePurchaseBatch" parameterType="PurchaseBatch">
|
||||
update purchase_batch
|
||||
set supplier_id=#{supplierId},business_date=#{businessDate}, batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus},
|
||||
|
||||
5
ruoyi-ui-vue3/src/api/system/mobile-release.js
Normal file
5
ruoyi-ui-vue3/src/api/system/mobile-release.js
Normal file
@ -0,0 +1,5 @@
|
||||
import request from '@/utils/request'
|
||||
export const listAppPackages=(params,signal)=>request({url:'/system/mobile-release/packages',params,signal})
|
||||
export const publishAppPackage=data=>request({url:'/system/mobile-release',method:'post',data,timeout:180000})
|
||||
export const removeAppPackage=id=>request({url:'/system/mobile-release/packages/'+id,method:'delete'})
|
||||
export const migrateAppPackages=()=>request({url:'/system/mobile-release/packages/migrate-library',method:'post',timeout:180000})
|
||||
@ -114,3 +114,5 @@ export function delPurchase(ids) {
|
||||
}
|
||||
export const preparePurchaseSheet = (ids,batchId) => request({url:'/warehouse/purchase/sheet/prepare',method:'post',data:ids,params:{batchId}})
|
||||
export const getUnbatchedSheet = ids => request({url:'/warehouse/purchase/sheet/unbatched',method:'get',params:{ids:ids.join(',')}})
|
||||
|
||||
export function updatePurchaseBatchRemark(id, remark) { return request({url: `/warehouse/purchase/batch/${id}/remark`, method: 'put', data: {remark}}) }
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<template><el-dialog title="可选历史补录" v-model="visible" width="min(1200px,98vw)" append-to-body :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy">
|
||||
<el-alert title="历史补录不是启用前提。库存、采购、借用分别录入;不自动覆盖已有数据。采购导入后仍需在采购页锁价才计费。" type="info" :closable="false"/>
|
||||
<el-form inline class="mt10 dialog-filter-form"><el-form-item label="补录类型"><el-select v-model="kind" :disabled="busy" @change="changeKind"><el-option label="期初库存" value="STOCK"/><el-option label="历史采购" value="PURCHASE"/><el-option label="历史借用余额" value="LOAN"/></el-select></el-form-item><el-form-item><el-button @click="download(`warehouse/initialization/${kind}/template`,{},`${kind}模板.xlsx`)">下载模板</el-button></el-form-item><el-form-item><el-upload action="#" :show-file-list="false" :http-request="read" :disabled="busy" accept=".xlsx,.xls"><el-button :loading="busy">选择Excel并预览</el-button></el-upload></el-form-item><el-form-item><el-button @click="add" :disabled="busy">手工增加一行</el-button></el-form-item></el-form>
|
||||
<el-alert title="历史补录不是启用前提。库存、采购分别录入;不自动覆盖已有数据。采购导入后仍需在采购页锁价才计费。" type="info" :closable="false"/>
|
||||
<el-form inline class="mt10 dialog-filter-form"><el-form-item label="补录类型"><el-select v-model="kind" :disabled="busy" @change="changeKind"><el-option label="期初库存" value="STOCK"/><el-option label="历史采购" value="PURCHASE"/></el-select></el-form-item><el-form-item><el-button @click="download(`warehouse/initialization/${kind}/template`,{},`${kind}模板.xlsx`)">下载模板</el-button></el-form-item><el-form-item><el-upload action="#" :show-file-list="false" :http-request="read" :disabled="busy" accept=".xlsx,.xls"><el-button :loading="busy">选择Excel并预览</el-button></el-upload></el-form-item><el-form-item><el-button @click="add" :disabled="busy">手工增加一行</el-button></el-form-item></el-form>
|
||||
<p v-if="kind==='PURCHASE'">“数量”填原净采购总量;已入库数量留空视为全部已入库,填0表示尚未入库。已入库部分只归档;剩余部分继续采购,已验收部分恢复待入库。原日期必填。</p>
|
||||
<p v-if="kind==='LOAN'">“项目编码”为借入项目;历史已还与后续新归还共同累计,补录本身不移动库存。</p>
|
||||
<el-table :data="rows" border max-height="460"><el-table-column prop="line" label="行" width="70" show-overflow-tooltip/><el-table-column v-for="c in columns" :key="c[0]" :label="c[1]" min-width="145" class-name="business-control-cell"><template #default="s"><el-input v-model="s.row.row[c[0]]" size="small" :disabled="busy || s.row.done" @update:model-value="s.row.error='已修改,请重新校验';validated=false"/></template></el-table-column><el-table-column label="结果" width="190" fixed="right" class-name="business-operation-cell"><template #default="s">{{ s.row.done?'已导入':s.row.error||'校验通过' }}<el-button v-if="!s.row.done" link type="primary" :disabled="busy" @click="rows.splice(s.$index,1)">移除本行</el-button></template></el-table-column></el-table>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<section class="managed-upload">
|
||||
<div class="upload-toolbar"><input ref="input" type="file" multiple hidden :disabled="disabled||running" @change="choose"/><el-button type="primary" :icon="UploadFilled" :disabled="disabled||running||modelValue.length>=limit" @click="input.click()">{{ buttonText }}</el-button><span class="upload-hint">单文件最多 1GB · 支持断点续传、秒传</span><el-button v-if="showCompleted&&jobs.some(j=>j.status==='done')" link :disabled="running" @click="jobs=jobs.filter(j=>j.status!=='done')">清空已完成</el-button></div>
|
||||
<div class="upload-toolbar"><input ref="input" type="file" multiple hidden :accept="purpose==='appRelease'?'.apk':undefined" :disabled="disabled||running" @change="choose"/><el-button type="primary" :icon="UploadFilled" :disabled="disabled||running||modelValue.length>=limit" @click="input.click()">{{ buttonText }}</el-button><span class="upload-hint">{{ purpose==='appRelease'?'APK · 单个最多250MB':'单文件最多 1GB' }} · 支持断点续传、秒传</span><el-button v-if="showCompleted&&jobs.some(j=>j.status==='done')" link :disabled="running" @click="jobs=jobs.filter(j=>j.status!=='done')">清空已完成</el-button></div>
|
||||
<div v-if="visibleJobs.length" class="upload-jobs" aria-live="polite"><article v-for="job in visibleJobs" :key="job.key" class="upload-job"><div class="upload-name" :title="job.file.name">{{ job.file.name }}</div><div class="upload-stage"><el-progress :percentage="job.progress" :status="job.status==='done'?'success':job.status==='failed'?'exception':undefined" :stroke-width="5"/><small>{{ job.error||job.label }}</small></div><el-button v-if="job.status==='uploading'" link type="warning" @click="job.controller?.abort()">暂停</el-button><el-button v-else-if="job.status==='failed'" link type="primary" :disabled="disabled||running" @click="retry(job)">重试</el-button><el-button v-if="job.status!=='uploading'" link :disabled="running" @click="removeJob(job)">{{ job.status==='done'?'清除记录':'移除' }}</el-button></article></div>
|
||||
</section>
|
||||
</template>
|
||||
@ -17,7 +17,7 @@ const pending=computed(()=>running.value||jobs.value.some(j=>j.status==='failed'
|
||||
const visibleJobs=computed(()=>jobs.value.filter(j=>props.showCompleted||j.status!=='done'))
|
||||
watch(pending,v=>emit('pending',v),{immediate:true})
|
||||
async function removeJob(job){if(job.status==='failed'&&job.sessionId)try{await cancelFileTransfer(job.sessionId)}catch(error){ElMessage.error(error.message||'取消上传失败,请重试');return}jobs.value=jobs.value.filter(j=>j.key!==job.key)}
|
||||
async function choose(event){const files=[...event.target.files];event.target.value='';if(props.disabled||running.value)return;const room=props.limit-props.modelValue.length-jobs.value.filter(j=>j.status!=='done').length;const selected=[];for(const file of files){if(selected.length>=room){ElMessage.warning('最多选择'+props.limit+'个文件');break}if(!file.size||file.size>1024**3){ElMessage.warning(file.name+':请选择非空文件,单个不超过1GB');continue}selected.push(reactive({key:++nextJob,file,status:'queued',progress:0,label:'等待上传',error:''}))}jobs.value.push(...selected);for(const job of selected)await upload(job)}
|
||||
async function choose(event){const files=[...event.target.files];event.target.value='';if(props.disabled||running.value)return;const room=props.limit-props.modelValue.length-jobs.value.filter(j=>j.status!=='done').length;const selected=[];for(const file of files){if(selected.length>=room){ElMessage.warning('最多选择'+props.limit+'个文件');break}const app=props.purpose==='appRelease';if(app&&!/\.apk$/i.test(file.name)){ElMessage.warning('请选择APK安装包');continue}if(!file.size||file.size>(app?250*1024**2:1024**3)){ElMessage.warning(file.name+':请选择非空文件,单个不超过'+(app?'250MB':'1GB'));continue}selected.push(reactive({key:++nextJob,file,status:'queued',progress:0,label:'等待上传',error:''}))}jobs.value.push(...selected);for(const job of selected)await upload(job)}
|
||||
async function retry(job){job.progress=0;await upload(job)}
|
||||
async function upload(job){if(disposed||props.disabled||running.value)return;const ctl=new AbortController();job.controller=ctl;job.status='uploading';job.error='';running.value=true
|
||||
try{const result=await uploadFileResumable(job.file,{purpose:props.purpose},{signal:ctl.signal,onProgress:p=>{if(p.sessionId)job.sessionId=p.sessionId;const value=p.phase==='complete'?100:p.phase==='finalizing'?98:p.phase==='uploading'?10+p.percent*.85:p.percent*.1;job.progress=Math.min(100,Math.max(job.progress,Math.round(value)));job.label=p.phase==='hashing'?'正在校验文件':p.phase==='finalizing'?'正在保存文件':p.phase==='complete'?'上传完成':p.resumed?'正在继续上传':'正在上传'}});if(disposed)return;job.status='done';job.progress=100;job.label=result.transfer?.instant?'秒传完成':'上传完成';if(!props.modelValue.some(f=>f.id===result.data.id))emit('update:modelValue',[...props.modelValue,result.data]);emit('uploaded',result.data);await nextTick()}
|
||||
|
||||
@ -1,11 +1,4 @@
|
||||
<template><div>
|
||||
<el-form-item label="采购用途"><el-radio-group :model-value="purpose || 'SELF'" :disabled="disabled" @update:model-value="changePurpose"><el-radio value="SELF">本项目使用</el-radio><el-radio value="REPAY">归还借用</el-radio></el-radio-group></el-form-item>
|
||||
<el-form-item v-if="purpose==='REPAY'" label="归还哪笔借用"><el-select :model-value="loanId" :disabled="disabled" @update:model-value="$emit('update:loanId',$event)" :loading="loading" filterable style="width:100%" placeholder="请先选择采购项目和物品">
|
||||
<el-option v-for="l in options" :key="l.id" :label="l.lenderProjectName+' / '+l.itemName+' / 未还 '+l.outstandingQuantity+' '+(l.unit||'')" :value="l.id"/>
|
||||
<el-option v-if="loanId && !options.some(l=>l.id===loanId)" :value="loanId" :label="'当前借用 #'+loanId+'(已归还或非待还)'"/>
|
||||
</el-select></el-form-item>
|
||||
</div></template>
|
||||
<template><span v-if="purpose==='REPAY'" class="text-muted">历史采购用途</span></template>
|
||||
<script>
|
||||
import { loanOptions } from '@/api/project/loan'
|
||||
export default {name:'PurchasePurpose',props:{purpose:String,loanId:[Number,String],projectId:[Number,String],itemId:[Number,String],disabled:Boolean},data:()=>({options:[],loading:false,request:0}),watch:{projectId:'load',itemId:'load',purpose:'load'},mounted(){this.load()},methods:{changePurpose(v){this.$emit('update:purpose',v);if(v==='SELF')this.$emit('update:loanId',null)},load(){const id=++this.request;this.options=[];this.loading=false;if(this.purpose!=='REPAY'||!this.projectId||!this.itemId)return;this.loading=true;loanOptions({projectId:this.projectId,itemId:this.itemId}).then(r=>{if(id===this.request)this.options=(r.data||[]).filter(l=>Number(l.borrowerProjectId)===Number(this.projectId))}).finally(()=>{if(id===this.request)this.loading=false})}}}
|
||||
export default {name:'PurchasePurpose',props:{purpose:String,loanId:[Number,String],projectId:[Number,String],itemId:[Number,String],disabled:Boolean}}
|
||||
</script>
|
||||
|
||||
@ -6,14 +6,15 @@
|
||||
<div class="list-actions__secondary budget-totals"><span>项目总金额 <strong>{{ money(totalAmount) }}</strong></span><span>分类预算合计 <strong>{{ money(rows.reduce((s,r)=>s+Number(r.budgetAmount||0),0)) }}</strong></span></div>
|
||||
</div>
|
||||
<div v-if="loadError" role="alert">{{ loadError }} <el-button link @click="load">重试</el-button></div></template>
|
||||
<template #default="{tableHeight}"><business-table :height="tableHeight" :data="rows" border v-loading="loading"><el-table-column prop="categoryName" label="费用分类" show-overflow-tooltip min-width="160"/><el-table-column label="分类预算" show-overflow-tooltip min-width="100"><template #default="s">{{ money(s.row.budgetAmount) }}</template></el-table-column><el-table-column label="已锁定采购费用" show-overflow-tooltip min-width="115"><template #default="s">{{ money(s.row.spentAmount) }}</template></el-table-column><el-table-column label="剩余额度" show-overflow-tooltip min-width="100"><template #default="s">{{ money(s.row.availableAmount) }}</template></el-table-column><el-table-column label="操作" align="center" width="100" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" @click="edit(s.row)" v-if="$can(['project:budget:edit','project:project:manage'])">调整</el-button></template></el-table-column></business-table></template>
|
||||
<template #default="{tableHeight}"><business-table :height="tableHeight" :data="rows" border v-loading="loading"><el-table-column prop="categoryName" label="费用分类" show-overflow-tooltip min-width="160"/><el-table-column label="分类预算" show-overflow-tooltip min-width="150" align="right"><template #default="s">{{ money(s.row.budgetAmount) }}</template></el-table-column><el-table-column label="已锁定采购费用" show-overflow-tooltip min-width="150" align="right"><template #default="s">{{ money(s.row.spentAmount) }}</template></el-table-column><el-table-column label="剩余额度" show-overflow-tooltip min-width="150" align="right"><template #default="s">{{ money(s.row.availableAmount) }}</template></el-table-column><el-table-column label="操作" align="center" width="100" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" @click="edit(s.row)" v-if="$can(['project:budget:edit','project:project:manage'])">调整</el-button></template></el-table-column></business-table></template>
|
||||
<template #footer></template>
|
||||
<template #dialogs><el-dialog title="分类预算" v-model="visible" :before-close="closeEditor" width="480px" append-to-body :close-on-click-modal="!saving" :close-on-press-escape="!saving" :show-close="!saving"><el-form label-width="auto" :disabled="saving"><el-form-item label="费用分类" :disabled="saving"><el-select v-model="form.expenseCategoryId" :disabled="!!form.id"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item><el-form-item label="预算金额" :disabled="saving"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2"/></el-form-item><el-form-item label="备注" :disabled="saving"><el-input v-model="form.remark"/></el-form-item></el-form><template #footer><div ><el-button :disabled="saving" @click="closeEditor()">取消</el-button><el-button type="primary" :loading="saving" @click="save">保存</el-button></div></template></el-dialog><el-dialog title="经费流水" v-model="ledgerOpen" width="min(1100px,96vw)" append-to-body><el-table :data="ledgerRows" max-height="450"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="createTime" label="时间" width="165" show-overflow-tooltip/><el-table-column prop="categoryName" label="分类" show-overflow-tooltip min-width="160"/><el-table-column prop="bizNo" label="业务单号" min-width="150" show-overflow-tooltip/><el-table-column prop="budgetDelta" label="预算变化" show-overflow-tooltip min-width="100"/><el-table-column prop="spentDelta" label="费用变化" show-overflow-tooltip min-width="100"/><el-table-column prop="operator" label="操作人" show-overflow-tooltip min-width="100"/><el-table-column prop="remark" label="说明" min-width="180" show-overflow-tooltip/></el-table><pagination :total="ledgerTotal" v-model:page="ledgerQuery.pageNum" v-model:limit="ledgerQuery.pageSize" @pagination="loadLedger"/></el-dialog></template>
|
||||
<template #dialogs><el-dialog title="分类预算" v-model="visible" :before-close="closeEditor" width="480px" append-to-body :close-on-click-modal="!saving" :close-on-press-escape="!saving" :show-close="!saving"><el-form label-width="auto" :disabled="saving"><el-form-item label="费用分类" :disabled="saving"><el-select v-model="form.expenseCategoryId" :disabled="!!form.id"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item><el-form-item label="预算金额" :disabled="saving"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2"/></el-form-item><el-form-item label="备注" :disabled="saving"><el-input v-model="form.remark"/></el-form-item></el-form><template #footer><div ><el-button :disabled="saving" @click="closeEditor()">取消</el-button><el-button type="primary" :loading="saving" @click="save">保存</el-button></div></template></el-dialog><el-dialog title="经费流水" v-model="ledgerOpen" width="min(1100px,96vw)" append-to-body><el-table :data="ledgerRows" max-height="450"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="createTime" label="时间" width="165" show-overflow-tooltip/><el-table-column prop="categoryName" label="分类" show-overflow-tooltip min-width="160"/><el-table-column prop="bizNo" label="业务单号" min-width="150" show-overflow-tooltip/><el-table-column prop="budgetDelta" label="预算变化" show-overflow-tooltip min-width="150" align="right" :formatter="(row,column,value)=>money(value)"/><el-table-column prop="spentDelta" label="费用变化" show-overflow-tooltip min-width="150" align="right" :formatter="(row,column,value)=>money(value)"/><el-table-column prop="operator" label="操作人" show-overflow-tooltip min-width="100"/><el-table-column prop="remark" label="说明" min-width="180" show-overflow-tooltip/></el-table><pagination :total="ledgerTotal" v-model:page="ledgerQuery.pageNum" v-model:limit="ledgerQuery.pageSize" @pagination="loadLedger"/></el-dialog></template>
|
||||
</business-list-page></template>
|
||||
<script>
|
||||
import {listProjectBudget,categoryOptions,saveProjectBudget,listFundLedger} from '@/api/project/project'
|
||||
import {runLatest,queryError} from '@/utils/query-session'
|
||||
import {createEditSession,registerEditGuard} from '@/utils/edit-session'
|
||||
import { formatMoney } from '@/utils/money-display'
|
||||
export default {
|
||||
props:{projectId:Number,totalAmount:[Number,String]},
|
||||
data:()=>({rows:[],categories:[],visible:false,form:{},saving:false,loading:false,loadError:'',ledgerOpen:false,ledgerRows:[],ledgerTotal:0,ledgerQuery:{pageNum:1,pageSize:20}}),
|
||||
@ -24,7 +25,7 @@ export default {
|
||||
},
|
||||
beforeUnmount(){this._unregisterEdit?.()},
|
||||
methods:{
|
||||
money(v){return Number(v||0).toFixed(2)},
|
||||
money:formatMoney,
|
||||
load(){return runLatest(this,'budget',()=>listProjectBudget(this.projectId),{start:()=>{this.loading=true;this.loadError=''},success:r=>{this.rows=r.data||[]},error:e=>{this.loadError=queryError(e)},finish:()=>{this.loading=false}})},
|
||||
loadLedger(){this.ledgerOpen=true;return runLatest(this,'ledger',()=>listFundLedger({...this.ledgerQuery,projectId:this.projectId}),{success:r=>{this.ledgerRows=r.rows||[];this.ledgerTotal=r.total||0}})},
|
||||
async edit(row){try{this.categories=(await categoryOptions()).data||[];this.form=row?{...row,budgetAmount:Number(row.budgetAmount)}:{projectId:this.projectId,budgetAmount:0,expenseCategoryId:undefined,remark:''};this._editSession.markClean();this.visible=true}catch(_){/* request handler reports failure */}},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user