优化采购实时编辑与权限,支持先到货后补报价、按批次补录照片和批量附件上传。更新验收报告模板及明细选择,增加验收发票独立管理和付款前置校验。完善 BOM 数据权限及 App 更新兼容性。
121 lines
12 KiB
TypeScript
121 lines
12 KiB
TypeScript
import React,{useCallback,useEffect,useRef,useState} from 'react';
|
||
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,createPackageDownloadProcessor,verifyInstalledPackage,packageInstallError,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'|'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):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;
|
||
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(error){if(valid()&&!abort.signal.aborted)setError(packageInstallError(error));}
|
||
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>;
|
||
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>;
|
||
}
|