From 6b43b0104f63dcbebad2fbc96868875589a5c08d Mon Sep 17 00:00:00 2001 From: lixiaolong <702156524@qq.com> Date: Fri, 30 Oct 2026 15:02:54 +0800 Subject: [PATCH] =?UTF-8?q?feat(app):=20=E4=BC=98=E5=8C=96=E7=A7=BB?= =?UTF-8?q?=E5=8A=A8=E7=AB=AF=E5=BA=94=E7=94=A8=E9=85=8D=E7=BD=AE=E5=92=8C?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加生产环境服务器地址配置支持内外网切换 - 实现采购列表只看我创建的功能开关 - 更新构建脚本中的默认生产环境API地址 - 优化采购单表格单元格编辑体验改用自动补全组件 - 调整应用更新检查逻辑增强生产环境兼容性 - 修复开发服务器切换时的一些验证问题 - 增强应用启动时的服务地址配置灵活性 --- mobile-app/app.config.js | 4 +- mobile-app/fingerprint.config.cjs | 2 + .../plugins/native/CmvrPackageTransfer.java | 105 ++++++++++++++++ mobile-app/plugins/with-apk-installer.cjs | 37 ++++++ mobile-app/release-notes.json | 7 ++ mobile-app/scripts/export-update.mjs | 3 +- mobile-app/scripts/publish-update.mjs | 5 +- mobile-app/scripts/test-native-download.cjs | 6 + mobile-app/scripts/verify-development-ota.mjs | 3 +- mobile-app/src/App.tsx | 9 +- mobile-app/src/AppUpdateDialog.tsx | 10 +- mobile-app/src/AppUpdates.tsx | 2 +- mobile-app/src/PackageUpdates.tsx | 116 +++++++++++++++--- mobile-app/src/UpdateNotes.tsx | 9 ++ mobile-app/src/VersionUpdates.tsx | 21 ++++ mobile-app/src/core/modules.ts | 9 +- .../src/core/native-package-download.ts | 32 +++++ mobile-app/src/core/network.ts | 17 ++- mobile-app/src/core/package-cache.ts | 40 ++++++ mobile-app/src/core/package-update.ts | 34 +++-- mobile-app/src/core/record-presentation.ts | 42 +++++++ mobile-app/src/core/stock-operations.ts | 2 +- mobile-app/src/core/update-notes.ts | 11 ++ mobile-app/src/core/updates.ts | 13 +- mobile-app/src/core/version-update.ts | 11 ++ mobile-app/src/package-cache.ts | 48 ++++++++ mobile-app/src/screens/Account.tsx | 2 +- mobile-app/src/screens/ArrivalHistory.tsx | 7 +- mobile-app/src/screens/ArrivalListParts.tsx | 31 ++--- mobile-app/src/screens/ArrivalOperation.tsx | 4 +- mobile-app/src/screens/Assistant.tsx | 2 +- mobile-app/src/screens/BatchOperation.tsx | 5 +- mobile-app/src/screens/BusinessList.tsx | 30 ++--- mobile-app/src/screens/ItemIdentity.tsx | 31 +++++ mobile-app/src/screens/RecordCard.tsx | 18 +++ mobile-app/src/screens/Workspace.tsx | 8 +- mobile-app/tests/arrival-list.test.mjs | 11 +- mobile-app/tests/field-operations.test.mjs | 2 + mobile-app/tests/mobile-layout.test.mjs | 2 +- .../tests/native-package-download.test.mjs | 28 +++++ .../tests/native/CmvrPackageTransferTest.java | 68 ++++++++++ mobile-app/tests/operation-guide.test.mjs | 2 +- mobile-app/tests/package-cache.test.mjs | 34 +++++ .../tests/package-update-native-flow.test.mjs | 70 +++++++++++ mobile-app/tests/package-update.test.mjs | 48 ++++++-- mobile-app/tests/publish.test.mjs | 3 +- mobile-app/tests/purchase-only-mine.test.mjs | 5 +- mobile-app/tests/record-presentation.test.mjs | 48 ++++++++ mobile-app/tests/ui-contract.test.mjs | 2 +- mobile-app/tests/update-dialog.test.mjs | 2 +- mobile-app/tests/version-updates.test.mjs | 51 ++++++++ .../project/ProjectLoanController.java | 1 + .../system/MobilePackageController.java | 14 +++ .../system/MobileReleaseController.java | 7 +- .../warehouse/PurchaseRequestController.java | 31 ++++- .../warehouse/SupplierInquiryExport.java | 26 ++-- .../warehouse/SupplierQuoteImport.java | 18 ++- .../assistant/AssistantModelClient.java | 2 +- .../assistant/BusinessActionRegistry.java | 3 + .../service/files/ResumableUploadService.java | 4 +- .../web/service/files/UploadTargets.java | 7 +- .../BusinessControllerContractTest.java | 2 +- .../ruoyi/projectdev/PendingOnlyMineTest.java | 32 +++++ .../projectdev/ProjectLoansDisabledTest.java | 21 ++++ .../projectdev/PurchaseNamedImportTest.java | 2 +- .../com/ruoyi/system/ManagedFileTest.java | 2 +- .../system/MobilePackageManagementTest.java | 47 +++++++ .../ruoyi/system/MobileReleaseRangeTest.java | 31 +++++ .../com/ruoyi/system/MobileReleaseTest.java | 6 +- .../service/impl/PurchaseDocumentsTest.java | 1 + .../PurchaseOnlyMineControllerTest.java | 8 +- .../warehouse/PurchaseQuoteAccessTest.java | 1 + .../SupplierInquiryRoundTripTest.java | 39 +++++- .../AssistantBlackboxRegressionTest.java | 2 +- .../AssistantBusinessContractTest.java | 3 +- .../AssistantPurchaseSheetContractTest.java | 4 +- .../AssistantReadOnlyRegistryTest.java | 18 +-- .../assistant/BusinessActionRegistryTest.java | 2 +- .../ruoyi/common/core/page/TableDataInfo.java | 3 + .../common/storage/BusinessFileStorage.java | 8 ++ .../project/service/ProjectLoanService.java | 9 +- .../service/impl/ManagedFileService.java | 21 ++-- .../service/impl/MobilePackageService.java | 62 ++++++++++ .../service/impl/MobileReleaseService.java | 20 ++- .../service/impl/SysMenuServiceImpl.java | 3 +- .../com/ruoyi/warehouse/domain/InRecord.java | 3 + .../warehouse/mapper/PurchaseBatchMapper.java | 2 + .../service/impl/InRecordServiceImpl.java | 1 + .../service/impl/InitializationService.java | 2 +- .../service/impl/PendingReceiptService.java | 3 + .../impl/PurchaseRequestServiceImpl.java | 2 + .../warehouse/util/PendingReceiptScope.java | 8 ++ .../mapper/warehouse/InRecordMapper.xml | 5 + .../mapper/warehouse/PurchaseBatchMapper.xml | 7 +- .../src/api/system/mobile-release.js | 5 + ruoyi-ui-vue3/src/api/warehouse/purchase.js | 2 + .../src/components/Initialization/index.vue | 4 +- .../src/components/ManagedFiles/Upload.vue | 4 +- .../ProjectLoans/PurchasePurpose.vue | 11 +- .../components/ProjectWorkspace/Budget.vue | 7 +- .../src/components/ProjectWorkspace/Costs.vue | 6 +- .../src/components/ProjectWorkspace/index.vue | 6 +- .../PurchaseSheet/SupplierQuotation.vue | 23 ++-- .../src/components/PurchaseSheet/index.vue | 38 +++++- ruoyi-ui-vue3/src/store/modules/permission.js | 1 + ruoyi-ui-vue3/src/utils/money-display.js | 12 ++ .../src/utils/purchase-history-correction.js | 2 +- ruoyi-ui-vue3/src/utils/supplier-quotation.js | 6 +- .../src/views/businessHome/index.vue | 2 +- .../src/views/production/tasks/index.vue | 1 - .../src/views/project/info/index.vue | 17 +-- ruoyi-ui-vue3/src/views/system/file/index.vue | 12 +- .../PublishDialog.vue} | 9 +- .../src/views/system/mobileRelease/index.vue | 50 ++++++++ ruoyi-ui-vue3/src/views/system/user/index.vue | 10 +- .../views/system/user/profile/resetPwd.vue | 26 ++-- .../src/views/warehouse/inRecord/index.vue | 3 +- .../src/views/warehouse/stock/index.vue | 4 +- .../tests/runtime/managed-files.spec.js | 3 + .../tests/runtime/mobile-release.spec.js | 22 ++++ .../runtime/supplier-inquiry-export.spec.js | 38 ++++++ .../tests/unit/money-display.test.mjs | 23 ++++ .../tests/unit/supplier-quotation.test.mjs | 12 +- .../20261030_mobile_package_management.sql | 17 +++ 124 files changed, 1715 insertions(+), 266 deletions(-) create mode 100644 mobile-app/fingerprint.config.cjs create mode 100644 mobile-app/plugins/native/CmvrPackageTransfer.java create mode 100644 mobile-app/release-notes.json create mode 100644 mobile-app/scripts/test-native-download.cjs create mode 100644 mobile-app/src/UpdateNotes.tsx create mode 100644 mobile-app/src/VersionUpdates.tsx create mode 100644 mobile-app/src/core/native-package-download.ts create mode 100644 mobile-app/src/core/package-cache.ts create mode 100644 mobile-app/src/core/record-presentation.ts create mode 100644 mobile-app/src/core/update-notes.ts create mode 100644 mobile-app/src/core/version-update.ts create mode 100644 mobile-app/src/package-cache.ts create mode 100644 mobile-app/src/screens/ItemIdentity.tsx create mode 100644 mobile-app/src/screens/RecordCard.tsx create mode 100644 mobile-app/tests/native-package-download.test.mjs create mode 100644 mobile-app/tests/native/CmvrPackageTransferTest.java create mode 100644 mobile-app/tests/package-cache.test.mjs create mode 100644 mobile-app/tests/package-update-native-flow.test.mjs create mode 100644 mobile-app/tests/record-presentation.test.mjs create mode 100644 mobile-app/tests/version-updates.test.mjs create mode 100644 ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/MobilePackageController.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/PendingOnlyMineTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/projectdev/ProjectLoansDisabledTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/system/MobilePackageManagementTest.java create mode 100644 ruoyi-admin/src/test/java/com/ruoyi/system/MobileReleaseRangeTest.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/impl/MobilePackageService.java create mode 100644 ruoyi-system/src/main/java/com/ruoyi/warehouse/util/PendingReceiptScope.java create mode 100644 ruoyi-ui-vue3/src/api/system/mobile-release.js create mode 100644 ruoyi-ui-vue3/src/utils/money-display.js rename ruoyi-ui-vue3/src/views/system/{file/AppRelease.vue => mobileRelease/PublishDialog.vue} (67%) create mode 100644 ruoyi-ui-vue3/src/views/system/mobileRelease/index.vue create mode 100644 ruoyi-ui-vue3/tests/runtime/mobile-release.spec.js create mode 100644 ruoyi-ui-vue3/tests/runtime/supplier-inquiry-export.spec.js create mode 100644 ruoyi-ui-vue3/tests/unit/money-display.test.mjs create mode 100644 sql/projectdev/20261030_mobile_package_management.sql diff --git a/mobile-app/app.config.js b/mobile-app/app.config.js index 0dddd13..9e2b40d 100644 --- a/mobile-app/app.config.js +++ b/mobile-app/app.config.js @@ -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 }], diff --git a/mobile-app/fingerprint.config.cjs b/mobile-app/fingerprint.config.cjs new file mode 100644 index 0000000..33353c7 --- /dev/null +++ b/mobile-app/fingerprint.config.cjs @@ -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']}]}; diff --git a/mobile-app/plugins/native/CmvrPackageTransfer.java b/mobile-app/plugins/native/CmvrPackageTransfer.java new file mode 100644 index 0000000..8577877 --- /dev/null +++ b/mobile-app/plugins/native/CmvrPackageTransfer.java @@ -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 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 headers; + private final File target; + private final long size; + private final int requested; + public CmvrPackageTransfer(String address, Map 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 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> tasks=new ArrayList<>(); + long block=(size+workers-1)/workers; + for(int i=0;i{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);} + } + } +} diff --git a/mobile-app/plugins/with-apk-installer.cjs b/mobile-app/plugins/with-apk-installer.cjs index ecbb7d0..525276d 100644 --- a/mobile-app/plugins/with-apk-installer.cjs +++ b/mobile-app/plugins/with-apk-installer.cjs @@ -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 = listOf(CmvrApkVerification(context)) override fun createViewManagers(context: ReactApplicationContext): List> = emptyList() } class CmvrApkVerification(private val context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { + private val downloads = ConcurrentHashMap() 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();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 { val signatures = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures diff --git a/mobile-app/release-notes.json b/mobile-app/release-notes.json new file mode 100644 index 0000000..9858f91 --- /dev/null +++ b/mobile-app/release-notes.json @@ -0,0 +1,7 @@ +[ + "优化库存与采购卡片,重点信息直接展示,规格字号更紧凑。", + "隐藏批次号,保留批次名称和供应商。", + "统一版本更新入口,下载进度展示更简洁。", + "更新说明按条目展示,方便查看本次变化。", + "待入库增加只看我的,可按本人发起的采购和生产来源筛选。" +] diff --git a/mobile-app/scripts/export-update.mjs b/mobile-app/scripts/export-update.mjs index ab3cce4..9301cef 100644 --- a/mobile-app/scripts/export-update.mjs +++ b/mobile-app/scripts/export-update.mjs @@ -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}`); diff --git a/mobile-app/scripts/publish-update.mjs b/mobile-app/scripts/publish-update.mjs index 4c89fca..87c9a56 100644 --- a/mobile-app/scripts/publish-update.mjs +++ b/mobile-app/scripts/publish-update.mjs @@ -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'); diff --git a/mobile-app/scripts/test-native-download.cjs b/mobile-app/scripts/test-native-download.cjs new file mode 100644 index 0000000..8a51fc1 --- /dev/null +++ b/mobile-app/scripts/test-native-download.cjs @@ -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'); diff --git a/mobile-app/scripts/verify-development-ota.mjs b/mobile-app/scripts/verify-development-ota.mjs index fa43332..d1585f9 100644 --- a/mobile-app/scripts/verify-development-ota.mjs +++ b/mobile-app/scripts/verify-development-ota.mjs @@ -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)); diff --git a/mobile-app/src/App.tsx b/mobile-app/src/App.tsx index 922fd0e..8522ba7 100644 --- a/mobile-app/src/App.tsx +++ b/mobile-app/src/App.tsx @@ -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'?:!!selected&&} {(page==='profile'||page==='password')&&setUser(old=>old?{...old,user:{...old.user,...profile}}:null)}/>} {(page==='feedback'||page==='feedback-list')&&} - {(page==='settings'||page==='about')&&} logout={logout} about={page==='about'}/>} + {(page==='settings'||page==='about')&&} logout={logout} about={page==='about'}/>} {!page&&!keyboard&&{tabs.map(([key,label,icon])=>go(key)} style={{flex:1,alignItems:'center',justifyContent:'center',minHeight:50,gap:3}}>{label})}} } - {!packageUpdates.visible&&} + ; } function ProductionConnection({address,onSave}:{address:string;onSave:(value:string)=>Promise}){ diff --git a/mobile-app/src/AppUpdateDialog.tsx b/mobile-app/src/AppUpdateDialog.tsx index e3176dc..246f74a 100644 --- a/mobile-app/src/AppUpdateDialog.tsx +++ b/mobile-app/src/AppUpdateDialog.tsx @@ -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 - - 发现新版本更新已下载完成,重启 App 后即可使用。 - 请先保存正在填写的内容,并等待当前操作完成。重启后,未提交的内容不会保留。 + return + + 发现新版本更新已下载,重启后生效。请先保存当前内容,未提交的内容不会保留。 {!!view.error&&{view.error}}