feat(warehouse): 优化采购报价权限控制和文件管理功能

- 实现基于角色的采购报价权限检查,仅超级管理员和采购经理角色可查看报价
- 替换原有的仓库采购管理权限检查为新的报价权限函数
- 在采购单据组件中更新报价字段显示权限逻辑
- 集成文件管理功能,支持文档附件上传下载
- 添加移动端应用更新提示和发布功能
- 增强采购历史更正服务的安全访问控制
- 重构报价访问工具类以支持细粒度字段过滤
- 添加单元测试验证新的权限控制逻辑
This commit is contained in:
lixiaolong 2026-10-29 09:58:51 +08:00
parent d37b4ff379
commit 89c962223a
90 changed files with 2000 additions and 29 deletions

View File

@ -3,7 +3,7 @@ module.exports = () => {
const env = environment();
const cleartextHosts = [...new Set([env.apiUrl, env.updateOrigin].filter(url => url.startsWith('http:')).map(url => new URL(url).hostname))];
return {
name: env.variant === 'prod' ? '车研物资' : '车研物资·开发',
name: env.variant === 'prod' ? '设备科综合管理系统' : '设备科综合管理系统·开发',
icon: `./assets/brand/app-icon-blue-${env.variant}.png`,
slug: 'cmvr-wms', version: '1.0.0', orientation: 'portrait', userInterfaceStyle: 'automatic',
platforms: ['android', 'web'],

View File

@ -0,0 +1,31 @@
# 素材与生成提示词
使用内置 imagegen 生成原创素材。安装包图标的安全区域适配是对生成结果的尺寸和透明通道处理;未使用或伪造官方商标。
## 正式版图标
Use case: logo-brand. Asset type: production Android application launcher icon, single square image, 1024x1024, full bleed opaque background without rounded outside corners. Create a premium original app emblem for 招商车研 (automotive testing research), 研发中心, 设备仪器科, an internal equipment/materials management app. A bold simple geometric monogram-like emblem combining a precision measurement frame / caliper with the silhouette of an automotive test-track curve and a subtle central data pulse. One coherent strong symbol, not a collage of small objects. Deep midnight navy background, rich cobalt blue and emerald-teal luminous metallic linework, exceptionally restrained highlights, precise symmetry and excellent readability at 48 pixels. Center the entire emblem inside the central 58% square safe zone so Android adaptive masks do not crop it; outside is generous clean dark blue background. Modern Chinese state-owned research institute visual identity, trustworthy engineering, minimal premium three-dimensional finish, crisp edges. Do not copy or invent the official China Merchants logo; this is an original departmental application mark. No Chinese or English text, no letters, no labels, no watermark, no photo, no phone mockup, no border.
## 开发版图标
Use case: logo-brand. Asset type: fixed DEVELOPMENT Android launcher icon, square 1024x1024 full bleed opaque. EDIT the supplied production icon as the reference and edit target. Preserve exactly the recognizable geometric precision instrument frame, central measurement probe, data pulse and curving automotive test-track emblem and the premium engineering style. Change palette to strong amber-orange and warm pale gold on a deep ink-blue background so development is instantly distinguishable from blue/teal production. Simplify excessive tiny shine, retain clean edges. Add one small but highly legible rectangular badge integrated in the LOWER RIGHT OF THE CENTRAL SAFE ZONE bearing exact uppercase text "DEV", dark navy lettering on amber-gold. Keep whole emblem and DEV badge within center 60% of canvas with generous plain dark margins, so round/squircle Android masks cannot crop it. No extra text, no Chinese characters, no official company logo, no watermark or phone mockup. This is an original internal departmental app icon for 招商车研 研发中心 设备仪器科.
## 登录背景
Use case: stylized-concept. Asset type: portrait mobile app login background 1024x1536. EDIT the reference automotive test laboratory image to reflect the full business of 招商车研 研发中心 设备仪器科, while preserving its refined photoreal cinematic industrial style, midnight navy/cobalt/teal palette, and clean empty lower portion. Replace the car-only scene with ONE coherent advanced multi-disciplinary testing research laboratory in the UPPER 38%: a clearly recognizable elegant full-body humanoid research robot at center-left, a compact mobile manipulation robot with wheeled AGV base and a single industrial arm in foreground left, an intelligent vehicle cockpit testing rig on right with steering wheel and wide dashboard display, and a restrained automotive durability / dynamometer test vehicle further back at far right. Precision measurement instruments and subtle thin sensor/data trajectories connect these research areas. Physically plausible equipment, no humanoid faces like humans, no weapons, no people. Premium trustworthy corporate research atmosphere; NOT a collage, no separate panels, no poster, no text, logos or watermarks. Keep bottom 62% mostly smooth midnight navy negative space for a login form. Reduce visual clutter and loud neon. A refined cinematic photo/3D blend, sharp engineering details, upper scene with enough breathing room for a company masthead overlaid at very top. No UI controls drawn.
项目使用文件:app-icon-prod.png、app-icon-dev.png、app-icon-prod-adaptive.png、app-icon-dev-adaptive.png、login-tech-background.jpg。
## 蓝色复用版(当前使用)
使用内置 imagegen,以用户提供的图片为参考进行重新绘制。正式版提示词:保持原图几何形状和比例,将金色改为统一蓝色 #176AB2、白色背景,不添加其他文字或装饰;图形置于 Android 图标安全区域。
开发版提示词:保持同一蓝色图形,在图案正下方居中添加蓝色大写 DEV,不增加徽章或其他装饰;保留足够白边以适配圆形桌面图标。
当前文件:app-icon-blue-prod.png、app-icon-blue-dev.png 及对应的 -adaptive.png。原图像为低分辨率截图,蓝色图案由图像工具重绘,并非逐像素的颜色替换。
### 本次使用的原始提示词
正式版:Edit the attached icon, using it as the exact design reference. Preserve the SAME geometry, positions, proportions, circular gap, angles and shape of the interior angular emblem. It must be directly recognizable as the supplied original, not a redesign. Change all gold/beige strokes to a single flat medium blue (#176AB2), preserve the white background, crisp clean vector-like edges. Upscale/re-render accurately in a high-resolution square suitable for an Android launcher icon, center original mark within central 58% of canvas with white space around it so Android adaptive icons don't clip it. No extra decoration, no gradients, shadows, gloss, 3D, words or typography. Preserve original visual geometry.
开发版:Edit the attached icon as an exact visual reference. Preserve the SAME geometry, positions, proportions, circular gap, angles, and interior angular emblem; do not redesign the mark. Recolor gold/beige strokes to a single flat medium blue (#176AB2) on pure white. Directly below the circular emblem, centered, add a small clean, readable blue uppercase label "DEV" in bold sans-serif. No badge box, no other text. Original symbol plus DEV label fully contained in the central 58% square safe area of the overall white square, ample white margin for Android adaptive masking. Crisp vector-like, no decoration, no gradients, shadows, gloss or 3D.

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 510 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 298 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 994 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 326 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

View File

@ -0,0 +1,62 @@
const {withAndroidManifest,withMainApplication,withDangerousMod}=require('expo/config-plugins');
const fs=require('node:fs/promises'),path=require('node:path');
module.exports=config=>{
const pkg=config.android?.package;if(!/^cn\.cmvr\.wms(\.dev)?$/.test(pkg||''))throw Error('Unexpected application package');
config=withAndroidManifest(config,cfg=>{
const m=cfg.modResults.manifest;m.queries=m.queries||[{}];const query=m.queries[0];query.intent=query.intent||[];
if(!query.intent.some(i=>i.data?.some(d=>d.$?.['android:mimeType']==='application/vnd.android.package-archive')))query.intent.push({action:[{$:{'android:name':'android.intent.action.VIEW'}}],data:[{$:{'android:mimeType':'application/vnd.android.package-archive'}}]});
return cfg;
});
config=withMainApplication(config,cfg=>{
const marker='add(CmvrApkVerificationPackage())',source=cfg.modResults.contents;
if(!source.includes(marker)){const needle='PackageList(this).packages.apply {';if(!source.includes(needle))throw Error('Unexpected MainApplication template');cfg.modResults.contents=source.replace(needle,needle+'\n '+marker);}
return cfg;
});
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});
await fs.writeFile(path.join(dir,'CmvrApkVerificationPackage.kt'),`package ${pkg}
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.*
import com.facebook.react.uimanager.ViewManager
import java.io.File
import java.security.MessageDigest
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) {
override fun getName() = "CmvrApkVerification"
@Suppress("DEPRECATION")
private fun signatures(info: PackageInfo): Set<String> {
val signatures = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures
return signatures?.map { signature -> MessageDigest.getInstance("SHA-256").digest(signature.toByteArray()).joinToString("") { "%02x".format(it) } }?.toSet() ?: emptySet()
}
@Suppress("DEPRECATION")
@ReactMethod fun verify(uri: String, expectedVersion: Double, promise: Promise) {
try {
val parsed = Uri.parse(uri)
require(parsed.scheme == "file")
val file = File(requireNotNull(parsed.path)).canonicalFile
val base = File(context.cacheDir, "app-updates").canonicalFile
require(file.parentFile == base && file.isFile && expectedVersion >= 1 && expectedVersion <= Int.MAX_VALUE && expectedVersion % 1.0 == 0.0)
val flags = if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES
val manager = context.packageManager
val archive = requireNotNull(manager.getPackageArchiveInfo(file.path, flags))
val current = manager.getPackageInfo(context.packageName, flags)
val version = if (Build.VERSION.SDK_INT >= 28) archive.longVersionCode else archive.versionCode.toLong()
val archiveSignatures = signatures(archive)
val installedSignatures = signatures(current)
require(archive.packageName == context.packageName && version == expectedVersion.toLong() && archiveSignatures.isNotEmpty() && archiveSignatures == installedSignatures)
promise.resolve(true)
} catch (error: Exception) { promise.reject("INVALID_APK", "安装包与当前应用的包名、签名或版本不一致,请联系管理员。") }
}
}
`);
return cfg;
}]);
};

View File

@ -1,3 +1,4 @@
import {canViewPurchaseQuotes} from './core/purchase-quote-permission';
import {Text,ReadingContext,type ReadingSize} from './typography';
import {usePackageUpdates,PackageUpdateDialog,PackageUpdateStatus} from './PackageUpdates';
import {LoginView} from './screens/LoginView';
@ -34,7 +35,7 @@ const config=Constants.expoConfig?.extra || {};
const variant=String(config.environment || 'dev');
const nativeBase=internalUrl(String(config.apiUrl || 'http://127.0.0.1:8080'),variant==='dev');
const base=Platform.OS==='web'?`${globalThis.location.origin}/native-api`:nativeBase;
type User={user:Row; permissions:string[]; pages?:string[];pwdChrtype?:string};
type User={user:Row; roles?:string[]; permissions:string[]; pages?:string[];pwdChrtype?:string};
const preferences={get:async(key:string)=>Platform.OS==='web'?localStorage.getItem(key):SecureStore.getItemAsync(key),
put:async(key:string,value:string)=>{if(Platform.OS==='web')localStorage.setItem(key,value);else await SecureStore.setItemAsync(key,value);}};
export default function App(){
@ -113,7 +114,7 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
{!page&&tab==='me'&&<Me api={api} user={user.user} open={open}/>}
{page==='messages'&&<MessageCenter api={api} onRead={refreshMessages}/>}
{aiVisited&&ai&&<View style={[s.fill,{display:!page&&tab==='assistant'?'flex':'none'}]}><Assistant api={api}/></View>}
{selected?.key==='files'?<FileLibrary api={api} scope={scope} permissions={user.permissions}/>:!!selected&&<BusinessList key={page} api={api} scope={scope} module={selected} permissions={user.permissions} initialQuery={entry?.query} onNavigate={open}/>}
{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'}/>}

View File

@ -0,0 +1,17 @@
import {Text} from './typography';
import React from 'react';
import {Modal,ScrollView,View} from 'react-native';
import {Button,Icon,Note,useTheme} from './ui';
import type {UpdateView} from './core/updates';
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>
{!!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>
</View></View></Modal>;
}

View File

@ -0,0 +1,21 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {AppState,Platform} from 'react-native';
import * as Updates from 'expo-updates';
import {createUpdateController,updateMessages,type UpdateView} from './core/updates';
export {AppUpdateDialog} from './AppUpdateDialog';
export function useAppUpdates(){
const [view,setView]=useState<UpdateView>({state:'disabled',visible:false,restarting:false,error:''});
const controller=useRef<ReturnType<typeof createUpdateController>|null>(null);
const enabled=Platform.OS==='android'&&!__DEV__&&Updates.isEnabled;
useEffect(()=>{
const current=createUpdateController({...Updates,isEnabled:enabled},setView,{active:AppState.currentState==='active'});controller.current=current;
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 later=useCallback(()=>controller.current?.later(),[]);
const restart=useCallback(()=>{void controller.current?.restart();},[]);
return {view,text:updateMessages[view.state],enabled,check,later,restart};
}
export type AppUpdateControls=ReturnType<typeof useAppUpdates>;

View File

@ -0,0 +1,32 @@
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {AppState,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,verifyInstalledPackage,type PackageRelease} from './core/package-update';
import {Button,Card,Heading,Icon,Note,s,useTheme} from './ui';
import {Text} from './typography';
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'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState('');
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)&&current>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);
try{await api.download(release.downloadPath,async bytes=>{verify.write(bytes);handle.writeBytes(bytes);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch,onProgress:n=>{if(valid())setProgress(Math.min(99,Math.round(n/release.size*100)));}});verify.finish();}finally{handle.close();}
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;try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;}}
function later(){if(phase==='downloading')ctl.current?.abort();setVisible(false);}
return {release,visible,phase,progress,error,available,check:()=>void check(true),download:()=>void download(),install:()=>void install(),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={c.phase==='downloading'} 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}%</Note></>}{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}</ScrollView><Button title={c.phase==='ready'?'安装新版':c.phase==='downloading'?'正在下载…':'下载新版'} disabled={c.phase==='downloading'} onPress={c.phase==='ready'?c.install:c.download}/><Button title={c.phase==='downloading'?'取消下载':'稍后再说'} secondary onPress={c.later}/></View></View></Modal>;}

View File

@ -0,0 +1,34 @@
import React,{useMemo,useState} from 'react';
import {FlatList,KeyboardAvoidingView,Modal,Platform,Pressable,View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {Icon,useTheme} from '../ui';
import {Text,TextInput} from '../typography';
type Item=Record<string,any>;
const recent=new Map<string,string[]>();
const identity=(item:Item)=>String(item.id??item.userId??item.value??item.areaCode??'');
export function Choice({label,items,value,onChange,nameKey,disabled=false}:{label:string;items:Item[];value:Item|null;onChange:(item:Item)=>void;nameKey:string;disabled?:boolean}){
const t=useTheme(),[query,setQuery]=useState(''),[open,setOpen]=useState(false);
const matches=useMemo(()=>{
const words=query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean),seen=new Set<string>();
const filtered=items.filter(item=>{const id=identity(item);if(!id||seen.has(id))return false;seen.add(id);return words.every(word=>[item[nameKey],item.areaCode,item.userName,item.nickName,item.projectName].filter(Boolean).join(' ').toLocaleLowerCase().includes(word));});
if(query.trim())return filtered;
const selected=identity(value||{}),previous=recent.get(label)||[];
return filtered.map((item,index)=>({item,index,rank:identity(item)===selected?-2:previous.includes(identity(item))?previous.indexOf(identity(item)):100})).sort((a,b)=>a.rank-b.rank||a.index-b.index).map(v=>v.item);
},[items,value,query,label,nameKey]);
function choose(item:Item){recent.set(label,[identity(item),...(recent.get(label)||[]).filter(id=>id!==identity(item))].slice(0,5));onChange(item);setOpen(false);setQuery('');}
const close=()=>{setOpen(false);setQuery('');};
return <View style={{gap:6}}><Text style={{color:t.text,fontSize:13,lineHeight:19}}>{label}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={`选择${label}`} accessibilityState={{expanded:open,disabled}} disabled={disabled} onPress={()=>setOpen(true)} style={{minHeight:44,paddingHorizontal:12,paddingVertical:10,borderWidth:1,borderColor:t.line,borderRadius:9,backgroundColor:t.card,flexDirection:'row',alignItems:'center',gap:8,opacity:disabled?.55:1}}>
<Text style={{flex:1,color:value?t.text:t.muted,fontSize:14,lineHeight:20}}>{value?.[nameKey]||value?.areaCode||`请选择${label}`}</Text><Icon name="chevron-down" size={16} color={t.muted}/>
</Pressable>
{open&&<Modal visible transparent animationType="slide" onRequestClose={close}><KeyboardAvoidingView style={{flex:1}} behavior={Platform.OS==='ios'?'padding':undefined}><View style={{flex:1,backgroundColor:'rgba(10,20,35,.42)',justifyContent:'flex-end'}}>
<Pressable accessibilityRole="button" accessibilityLabel="关闭选择" onPress={close} style={{flex:1}}/>
<SafeAreaView edges={['bottom']} style={{backgroundColor:t.card,borderTopLeftRadius:18,borderTopRightRadius:18,maxHeight:'82%',minHeight:320,width:'100%',maxWidth:600,alignSelf:'center'}}>
<View style={{paddingHorizontal:16,paddingTop:8,flexDirection:'row',alignItems:'center'}}><Text style={{flex:1,fontSize:16,fontWeight:'600',color:t.text}}>选择{label}</Text><Pressable accessibilityRole="button" accessibilityLabel="关闭选择" onPress={close} style={{minHeight:44,minWidth:44,alignItems:'center',justifyContent:'center'}}><Icon name="close" size={20} color={t.muted}/></Pressable></View>
<View style={{marginHorizontal:16,marginBottom:8,borderWidth:1,borderColor:t.line,borderRadius:9,paddingHorizontal:10,flexDirection:'row',alignItems:'center'}}><Icon name="search-outline" size={17} color={t.muted}/><TextInput accessibilityLabel={`搜索${label}`} placeholder={`搜索${label}`} placeholderTextColor={t.muted} value={query} onChangeText={setQuery} autoCorrect={false} style={{flex:1,minHeight:44,paddingHorizontal:8,fontSize:14,color:t.text}}/>{!!query&&<Pressable accessibilityRole="button" accessibilityLabel="清除搜索" onPress={()=>setQuery('')} style={{padding:10}}><Icon name="close-circle" size={17} color={t.muted}/></Pressable>}</View>
<Text style={{paddingHorizontal:16,paddingBottom:6,color:t.muted,fontSize:12,lineHeight:18}}>{matches.length} 项{!query.trim()?' · 当前选择和最近使用优先':''}</Text>
<FlatList keyboardShouldPersistTaps="handled" data={matches} keyExtractor={identity} initialNumToRender={15} contentContainerStyle={{paddingHorizontal:16,paddingBottom:12}} ListEmptyComponent={<Text style={{padding:24,textAlign:'center',color:t.muted}}>没有匹配项,试试其他名称</Text>} renderItem={({item})=>{const selected=identity(item)===identity(value||{});return <Pressable accessibilityRole="button" accessibilityLabel={String(item[nameKey]||item.areaCode)} accessibilityState={{selected}} onPress={()=>choose(item)} style={{minHeight:48,paddingVertical:12,borderBottomWidth:1,borderColor:t.line,flexDirection:'row',alignItems:'center',gap:10}}><Text style={{flex:1,color:selected?t.accent:t.text,fontSize:14,lineHeight:21}}>{item[nameKey]||item.areaCode}</Text>{selected&&<Icon name="checkmark" size={18}/>}</Pressable>;}}/>
</SafeAreaView>
</View></KeyboardAvoidingView></Modal>}
</View>;
}

View File

@ -0,0 +1,21 @@
import React,{useState} from 'react';
import {Modal,Pressable,ScrollView,View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {Icon,useTheme} from '../ui';
import {Text} from '../typography';
import {calendarDate,calendarDays,dateParts} from '../core/calendar';
type Panel='days'|'months'|'years';
export function DateField({label,value,onChange,disabled=false}:{label:string;value:string;onChange:(value:string)=>void;disabled?:boolean}){
const t=useTheme(),[open,setOpen]=useState(false),[year,setYear]=useState(new Date().getFullYear()),[month,setMonth]=useState(new Date().getMonth()),[panel,setPanel]=useState<Panel>('days'),[yearPage,setYearPage]=useState(2020);
function show(){const selected=dateParts(value),now=new Date(),y=selected?.year??now.getFullYear();setYear(y);setYearPage(Math.floor(y/12)*12);setMonth(selected?.month??now.getMonth());setPanel('days');setOpen(true);}
function move(direction:number){if(panel==='years'){setYearPage(v=>Math.max(1900,Math.min(2188,v+direction*12)));return;}const date=new Date(year,month+direction,1);if(date.getFullYear()>=1900&&date.getFullYear()<=2199){setYear(date.getFullYear());setMonth(date.getMonth());}}
function choose(date:string){onChange(date);setOpen(false);}
return <View style={{gap:6}}><Text style={{fontSize:13,lineHeight:19,color:t.text}}>{label}</Text><Pressable accessibilityRole="button" accessibilityLabel={`选择${label}`} accessibilityState={{disabled,expanded:open}} disabled={disabled} onPress={show} style={{minHeight:44,padding:11,borderWidth:1,borderColor:t.line,borderRadius:9,backgroundColor:t.card,flexDirection:'row',alignItems:'center',gap:8,opacity:disabled?.55:1}}><Icon name="calendar-outline" size={18} color={t.muted}/><Text style={{color:value?t.text:t.muted,fontSize:14,lineHeight:20,flex:1}}>{value||'请选择日期'}</Text><Icon name="chevron-down" size={15} color={t.muted}/></Pressable>
{open&&<Modal transparent visible animationType="slide" onRequestClose={()=>setOpen(false)}><View style={{flex:1,backgroundColor:'rgba(10,20,35,.42)',justifyContent:'flex-end'}}><Pressable accessibilityRole="button" accessibilityLabel="关闭日期选择" onPress={()=>setOpen(false)} style={{flex:1}}/><SafeAreaView edges={['bottom']} style={{width:'100%',maxWidth:540,alignSelf:'center',backgroundColor:t.card,borderTopLeftRadius:18,borderTopRightRadius:18,padding:12,maxHeight:'92%'}}>
<View style={{flexDirection:'row',alignItems:'center',paddingHorizontal:4}}><Text style={{flex:1,color:t.text,fontSize:16,fontWeight:'600'}}>{label}</Text><Pressable accessibilityRole="button" accessibilityLabel="关闭日期选择" onPress={()=>setOpen(false)} style={{padding:12}}><Icon name="close" size={20} color={t.muted}/></Pressable></View>
<View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}><Pressable accessibilityRole="button" accessibilityLabel={panel==='years'?'前十二年':'上个月'} onPress={()=>move(-1)} style={{padding:12}}><Icon name="chevron-back" size={20}/></Pressable><View style={{flexDirection:'row'}}><Pressable accessibilityRole="button" accessibilityLabel="选择年份" onPress={()=>{setYearPage(Math.floor(year/12)*12);setPanel(panel==='years'?'days':'years');}} style={{padding:12}}><Text style={{color:t.text,fontWeight:'600'}}>{panel==='years'?`${yearPage}—${yearPage+11}`:`${year} 年`}</Text></Pressable>{panel!=='years'&&<Pressable accessibilityRole="button" accessibilityLabel="选择月份" onPress={()=>setPanel(panel==='months'?'days':'months')} style={{padding:12}}><Text style={{color:t.text,fontWeight:'600'}}>{month+1} 月</Text></Pressable>}</View><Pressable accessibilityRole="button" accessibilityLabel={panel==='years'?'后十二年':'下个月'} onPress={()=>move(1)} style={{padding:12}}><Icon name="chevron-forward" size={20}/></Pressable></View>
<ScrollView style={{flexShrink:1}}>{panel==='days'?<><View style={{flexDirection:'row'}}>{['一','二','三','四','五','六','日'].map(day=><Text key={day} style={{width:'14.2857%',textAlign:'center',paddingVertical:6,color:t.muted,fontSize:12}}>{day}</Text>)}</View><View style={{flexDirection:'row',flexWrap:'wrap'}}>{calendarDays(year,month).map((date,index)=><View key={index} style={{width:'14.2857%',padding:2}}>{date?<Pressable accessibilityRole="button" accessibilityLabel={date} accessibilityState={{selected:date===value}} onPress={()=>choose(date)} style={{minHeight:42,alignItems:'center',justifyContent:'center',borderRadius:9,backgroundColor:date===value?t.accent:t.card}}><Text style={{color:date===value?t.onAccent:t.text,fontSize:14}}>{Number(date.slice(-2))}</Text></Pressable>:<View style={{minHeight:42}}/>}</View>)}</View></>:<View style={{flexDirection:'row',flexWrap:'wrap'}}>{Array.from({length:12},(_,index)=>panel==='years'?yearPage+index:index).map(number=><Pressable key={number} accessibilityRole="button" accessibilityLabel={panel==='years'?`${number}年`:`${number+1}月`} disabled={panel==='years'&&(number<1900||number>2199)} onPress={()=>{if(panel==='years'){setYear(number);setPanel('months');}else{setMonth(number);setPanel('days');}}} style={{width:'33.3333%',minHeight:48,alignItems:'center',justifyContent:'center'}}><Text style={{color:t.text,fontSize:14}}>{panel==='years'?`${number} 年`:`${number+1} 月`}</Text></Pressable>)}</View>}</ScrollView>
<Pressable accessibilityRole="button" accessibilityLabel="选择今天" onPress={()=>{const now=new Date();choose(calendarDate(now.getFullYear(),now.getMonth(),now.getDate()));}} style={{minHeight:44,marginTop:8,backgroundColor:t.soft,borderRadius:9,alignItems:'center',justifyContent:'center'}}><Text style={{color:t.accent,fontWeight:'600'}}>今天</Text></Pressable>
</SafeAreaView></View></Modal>}
</View>;
}

View File

@ -0,0 +1,6 @@
export function calendarDate(year:number,month:number,day:number){return `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}`;}
export function calendarDays(year:number,month:number):(string|null)[]{
const start=new Date(year,month,1),length=new Date(year,month+1,0).getDate(),offset=(start.getDay()+6)%7;
return Array.from({length:Math.ceil((offset+length)/7)*7},(_,index)=>index<offset||index>=offset+length?null:calendarDate(year,month,index-offset+1));
}
export function dateParts(value:string){const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(value);if(!match)return null;const year=Number(match[1]),month=Number(match[2])-1,day=Number(match[3]),date=new Date(year,month,day);return year>=1900&&year<=2199&&date.getFullYear()===year&&date.getMonth()===month&&date.getDate()===day?{year,month,day}:null;}

View File

@ -0,0 +1,15 @@
import type {Row} from './modules.ts';
export type ReviewEntry={kind:'row'|'quote'|'reference'|'recipient'|'history';row:Row;value:Row;index:number};
export function draftReviewEntries(draft:Row):ReviewEntry[]{
return (draft.rows||[]).flatMap((row:Row,index:number)=>[
{kind:'row',row,value:row,index},
...(row._quotePreview||[]).map((value:Row)=>({kind:'quote',row,value,index})),
...(row._referencePricePreview||[]).map((value:Row)=>({kind:'reference',row,value,index})),
...(row._notificationPreview?.recipients||[]).map((value:Row)=>({kind:'recipient',row,value,index})),
...(row._historyPreview?[{kind:'history',row,value:row._historyPreview,index}]:[])
]);
}
export function incompleteRecipientReview(draft:Row){
return draft.action==='notification.send'&&(draft.rows||[]).some((row:Row)=>Number(row._notificationPreview?.recipientCount||0)>(row._notificationPreview?.recipients||[]).length);
}
export function reviewComplete(pages:number,checked:number[]){return pages>0&&Array.from({length:pages},(_,i)=>i).every(i=>checked.includes(i));}

View File

@ -0,0 +1,39 @@
export type DraftStorage={get:(key:string)=>Promise<string|null>;set:(key:string,value:string)=>Promise<void>;remove:(key:string)=>Promise<void>};
export type SavedDraft<T>={version:1;scope:string;kind:string;id:string;updatedAt:number;value:T};
const queues=new Map<string,Promise<unknown>>();
const MAX_CHARS=262144,CHUNK=320;
// A reversible key avoids hash collisions between accounts or environments.
export function draftKey(scope:string,kind:string,id:string|number){
if(!scope||!kind||String(id)==='')throw new Error('缺少草稿所属账号或业务标识');
return 'cmvr.draft.'+Array.from(JSON.stringify([scope,kind,String(id)])).map(c=>c.codePointAt(0)!.toString(16)).join('-');
}
function serial<T>(key:string,work:()=>Promise<T>):Promise<T>{
const next=(queues.get(key)||Promise.resolve()).catch(()=>{}).then(work);queues.set(key,next);
void next.finally(()=>{if(queues.get(key)===next)queues.delete(key);}).catch(()=>{});return next;
}
type Manifest={revision:string;count:number};
function manifest(raw:string|null):Manifest|null{if(!raw)return null;try{const m=JSON.parse(raw);return /^[a-z0-9]+$/.test(m.revision)&&Number.isInteger(m.count)&&m.count>0&&m.count<=Math.ceil(MAX_CHARS/CHUNK)?m:null;}catch{return null;}}
let revisionCounter=0;
export function createDraftStore(storage:DraftStorage){
async function removeChunks(key:string,m:Manifest|null){if(m)for(let i=0;i<m.count;i++)await storage.remove(`${key}.${m.revision}.${i}`);}
return {
load<T>(scope:string,kind:string,id:string|number):Promise<SavedDraft<T>|null>{const key=draftKey(scope,kind,id);return serial(key,async()=>{
const raw=await storage.get(key),m=manifest(raw);if(!raw)return null;if(!m)throw new Error('本地草稿索引异常,请先核对业务记录,勿重复提交');
const chunks=[];for(let i=0;i<m.count;i++){const chunk=await storage.get(`${key}.${m.revision}.${i}`);if(chunk===null)throw new Error('草稿读取不完整,请先核对业务记录');chunks.push(chunk);}
const data=JSON.parse(chunks.join('')) as SavedDraft<T>;
if(data.version!==1||data.scope!==scope||data.kind!==kind||data.id!==String(id))throw new Error('草稿不属于当前账号或业务');return data;
});},
save<T>(scope:string,kind:string,id:string|number,value:T):Promise<void>{const key=draftKey(scope,kind,id);return serial(key,async()=>{
const data:SavedDraft<T>={version:1,scope,kind,id:String(id),updatedAt:Date.now(),value};
const content=JSON.stringify(data,(name,v)=>{if(/^(password|token|authorization|secret)$/i.test(name))throw new Error('草稿不能保存登录凭据');return v;});
if(content.length>MAX_CHARS)throw new Error('草稿内容过多,请分批填写');
const characters=Array.from(content),previous=manifest(await storage.get(key)),revision=Date.now().toString(36)+(++revisionCounter).toString(36),count=Math.ceil(characters.length/CHUNK);let written=0;
try{for(let i=0;i<count;i++){await storage.set(`${key}.${revision}.${i}`,characters.slice(i*CHUNK,(i+1)*CHUNK).join(''));written++;}await storage.set(key,JSON.stringify({revision,count}));}
catch(error){await removeChunks(key,{revision,count:written}).catch(()=>{});throw error;}
// Commit the new index before removing the old version. A failed write keeps
// the previous idempotency key and submitted payload recoverable.
await removeChunks(key,previous).catch(()=>{});
});},
clear(scope:string,kind:string,id:string|number):Promise<void>{const key=draftKey(scope,kind,id);return serial(key,async()=>{const m=manifest(await storage.get(key));await storage.remove(key);await removeChunks(key,m).catch(()=>{});});}
};
}

View File

@ -0,0 +1,17 @@
import {sha256} from '@noble/hashes/sha2.js';
import {bytesToHex} from '@noble/hashes/utils.js';
import type {ApiClient} from './network';
export type UploadSource={name:string;size:number;read:(start:number,length:number)=>Promise<Uint8Array>;close:()=>void;part?:(bytes:Uint8Array)=>Promise<Blob|{uri:string;name:string;type:string}>;};
export type TransferProgress={phase:'hashing'|'uploading'|'saving'|'done';percent:number;sessionId?:string};
export function fileSize(value:unknown){const n=Number(value);return !Number.isFinite(n)||n<0?'—':n>=1024**3?(n/1024**3).toFixed(2)+' GB':n>=1024**2?(n/1024**2).toFixed(1)+' MB':n>=1024?(n/1024).toFixed(1)+' KB':n+' B';}
export async function uploadManagedFile(api:Pick<ApiClient,'request'|'captureSession'|'isSessionCurrent'>,file:UploadSource,signal:AbortSignal,progress:(value:TransferProgress)=>void){
const owner=api.captureSession(),check=()=>{if(signal.aborted)throw new Error('上传已暂停,重新选择同一文件可继续');if(!api.isSessionCurrent(owner))throw new Error('账号已切换,上传取消');};
try{if(!Number.isInteger(file.size)||file.size<=0||file.size>1024**3)throw new Error('请选择非空文件,单个最多1GB');
const hash=sha256.create();for(let start=0;start<file.size;start+=1024**2){check();const chunk=await file.read(start,Math.min(1024**2,file.size-start));if(chunk.length!==Math.min(1024**2,file.size-start))throw new Error('文件读取不完整,请重新选择');hash.update(chunk);progress({phase:'hashing',percent:Math.round((start+chunk.length)/file.size*10)});await new Promise(r=>setTimeout(r,0));}
check();let state=(await api.request<any>('/common/file-transfers',{method:'POST',body:{target:{purpose:'fileLibrary'},name:file.name,size:file.size,sha256:bytesToHex(hash.digest())},signal,timeout:180000})).data;
const id=state?.id;if(!/^[\da-f-]{36}$/i.test(id)||state.size!==file.size||!Number.isInteger(state.chunkSize)||state.chunkSize<1||state.chunkSize>1024**2||state.totalChunks!==Math.ceil(file.size/state.chunkSize))throw new Error('上传状态无效,请重新选择文件');
const uploaded=new Set<number>((state.uploaded||[]).filter((v:unknown)=>Number.isInteger(v)&&Number(v)>=0&&Number(v)<state.totalChunks));
if(!state.complete)for(let index=0;index<state.totalChunks;index++){check();if(!uploaded.has(index)){const chunk=await file.read(index*state.chunkSize,Math.min(state.chunkSize,file.size-index*state.chunkSize));if(chunk.length!==Math.min(state.chunkSize,file.size-index*state.chunkSize))throw new Error('文件读取不完整');const data=new FormData();const part=file.part?await file.part(chunk):new Blob([Uint8Array.from(chunk).buffer]);if(part instanceof Blob)data.append('file',part,'chunk.bin');else data.append('file',part as unknown as Blob);data.append('sha256',bytesToHex(sha256(chunk)));await api.request(`/common/file-transfers/${id}/chunks/${index}`,{method:'PUT',body:data,signal,timeout:180000});}progress({phase:'uploading',percent:10+Math.round((index+1)/state.totalChunks*85),sessionId:id});}
check();progress({phase:'saving',percent:98,sessionId:id});state=(await api.request<any>(`/common/file-transfers/${id}/complete`,{method:'POST',body:{},signal,timeout:180000})).data;check();if(!state?.complete||!state.result)throw new Error('上传结果待核对,请重新选择同一文件继续');progress({phase:'done',percent:100,sessionId:id});return state.result;
}finally{file.close();}
}

View File

@ -0,0 +1,30 @@
import {parseDocument} from 'htmlparser2';
import type {AnyNode,Element} from 'domhandler';
export type NoticePart={text:string;bold?:boolean;italic?:boolean;underline?:boolean;color?:string;href?:string};
export type NoticeBlock={kind:'text'|'image';parts:NoticePart[];src?:string;prefix?:string;indent:number;align?:'left'|'center'|'right';heading?:boolean};
const blocked=new Set(['script','style','iframe','object','embed','form','input','button','textarea','svg','math','video']);
export function safeNoticeUrl(raw:unknown,base:string){
try{const value=String(raw||'').trim();if(!value||/[\u0000-\u0020]/.test(value))return null;const url=new URL(value,base+'/');if(!['http:','https:'].includes(url.protocol)||url.username||url.password)return null;return url.href;}catch{return null;}
}
/** Parse to a small native view model. No HTML, CSS, or event handlers are executed. */
export function noticeBlocks(html:unknown):NoticeBlock[]{
const blocks:NoticeBlock[]=[],root=parseDocument(String(html||'').slice(0,500000),{decodeEntities:true});
let current:NoticeBlock|undefined;const lists:{ordered:boolean;next:number}[]=[],quillCounts=new Map<number,number>();
const flush=()=>{if(current?.parts.some(p=>p.text.trim()))blocks.push(current);current=undefined;};
const make=(indent=0)=>current||(current={kind:'text',parts:[],indent});
function walk(nodes:AnyNode[],style:Omit<NoticePart,'text'>={},indent=0){for(const node of nodes){
if(node.type==='text'){make(indent).parts.push({...style,text:node.data});continue;}if(node.type!=='tag')continue;
const e=node as Element,tag=e.name.toLowerCase();if(blocked.has(tag))continue;const attr=e.attribs||{},next={...style};
if(tag==='strong'||tag==='b')next.bold=true;if(tag==='em'||tag==='i')next.italic=true;if(tag==='u')next.underline=true;
if(tag==='a')next.href=attr.href;const color=attr.style?.match(/(?:^|;)\s*color\s*:\s*(#[0-9a-f]{3,8}|[a-z]+|rgb\([\d,\s]+\))\s*(?:;|$)/i)?.[1];if(color)next.color=color;
if(tag==='br'){make(indent).parts.push({text:'\n'});continue;}
if(tag==='img'){flush();blocks.push({kind:'image',parts:[{text:attr.alt||'公告图片'}],src:attr.src,indent});continue;}
const block=/^(p|div|h[1-6]|blockquote|pre|li|tr)$/.test(tag);if(block&&!(tag!=='li'&&current?.prefix&&!current.parts.length))flush();
if(tag==='ol'||tag==='ul'){flush();lists.push({ordered:tag==='ol',next:Math.max(1,Number(attr.start)||1)});walk(e.children,next,indent);flush();lists.pop();quillCounts.clear();continue;}
const depth=Number(attr.class?.match(/ql-indent-([1-8])/)?.[1]||0)+indent;
if(block){const b=make(depth);b.heading=/^h[1-6]$/.test(tag);const align=attr.class?.match(/ql-align-(center|right)/)?.[1]||attr.style?.match(/text-align:\s*(center|right)/)?.[1];if(align)b.align=align as 'center'|'right';
if(tag==='li'){const list=lists.at(-1),ordered=attr['data-list']?attr['data-list']==='ordered':list?.ordered;if(ordered){const n=attr.value?Number(attr.value):attr['data-list']?(quillCounts.get(depth)||0)+1:list?.next||1;b.prefix=`${n}.`;if(list)list.next=n+1;quillCounts.set(depth,n);}else{b.prefix=attr['data-list']==='checked'?'☑':attr['data-list']==='unchecked'?'☐':'•';quillCounts.delete(depth);}for(const key of quillCounts.keys())if(key>depth)quillCounts.delete(key);}
}
if(!(tag==='span'&&attr.class?.split(/\s+/).includes('ql-ui')))walk(e.children,next,depth+(tag==='blockquote'?1:0));if(tag==='td'||tag==='th')make(depth).parts.push({text:' '});if(block)flush();
}}walk(root.children);flush();return blocks;
}

View File

@ -0,0 +1,14 @@
import {sha256} from '@noble/hashes/sha2.js';
import {bytesToHex} from '@noble/hashes/utils.js';
export type PackageRelease={versionCode:number;versionName:string;sha256:string;size:number;notes:string;environment:string;downloadPath:string};
export function newerPackage(value:any,current:number,environment:string):PackageRelease|null{
if(!Number.isInteger(current)||current<1||!value||value.environment!==environment||!Number.isInteger(value.versionCode)||value.versionCode<=current)return null;
if(!/^[a-f0-9]{64}$/.test(value.sha256)||!Number.isSafeInteger(value.size)||value.size<=0||value.size>250*1024**2||value.downloadPath!==`/system/mobile-release/${value.sha256}/content`||typeof value.versionName!=='string'||value.versionName.length>32||typeof value.notes!=='string'||value.notes.length>140)throw new Error('安装包版本信息无效,请稍后重试');
return value;
}
/** 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('安装包校验失败,请重新下载');}};}
/** 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){
if(!bridge||!/^file:\/\//.test(uri)||!Number.isInteger(version)||version<1||await bridge.verify(uri,version)!==true)throw new Error('无法验证安装包的包名和签名,请联系管理员。');
}

View File

@ -0,0 +1,5 @@
import {Platform} from 'react-native';
import * as SecureStore from 'expo-secure-store';
function key(scope:string,name:string){return 'cmvr.preference.'+name+'.'+Array.from(scope).map(c=>c.codePointAt(0)!.toString(16)).join('-');}
export async function readPreference(scope:string,name:string){const k=key(scope,name),raw=Platform.OS==='web'?localStorage.getItem(k):await SecureStore.getItemAsync(k);return raw?JSON.parse(raw):null;}
export async function savePreference(scope:string,name:string,value:unknown){const k=key(scope,name),raw=JSON.stringify(value);if(Platform.OS==='web')localStorage.setItem(k,raw);else await SecureStore.setItemAsync(k,raw);}

View File

@ -0,0 +1,57 @@
import {validDate,type Row} from './modules.ts';
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 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{
if(!validDate(form.date))return '请选择有效的业务日期。';
if(form.remark.length>500)return '备注最多 500 字。';
if(!rows.length)return '请至少选择一项物品。';
const stocks=new Map<string,number>(),loans=new Map<string,number>();
for(let i=0;i<rows.length;i++){
const row=rows[i],label=`第 ${i+1} 项(${row.source.productName||row.source.itemName||'物品'})`;
if(row.status==='success'||row.payload)continue;
const quantity=Number(row.quantity);
if(!/^\d+(\.\d{1,4})?$/.test(row.quantity)||!Number.isFinite(quantity)||(kind==='check'?quantity<0:quantity<=0))return `${label}:请输入${kind==='check'?'不小于 0':'大于 0'}的数量,最多 4 位小数。`;
if(kind!=='check'&&quantity>available(kind,row))return `${label}:本次数量超过${kind==='return'?'未还数量或取料库存':'当前可用数量'}。`;
if(kind==='check'&&quantity!==available(kind,row)&&!form.remark.trim())return `${label}:盘点有差异,请填写原因。`;
if(['move','receive','borrow','return'].includes(kind)&&!row.area?.id)return `${label}:请选择目标库区。`;
if(kind==='move'&&String(row.source.areaId)===String(row.area?.id))return `${label}:目标库区不能与来源相同。`;
if(kind==='borrow'&&(!form.project?.id||String(form.project.id)===String(row.source.projectId)))return `${label}:请选择不同的借入项目。`;
if(kind==='receive'&&!row.source.receiptRoot&&quantity!==available(kind,row))return `${label}:历史待入库记录须整单办理。`;
if(kind==='return'&&(!row.stock||!row.source.active))return `${label}:请选择有效借用及取料库存。`;
const stockKey=String(kind==='return'?row.stock?.id:row.source.id),units=Math.round(quantity*10000),sum=(stocks.get(stockKey)||0)+units;stocks.set(stockKey,sum);
if(kind!=='check'&&sum>Math.round(Number(kind==='return'?row.stock?.stockNum:kind==='receive'?row.source.inNum:row.source.stockNum)*10000))return `${label}:同一库存的合计数量超过可用数量。`;
if(kind==='return'){const loan=String(row.source.id),returned=(loans.get(loan)||0)+units;loans.set(loan,returned);if(returned>Math.round(Number(row.source.outstandingQuantity)*10000))return `${label}:合计归还数量超过该笔借用的未还数量。`;}
}
return '';
}
export function operationPayload(kind:OperationKind,row:OperationRow,form:OperationForm):RequestStep[]{
const s=row.source,quantity=Number(row.quantity),base={quantity,key:row.key,date:form.date,remark:form.remark};
if(kind==='use')return [{path:'/warehouse/stock/out',method:'POST',body:{id:s.id,usageProjectId:s.projectId,outNum:quantity,outType:4,outNo:'MOUT-'+row.key,outTime:form.date+' 00:00:00',remark:form.remark}}];
if(kind==='move')return [{path:'/warehouse/stock/move',method:'POST',body:{...base,projectId:s.projectId,itemId:s.productId,fromAreaId:s.areaId,toAreaId:row.area?.id}}];
if(kind==='borrow')return [{path:'/project/loans',method:'POST',body:{...base,lenderProjectId:s.projectId,borrowerProjectId:form.project?.id,itemId:s.productId,fromAreaId:s.areaId,toAreaId:row.area?.id}}];
if(kind==='return')return [{path:`/project/loans/${s.id}/return`,method:'POST',body:{...base,fromAreaId:row.stock?.areaId,toAreaId:row.area?.id}}];
if(kind==='check')return [{path:'/warehouse/check',method:'POST',body:{projectId:s.projectId,productId:s.productId,areaId:s.areaId,realNum:quantity,businessDate:form.date,reason:form.remark,remark:form.remark}}];
return s.receiptRoot?[{path:`/warehouse/in/receive/${s.id}`,method:'POST',body:{...base,areaId:row.area?.id}}]:[
{path:'/warehouse/in',method:'PUT',body:{...s,areaId:row.area?.id,businessDate:form.date,remark:form.remark}},
{path:`/warehouse/in/confirm/${s.id}`,method:'PUT',body:{}}
];
}
/** Persist the frozen payload before sending. Only retryable rows reuse the exact identity/body. */
export async function runOperations(kind:OperationKind,rows:OperationRow[],form:OperationForm,request:(path:string,options:any)=>Promise<any>,changed:(rows:OperationRow[],durable:boolean)=>Promise<void>):Promise<OperationRow[]>{
let next=rows.map(row=>({...row,payload:row.payload||operationPayload(kind,row,form)}));
await changed(next,true);
for(let i=0;i<next.length;i++){
if(next[i].status==='success'||['pending','uncertain'].includes(next[i].status)&&!canRetry(kind,next[i]))continue;
next=next.map((r,j)=>i===j?{...r,status:'pending',error:''}:r);await changed(next,!canRetry(kind,next[i]));
try{for(const step of next[i].payload!)await request(step.path,{method:step.method,body:JSON.parse(JSON.stringify(step.body))});next=next.map((r,j)=>i===j?{...r,status:'success',error:''}:r);}
catch(error){next=next.map((r,j)=>i===j?{...r,status:canRetry(kind,r)?'failed':'uncertain',error:(error as Error).message||'处理结果待核对'}:r);}
await changed(next,!canRetry(kind,next[i]));
}
await changed(next,true);
return next;
}

View File

@ -0,0 +1,32 @@
// Expo fetch accepts Blob parts, while the Android picker returns local URI parts.
// Read only local files through the native file reader; HTTP uploads still use
// the authenticated API transport and its redirect/cancellation policy.
type LocalFile = {uri:string;name?:string;type?:string};
function readLocalFile(file:LocalFile,signal:AbortSignal):Promise<Blob>{
if(!/^(?:file|content):\/\//i.test(file.uri))return Promise.reject(new Error('附件地址无效,请重新选择文件。'));
return new Promise((resolve,reject)=>{
if(signal.aborted){reject(new Error('文件读取已取消。'));return;}
const request=new XMLHttpRequest();let settled=false;
const finish=(error?:Error,blob?:Blob)=>{if(settled)return;settled=true;signal.removeEventListener('abort',abort);request.onload=request.onerror=request.onabort=request.ontimeout=null;if(error)reject(error);else resolve(blob!);};
const abort=()=>{request.abort();finish(new Error('文件读取已取消。'));};
request.onload=()=>{const blob=request.response;if((request.status!==0&&request.status!==200)||!(blob instanceof Blob)||!blob.size){finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));return;}finish(undefined,blob.type===file.type||!file.type?blob:blob.slice(0,blob.size,file.type));};
request.onerror=()=>finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));
request.onabort=()=>finish(new Error('文件读取已取消。'));
request.ontimeout=()=>finish(new Error('读取本地附件超时,请重新选择文件。'));
signal.addEventListener('abort',abort,{once:true});
try{request.open('GET',file.uri,true);request.responseType='blob';request.timeout=30000;request.send();}
catch{finish(new Error('无法读取本地附件,请重新拍摄或选择文件后重试。'));}
});
}
export async function readableMultipart(body:FormData,signal:AbortSignal):Promise<FormData>{
const entries=Array.from((body as FormData & {entries():IterableIterator<[string,string|Blob|LocalFile]>}).entries());
const local=(value:unknown):value is LocalFile=>!!value&&typeof value==='object'&&!(value instanceof Blob)&&typeof (value as LocalFile).uri==='string';
if(!entries.some(([,value])=>local(value)))return body;
const prepared=new FormData();
for(const [name,value] of entries){
if(local(value))prepared.append(name,await readLocalFile(value,signal),value.name||'attachment');
else if(value instanceof Blob)prepared.append(name,value,(value as File).name||'attachment');
else prepared.append(name,value);
}
return prepared;
}

View File

@ -0,0 +1,16 @@
import type {Module,Row} from './modules.ts';
import {arrivalListQuery} from './arrival-list.ts';
export type WorkspaceTask={id:string;key:string;label:string;path:string;query:Row;openQuery:Row};
export function workspaceTasks(modules:Module[]):WorkspaceTask[]{
const has=(key:string)=>modules.some(m=>m.key===key);
return [
...(has('arrival')?[{id:'arrival',key:'arrival',label:'待登记到货',path:'/warehouse/purchase/list',query:arrivalListQuery('arrival'),openQuery:{arrivalQueue:'arrival'}},{id:'accept',key:'arrival',label:'待验收',path:'/warehouse/purchase/list',query:arrivalListQuery('accept'),openQuery:{arrivalQueue:'accept'}}]:[]),
...(has('pending')?[{id:'pending',key:'pending',label:'待入库',path:'/warehouse/in/list',query:{inStatus:0},openQuery:{}}]:[]),
...(has('check')?[{id:'check',key:'check',label:'待确认盘点',path:'/warehouse/check/list',query:{checkStatus:0},openQuery:{checkStatus:0}}]:[])
];
}
export function shortcutOrder(stored:unknown,modules:Module[]):string[]{
const allowed=new Set(modules.map(m=>m.key));
const requested=Array.isArray(stored)?stored:['arrival','pending','use','move','count','stock'];
return [...new Set(requested.filter((key):key is string=>typeof key==='string'&&allowed.has(key)))];
}

View File

@ -0,0 +1,48 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import {AppState,Platform} from 'react-native';
import * as SecureStore from 'expo-secure-store';
import {createDraftStore} from '../core/drafts';
import {Dialog} from '../dialogs';
const store=createDraftStore({
get:async key=>Platform.OS==='web'?localStorage.getItem(key):SecureStore.getItemAsync(key),
set:async(key,value)=>{if(Platform.OS==='web')localStorage.setItem(key,value);else await SecureStore.setItemAsync(key,value);},
remove:async key=>{if(Platform.OS==='web')localStorage.removeItem(key);else await SecureStore.deleteItemAsync(key);}
});
type Options<T>={scope?:string;kind:string;id:string|number;value:T;onRestore:(value:T)=>void;enabled?:boolean;suspendAutosave?:boolean;hasContent?:(value:T)=>boolean;isPending?:(value:T)=>boolean};
export function useOperationDraft<T>({scope,kind,id,value,onRestore,enabled=true,suspendAutosave=false,hasContent,isPending}:Options<T>){
const active=!!scope&&enabled,[ready,setReady]=useState(!active),[restored,setRestored]=useState(false),[error,setError]=useState('');
const latest=useRef(value),restore=useRef(onRestore),content=useRef(hasContent),pending=useRef(isPending),cleared=useRef(false),live=useRef(true),readyRef=useRef(!active);
const explicit=useRef<{value:T;fingerprint:string}|null>(null);
const fingerprint=JSON.stringify(value);
// An autosave scheduled before submit must never overwrite the durable
// "pending" snapshot while React is still committing its new state.
if(explicit.current?.fingerprint===fingerprint)explicit.current=null;
latest.current=value;restore.current=onRestore;content.current=hasContent;pending.current=isPending;
const saveNow=useCallback(async(override?:T)=>{
if(!active||!scope||cleared.current)return;
if(override!==undefined)explicit.current={value:override,fingerprint:JSON.stringify(override)};
const next=override===undefined?(explicit.current?.value??latest.current):override;
if(!readyRef.current)throw new Error('请先处理恢复草稿提示');
if(content.current&&!content.current(next))return;
try{await store.save(scope,kind,id,next);if(live.current)setError('');}
catch(e){if(live.current)setError('草稿未保存:'+(e instanceof Error?e.message:'请检查手机存储空间'));throw e;}
},[active,scope,kind,id]);
const clear=useCallback(async()=>{if(!scope||!active)return;cleared.current=true;await store.clear(scope,kind,id);if(live.current){setRestored(false);setError('');}},[scope,active,kind,id]);
useEffect(()=>{
live.current=true;cleared.current=false;readyRef.current=!active;setReady(!active);setRestored(false);let alive=true;
if(active&&scope)void store.load<T>(scope,kind,id).then(saved=>{
if(!alive)return;
const finish=()=>{readyRef.current=true;setReady(true);};
if(!saved){finish();return;}
const uncertain=pending.current?.(saved.value)===true;
Dialog.alert(uncertain?'有待核对的提交':'继续上次填写?',uncertain?'上次提交结果尚待核对。恢复后请先核对记录;重试会保留原请求标识,不会创建另一笔。':'已保留上次填写的内容,尚未自动提交业务。',[
...(!uncertain?[{text:'丢弃草稿',style:'destructive' as const,onPress:()=>{void store.clear(scope,kind,id).then(()=>{if(alive)finish();}).catch(e=>{if(alive)setError(e.message);});}}]:[]),
{text:uncertain?'恢复并核对':'继续填写',onPress:()=>{if(!alive)return;restore.current(saved.value);setRestored(true);finish();}}
]);
}).catch(e=>{if(alive)setError(e instanceof Error?e.message:'无法读取草稿,请核对业务记录后重试');});
return()=>{alive=false;live.current=false;};
},[active,scope,kind,id]);
useEffect(()=>{if(!ready||!active||suspendAutosave||cleared.current)return;const timer=setTimeout(()=>{void saveNow().catch(()=>{});},350);return()=>clearTimeout(timer);},[fingerprint,ready,active,suspendAutosave,saveNow]);
useEffect(()=>{if(!active)return;const sub=AppState.addEventListener('change',state=>{if(state!=='active'&&readyRef.current)void saveNow().catch(()=>{});});return()=>{sub.remove();if(readyRef.current&&!cleared.current)void saveNow().catch(()=>{});};},[active,saveNow]);
return {ready,restored,error,clear,saveNow};
}

View File

@ -0,0 +1,25 @@
import {Platform} from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
import {File,FileMode,Paths,Directory} from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import {fetch as expoFetch} from 'expo/fetch';
import type {ApiClient} from './core/network';
import type {Row} from './core/modules';
import type {UploadSource} from './core/managed-transfer';
export async function pickManagedFile():Promise<UploadSource|null>{
const chosen=await DocumentPicker.getDocumentAsync({type:'*/*',multiple:false,copyToCacheDirectory:true});if(chosen.canceled)return null;const asset=chosen.assets[0];
if(Platform.OS==='web'){const blob=asset.file;if(!blob)throw new Error('无法读取选择的文件');return {name:asset.name,size:blob.size,read:async(start,length)=>new Uint8Array(await blob.slice(start,start+length).arrayBuffer()),close(){}};}
const file=new File(asset.uri);if(file.size>1024**3||!file.size){try{if(file.uri.startsWith(Paths.cache.uri))file.delete();}catch{}throw new Error('请选择非空文件,单个最多1GB');}const handle=file.open(FileMode.ReadOnly),chunkFile=new File(Paths.cache,'upload-chunk-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.bin');
return {name:asset.name,size:file.size,read:async(start,length)=>{handle.offset=start;return handle.readBytes(length);},part:async bytes=>{chunkFile.write(bytes);return {uri:chunkFile.uri,name:'chunk.bin',type:'application/octet-stream'};},close(){handle.close();try{if(chunkFile.exists)chunkFile.delete();}catch{}try{if(file.uri.startsWith(Paths.cache.uri))file.delete();}catch{}}};
}
export async function downloadManagedFile(api:ApiClient,file:Row,signal:AbortSignal,onProgress:(value:number)=>void,action:'open'|'save'='save'){
const path=`/system/files/${encodeURIComponent(file.id)}/content`,name=String(file.name||'file').replace(/[\\/:*?"<>|\x00-\x1f]/g,'_').slice(0,160);
if(Platform.OS==='web'){
const picker=(globalThis as any).showSaveFilePicker;if(picker){const out=await(await picker({suggestedName:name})).createWritable();try{await api.download(path,b=>out.write(b),{signal,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});await out.close();}catch(e){await out.abort();throw e;}return;}
const chunks:Uint8Array<ArrayBuffer>[]=[];await api.download(path,async b=>{chunks.push(Uint8Array.from(b));},{signal,maxBytes:50*1024**2,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});const url=URL.createObjectURL(new Blob(chunks)),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000);return;
}
const dir=new Directory(Paths.cache,'managed-downloads');dir.create({idempotent:true,intermediates:true});const output=new File(dir,Date.now()+'-'+name);output.create();const handle=output.open(FileMode.WriteOnly);
try{await api.download(path,b=>handle.writeBytes(b),{signal,transport:expoFetch as typeof fetch,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});handle.close();if(signal.aborted)throw new Error('下载已取消');if(action==='open'&&await output.canPreview())await output.preview();else if(await Sharing.isAvailableAsync())await Sharing.shareAsync(output.uri,{dialogTitle:'保存或打开文件'});else throw new Error('系统没有可用于打开文件的应用');}
catch(error){try{handle.close();}catch{}try{output.delete();}catch{}throw error;}
// Keep successful files in cache so the selected viewer can finish reading them.
}

View File

@ -0,0 +1,80 @@
import React,{useEffect,useRef,useState} from 'react';
import {KeyboardAvoidingView,Modal,Platform,ScrollView,View} from 'react-native';
import {Text} from '../typography';
import {SafeAreaView} from 'react-native-safe-area-context';
import * as Crypto from 'expo-crypto';
import type {ApiClient} from '../core/network';
import {display,localDate,type Row} from '../core/modules';
import {available,canRetry,operationTitles,runOperations,validateOperation,type OperationKind,type OperationRow,type OperationForm} from '../core/stock-operations';
import {Button,Card,Choice,DateField,Field,Heading,Note,s,useTheme} from '../ui';
import {useOperationDraft} from '../hooks/useOperationDraft';
import {Dialog as Alert} from '../dialogs';
type Snapshot={rows:OperationRow[];form:OperationForm;preview:boolean};
export type BatchOperationProps={api:ApiClient;input:Row[];kind:OperationKind;scope:string;close:()=>void;done:()=>void};
export function BatchOperation({api,input,kind,scope,close,done}:BatchOperationProps){
const t=useTheme(),[rows,setRows]=useState<OperationRow[]>(()=>input.map(source=>({source,quantity:'',area:null,key:Crypto.randomUUID(),status:'editing',error:''}))),[form,setForm]=useState<OperationForm>({date:localDate(),remark:'',project:null});
const [areas,setAreas]=useState<Row[]>([]),[projects,setProjects]=useState<Row[]>([]),[stocks,setStocks]=useState<Row[]>([]),[ready,setReady]=useState(false),[loadError,setLoadError]=useState(''),[error,setError]=useState(''),[preview,setPreview]=useState(false),[busy,setBusy]=useState(false),[reload,setReload]=useState(0);
const lock=useRef(false),alive=useRef(true),snapshot={rows,form,preview},returnSource=kind==='return'?rows[0]?.source:undefined;
const attempted=rows.some(r=>r.payload),succeeded=rows.filter(r=>r.status==='success').length;
// One recoverable operation per action/account. Re-selecting a subset cannot
// silently create fresh identities for a previously uncertain batch.
const draft=useOperationDraft<Snapshot>({scope,suspendAutosave:busy,kind:'stock-'+kind,id:'active',value:snapshot,onRestore:value=>{setRows(value.rows.map(r=>r.status==='pending'?{...r,status:'uncertain'}:r));setForm(value.form);setPreview(value.preview||value.rows.some(r=>r.payload));},hasContent:value=>value.rows.some(r=>r.quantity||r.area||r.payload)||!!value.form.remark||!!value.form.project,isPending:value=>value.rows.some(r=>r.payload&&r.status!=='success')});
useEffect(()=>{alive.current=true;const ctl=new AbortController();setReady(false);setLoadError('');void(async()=>{try{
if(['receive','move','borrow','return'].includes(kind)){const result=await api.request<Row>('/warehouse/area/optionselect',{signal:ctl.signal});if(!ctl.signal.aborted)setAreas(result.data||[]);}
if(kind==='borrow'){const result=await api.request<Row>('/project/info/options',{signal:ctl.signal});if(!ctl.signal.aborted)setProjects(result.data||[]);}
if(kind==='return'){
const all:Row[]=[];let page=1;for(;;){const result=await api.request<Row>('/warehouse/stock/list',{signal:ctl.signal,query:{projectId:returnSource?.borrowerProjectId,productId:returnSource?.itemId,pageNum:page++,pageSize:100,includeZero:false}});const chunk=result.rows||[];all.push(...chunk);if(!chunk.length||all.length>=result.total)break;if(page>100)throw new Error('库存过多,请在库存页面缩小范围后办理。');}
if(!ctl.signal.aborted)setStocks(all.filter(r=>Number(r.stockNum)>0).map(r=>({...r,label:`${r.areaName||r.areaCode||'库区'} · 可用 ${r.stockNum}`})));
}
if(!ctl.signal.aborted)setReady(true);
}catch(e){if(!ctl.signal.aborted)setLoadError((e as Error).message);}})();return()=>{alive.current=false;ctl.abort();};},[api,kind,reload,returnSource?.id]);
function changeRow(index:number,patch:Partial<OperationRow>){if(attempted||busy)return;setRows(old=>old.map((r,i)=>i===index?{...r,...patch}:r));setError('');}
function fill(){if(attempted)return;setRows(old=>old.map(r=>({...r,quantity:String(available(kind,r))})));}
function allReturn(){
if(!returnSource)return;const remaining=Number(returnSource.outstandingQuantity),total=stocks.reduce((sum,r)=>sum+Math.round(Number(r.stockNum)*10000),0)/10000;
if(total<remaining)return setError(`可取料库存 ${total},不足以归还全部 ${remaining},请填写部分归还数量。`);
let left=remaining;const target=rows[0]?.area||areas.find(a=>String(a.id)===String(returnSource.originalAreaId))||null;
const next:OperationRow[]=[];for(const stock of stocks){const qty=Math.min(left,Number(stock.stockNum));if(qty>0)next.push({source:returnSource,stock,quantity:String(qty),area:target,key:Crypto.randomUUID(),status:'editing',error:''});left=Number((left-qty).toFixed(4));if(left<=0)break;}setRows(next);setError('');
}
function prepare(){const issue=validateOperation(kind,rows,form);if(issue)return setError(issue);setError('');setPreview(true);}
async function submit(){
if(lock.current||!ready||!draft.ready||!preview)return;
const issue=validateOperation(kind,rows,form);if(issue)return setError(issue);
lock.current=true;setBusy(true);setError('');
try{const result=await runOperations(kind,rows,form,(path,options)=>api.request(path,options),async(next,durable)=>{if(durable)await draft.saveNow({rows:next,form,preview:true});if(alive.current)setRows(next);});if(result.every(r=>r.status==='success'))await draft.clear();}
catch(e){if(alive.current)setError('无法保存本次处理状态:'+(e as Error).message+'。请先核对业务记录。');}
finally{lock.current=false;if(alive.current)setBusy(false);}
}
async function leave(){if(busy)return;try{await draft.saveNow();if(succeeded===rows.length)await draft.clear();succeeded?done():close();}catch(e){setError('草稿尚未保存,请稍后重试:'+(e as Error).message);}}
function requestClose(){if(busy)return;if(attempted&&succeeded!==rows.length)Alert.alert('保留处理记录','未完成项会保留原请求,重新打开相同物品可继续核对。请勿新建重复业务。',[{text:'继续核对',style:'cancel'},{text:'保存并关闭',onPress:()=>void leave()}]);else void leave();}
function finishChecked(){if(busy)return;Alert.alert('结束本次本地记录','请先在入库、出库、借还或盘点记录中核对本次结果。此操作只清除手机恢复记录,不会撤销、补交或修改任何业务。确认已经核对完成?',[{text:'继续保留',style:'cancel'},{text:'已核对,结束本次',onPress:()=>{void draft.clear().then(done).catch(e=>setError((e as Error).message));}}]);}
const retryable=rows.some(r=>r.status!=='success'&&(!['pending','uncertain'].includes(r.status)||canRetry(kind,r)));
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:16,paddingVertical:8,borderBottomWidth:1,borderColor:t.line,flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}><Heading>{rows.length>1?'批量':''}{operationTitles[kind]}</Heading><Button title="关闭" secondary disabled={busy} onPress={requestClose}/></View>
<ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{padding:14,gap:12}]}>
{loadError?<><Note>{loadError}</Note><Button title="重试加载" secondary onPress={()=>setReload(n=>n+1)}/></>:!ready?<Note>正在核对可选项目和库区…</Note>:null}
{!!draft.error&&<Note>{draft.error}</Note>}
{draft.restored&&<Note>已恢复上次 {rows.length} 项{operationTitles[kind]},请以以下物品和处理状态为准。</Note>}
{!preview?<>
<DateField label="业务日期" value={form.date} onChange={date=>setForm(old=>({...old,date}))}/>
{kind==='borrow'&&<Choice label="借入项目" items={projects} value={form.project} onChange={project=>setForm(old=>({...old,project}))} nameKey="projectName"/>}
<Field label={kind==='check'?'差异原因':'备注(选填)'} value={form.remark} onChange={remark=>setForm(old=>({...old,remark}))} multiline maxLength={500}/>
{['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>
{!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>
<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))}/>}
</>:<><Text style={{fontSize:16,lineHeight:23,fontWeight:'600',color:t.accent}}>{row.quantity} {row.source.unit||''}</Text>{!!row.area&&<Note>目标库区:{row.area.areaName||row.area.areaCode}</Note>}{kind==='check'&&<Note>账面 {row.source.stockNum} → 实盘 {row.quantity};确认盘点生效后才调整库存。</Note>}<Text style={{color:row.status==='success'?'#278357':row.error?'#bd3636':t.muted,fontSize:13,lineHeight:20}}>{row.status==='success'?'已成功':row.status==='pending'?'正在处理':row.status==='uncertain'?'结果待核对,不会自动重发':row.error||'待提交'}</Text></>}
</Card>)}
{!!error&&<Text accessibilityRole="alert" style={{color:'#bd3636',fontSize:14,lineHeight:21}}>{error}</Text>}
{attempted&&succeeded!==rows.length&&!busy&&<Button title="已核对业务记录,结束本次" secondary onPress={finishChecked}/>}
</ScrollView>
<View style={{padding:12,backgroundColor:t.card,borderTopWidth:1,borderColor:t.line,gap:8}}>{!preview?<Button title={`核对 ${rows.length} 项`} disabled={!ready||!draft.ready||!rows.length} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}>{!attempted&&<View style={{flex:1}}><Button title="返回修改" secondary disabled={busy} onPress={()=>setPreview(false)}/></View>}<View style={{flex:1}}>{succeeded===rows.length?<Button title="完成" onPress={()=>void leave()}/>:<Button title={attempted?'重试未成功项':'确认提交'} busy={busy} disabled={!retryable||!ready||!draft.ready} onPress={()=>void submit()}/>}</View></View>}</View>
</KeyboardAvoidingView></SafeAreaView></Modal>;
}

View File

@ -0,0 +1,77 @@
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 {ArrivalCard,ArrivalListTools} from './ArrivalListParts';
import {arrivalListQuery} from '../core/arrival-list';
import {ArrivalActions} from './ArrivalActions';
import {ArrivalHistory} from './ArrivalHistory';
import {ArrivalOperation} from './ArrivalOperation';
import {StockOperation} from './StockOperation';
import {BatchOperation} from './BatchOperation';
import {LoanOperation} from './LoanOperation';
import type {OperationKind} from '../core/stock-operations';
import {Dialog as Alert} from '../dialogs';
type SavedList={query:string;applied:string;rows:Row[];total:number;page:number;offset:number;queue:'arrival'|'accept';compact:boolean};
const remembered=new Map<string,SavedList>();
export function BusinessList({api,module,permissions,canViewQuotes,scope,initialQuery={},onNavigate}:{api:ApiClient;module:Module;permissions:string[];canViewQuotes:boolean;scope:string;initialQuery?:Row;onNavigate?:(key:string,query?:Row)=>void}){
const t=useTheme(),cacheKey=scope+'|'+module.key+'|'+JSON.stringify(initialQuery),cached=useRef(remembered.get(cacheKey));
const [query,setQuery]=useState(cached.current?.query||''),[rows,setRows]=useState<Row[]>(cached.current?.rows||[]),[total,setTotal]=useState(cached.current?.total||0),[page,setPage]=useState(cached.current?.page||1),[arrivalQueue,setArrivalQueue]=useState<'arrival'|'accept'>(initialQuery.arrivalQueue||cached.current?.queue||'arrival');
const [busy,setBusy]=useState(false),[error,setError]=useState(''),[compactAmounts,setCompactAmounts]=useState(cached.current?.compact??true),[selected,setSelected]=useState<Row[]>([]),[picking,setPicking]=useState(!!initialQuery.borrow),[batch,setBatch]=useState<OperationKind|null>(null),[operation,setOperation]=useState<{row:Row;kind:string}|null>(null),[historyRow,setHistoryRow]=useState<Row|null>(null);
const serial=useRef(0),controller=useRef<AbortController|null>(null),busyRef=useRef(false),appliedQuery=useRef(cached.current?.applied||''),offset=useRef(cached.current?.offset||0),list=useRef<FlatList<Row>>(null),first=useRef(true),lastRequest=useRef({next:1,text:'',append:false});
const stockWrite=allows(permissions,['warehouse:stock:out'],['project:inventory:use']),stockRead=allows(permissions,['warehouse:stock:list']);
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):{}),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});}
}catch(e){if(id===serial.current)setError((e as Error).message);}finally{if(id===serial.current){busyRef.current=false;setBusy(false);}}
},[api,module,arrivalQueue,cacheKey]);
useEffect(()=>{if(first.current&&cached.current){first.current=false;}else{first.current=false;void load(1,appliedQuery.current);}return()=>{serial.current++;controller.current?.abort();};},[load]);
useEffect(()=>{remembered.set(cacheKey,{query,applied:appliedQuery.current,rows,total,page,offset:offset.current,queue:arrivalQueue,compact:compactAmounts});if(remembered.size>30)remembered.delete(remembered.keys().next().value!);},[cacheKey,query,rows,total,page,arrivalQueue,compactAmounts]);
function refresh(){return load(1,appliedQuery.current);}
function eligible(row:Row){return module.key==='pending'?allows(permissions,['warehouse:in:confirm'])&&(row.receiptRoot||allows(permissions,['warehouse:in:edit']))&&Number(row.inNum)>0:stockWrite&&Number(row.stockNum)>0;}
function toggle(row:Row){if(busy||!eligible(row))return;setSelected(old=>old.some(r=>String(r.id)===String(row.id))?old.filter(r=>String(r.id)!==String(row.id)):old.length>=100?old:[...old,row]);}
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'})}/>}
{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={setArrivalQueue} busy={busy} total={total} page={page} 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>{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>}
{!!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>}
<FlatList ref={list} data={rows} keyExtractor={(row,index)=>String(row.id||row.loanNo||index)} onScroll={event=>{offset.current=event.nativeEvent.contentOffset.y;const saved=remembered.get(cacheKey);if(saved)saved.offset=offset.current;}} scrollEventThrottle={100} onLayout={()=>{if(cached.current?.offset){list.current?.scrollToOffset({offset:cached.current.offset,animated:false});cached.current=undefined;}}} contentContainerStyle={{paddingHorizontal:14,paddingBottom:14,gap:10}}
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>}
{!!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>;
}

View File

@ -0,0 +1,26 @@
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {FlatList,Pressable,View} from 'react-native';
import {Text,TextInput} from '../typography';
import {Button,Card,Icon,Note,useTheme} from '../ui';
import {allows,type ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {formatDateTime} from '../core/date-display';
import {uploadManagedFile,type TransferProgress} from '../core/managed-transfer';
import {pickManagedFile} from '../managed-files';
import {ManagedAttachments} from './ManagedAttachments';
export function FileLibrary({api,permissions,scope}:{api:ApiClient;permissions:string[];scope:string}){
const t=useTheme(),[query,setQuery]=useState(''),[mine,setMine]=useState(false),[rows,setRows]=useState<Row[]>([]),[page,setPage]=useState(1),[total,setTotal]=useState(0),[busy,setBusy]=useState(false),[canUpload,setCanUpload]=useState(false),[error,setError]=useState(''),[upload,setUpload]=useState<TransferProgress|null>(null),[uploadName,setUploadName]=useState('');
const serial=useRef(0),loadCtl=useRef<AbortController|null>(null),uploadCtl=useRef<AbortController|null>(null),alive=useRef(true),busyRef=useRef(false);
const allowed=allows(permissions,['system:file:list','system:file:manage']);
const load=useCallback(async(next=1)=>{if(!allowed)return;loadCtl.current?.abort();const ctl=new AbortController();loadCtl.current=ctl;const id=++serial.current;setBusy(true);busyRef.current=true;setError('');try{const response=await api.request<Row>('/system/files',{query:{keyword:query.trim(),mine,page:next,size:20},signal:ctl.signal});if(alive.current&&id===serial.current){const data=response.data;setRows(old=>next===1?data.rows:[...old,...data.rows.filter((n:Row)=>!old.some(v=>v.id===n.id))]);setPage(next);setTotal(data.total);setCanUpload(data.canUpload===true);}}catch(e){if(alive.current&&id===serial.current&&!ctl.signal.aborted)setError((e as Error).message);}finally{if(id===serial.current){busyRef.current=false;if(alive.current)setBusy(false);}}},[api,query,mine,allowed]);
useEffect(()=>{alive.current=true;const timer=setTimeout(()=>void load(),250);return()=>{clearTimeout(timer);loadCtl.current?.abort();serial.current++;};},[load,scope]);
useEffect(()=>()=>{alive.current=false;loadCtl.current?.abort();uploadCtl.current?.abort();},[api,scope]);
async function choose(){if(uploadCtl.current||!canUpload)return;const ctl=new AbortController();uploadCtl.current=ctl;setError('');try{const file=await pickManagedFile();if(!file)return;if(!alive.current||ctl.signal.aborted){file.close();return;}setUploadName(file.name);setUpload({phase:'hashing',percent:0});await uploadManagedFile(api,file,ctl.signal,p=>{if(alive.current)setUpload(p);});if(alive.current)await load();}catch(e){if(alive.current)setError((e as Error).message);}finally{uploadCtl.current=null;if(alive.current)setUpload(null);}}
if(!allowed)return <Note>当前账号尚未开通共享文件权限。</Note>;
return <View style={{flex:1,paddingHorizontal:14,gap:8}}><View style={{flexDirection:'row',gap:8,alignItems:'center'}}><View style={{flex:1,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:8,paddingHorizontal:9,backgroundColor:t.card}}><Icon name="search-outline" size={17}/><TextInput accessibilityLabel="搜索文件名或上传人" placeholder="文件名或上传人" placeholderTextColor={t.muted} value={query} onChangeText={setQuery} returnKeyType="search" onSubmitEditing={()=>void load()} style={{flex:1,minHeight:44,color:t.text,fontSize:14,paddingHorizontal:7}}/></View>{canUpload&&<Button title="上传" disabled={!!upload} onPress={()=>void choose()}/>}</View>
<View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}><Pressable accessibilityRole="checkbox" accessibilityState={{checked:mine}} onPress={()=>setMine(v=>!v)} style={{minHeight:44,justifyContent:'center'}}><Text style={{color:mine?t.accent:t.muted,fontSize:13}}>{mine?'☑':'☐'} 我的上传</Text></Pressable><Text style={{color:t.muted,fontSize:12}}>共 {total} 个文件</Text></View>
{!!upload&&<Card><Text numberOfLines={1} style={{color:t.text,fontSize:14}}>{uploadName}</Text><View style={{height:5,backgroundColor:t.line,borderRadius:3}}><View style={{height:5,width:`${upload.percent}%`,backgroundColor:t.accent,borderRadius:3}}/></View><View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}><Text style={{color:t.muted,fontSize:12}}>{{hashing:'校验中',uploading:'上传中',saving:'保存中',done:'已完成'}[upload.phase]} {upload.percent}%</Text><Button title="暂停" secondary onPress={()=>uploadCtl.current?.abort()}/></View></Card>}
{!!error&&<View><Note>{error}</Note><Button title="重新加载" secondary disabled={busy} onPress={()=>void load()}/></View>}
<FlatList data={rows} keyExtractor={r=>r.id} refreshing={busy&&page===1} onRefresh={()=>void load()} contentContainerStyle={{gap:10,paddingBottom:20}} renderItem={({item})=><Card><ManagedAttachments api={api} files={[item]}/><Text style={{color:t.muted,fontSize:12}}>{item.uploadedBy} · {formatDateTime(item.uploadedAt)}</Text></Card>} ListEmptyComponent={!busy?<Note>暂无文件,可上传后共享给有权限的同事。</Note>:<Note>正在加载…</Note>} ListFooterComponent={rows.length<total?<Button title={busy?'加载中':'加载更多'} secondary busy={busy} onPress={()=>{if(!busyRef.current)void load(page+1);}}/>:undefined}/>
</View>;
}

View File

@ -0,0 +1,5 @@
import React from 'react';
import {StockOperation} from './StockOperation';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
export function LoanOperation(props:{api:ApiClient;row:Row;scope:string;close:()=>void;done:()=>void}){return <StockOperation {...props} kind="return"/>;}

View File

@ -0,0 +1,33 @@
import React,{useState} from 'react';
import {ActivityIndicator,Image,KeyboardAvoidingView,Platform,Pressable,ScrollView,StyleSheet,View} from 'react-native';
import {Text,TextInput} from '../typography';
import {Icon} from '../ui';
import type {Row} from '../core/modules';
type Props={environment:string;username:string;password:string;code:string;captcha:Row|null;busy:boolean;connecting:boolean;error:string;server:string;connection?:React.ReactNode;setUsername:(v:string)=>void;setPassword:(v:string)=>void;setCode:(v:string)=>void;refresh:()=>void;submit:()=>void};
export function LoginView(p:Props){
const dev=p.environment!=='prod',[visible,setVisible]=useState(false),[settings,setSettings]=useState(false);
const accent=dev?'#ffbb68':'#60e0cf';
const icon=dev?require('../../assets/brand/app-icon-blue-dev.png'):require('../../assets/brand/app-icon-blue-prod.png');
const input=(label:string,value:string,change:(v:string)=>void,kind:'person-outline'|'lock-closed-outline'|'shield-checkmark-outline',secure=false)=><View style={{gap:7,flex:1,minWidth:0}}><Text style={styles.label}>{label}</Text><View style={styles.inputWrap}><Icon name={kind} size={18} color="#7b91a8"/><TextInput accessibilityLabel={label} value={value} onChangeText={change} editable={!p.busy} secureTextEntry={secure&&!visible} autoCapitalize="none" autoCorrect={false} placeholder={label==='验证码'?'输入验证码':`请输入${label}`} placeholderTextColor="#9aabba" returnKeyType={secure?'go':'next'} onSubmitEditing={secure?p.submit:undefined} style={styles.input}/>{secure&&<Pressable accessibilityRole="button" accessibilityLabel={visible?'隐藏密码':'显示密码'} accessibilityState={{disabled:p.busy}} disabled={p.busy} onPress={()=>setVisible(v=>!v)} style={styles.iconButton}><Icon name={visible?'eye-off-outline':'eye-outline'} size={19} color="#7189a0"/></Pressable>}</View></View>;
return <KeyboardAvoidingView style={styles.page} behavior={Platform.OS==='ios'?'padding':undefined}>
<View pointerEvents="none" style={styles.heroImage}><Image accessible={false} source={require('../../assets/brand/login-tech-background.jpg')} resizeMode="cover" style={{width:'100%',height:600}}/><View style={[StyleSheet.absoluteFill,{backgroundColor:'rgba(2,13,30,.16)'}]}/></View>
<ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.scroll}>
<View style={styles.brand}><Image accessible={false} source={icon} style={styles.mark}/><View style={{flex:1,minWidth:0,gap:3}}><Text style={styles.brandName}>招商车研</Text><Text style={styles.department}>研发中心 · 设备仪器科</Text></View><View style={[styles.badge,{borderColor:dev?'#94724a':'#31696d'}]}><View style={{width:5,height:5,borderRadius:3,backgroundColor:accent}}/><Text style={{color:accent,fontSize:11,lineHeight:17}}>{dev?'开发环境':'正式环境'}</Text></View></View>
<View style={styles.intro}><Text style={styles.title}>设备科综合管理系统</Text><Text style={styles.subtitle}>连接研发现场,让每一项业务清晰有序</Text></View>
<View style={styles.card}>
<View style={{gap:4,marginBottom:4}}><Text style={styles.cardTitle}>登录工作空间</Text><Text style={styles.hint}>请连接公司内网,使用现有账号登录</Text></View>
{input('登录账号',p.username,p.setUsername,'person-outline')}
{input('密码',p.password,p.setPassword,'lock-closed-outline',true)}
{!!p.captcha&&p.captcha.captchaEnabled!==false&&<View style={{flexDirection:'row',gap:10,alignItems:'flex-end'}}>{input('验证码',p.code,p.setCode,'shield-checkmark-outline')}<Pressable accessibilityRole="button" accessibilityLabel="刷新验证码" disabled={p.busy} onPress={p.refresh} style={styles.captcha}>{p.captcha.img?<Image source={{uri:`data:image/png;base64,${p.captcha.img}`}} resizeMode="contain" style={{width:106,height:46}}/>:<Text style={styles.hint}>点击刷新</Text>}</Pressable></View>}
{!!p.error&&<View accessibilityRole="alert" style={styles.error}><Icon name="alert-circle-outline" size={18} color="#ce3e46"/><Text style={{flex:1,minWidth:0,color:'#ad3038',fontSize:13,lineHeight:20}}>{p.error}</Text></View>}
<Pressable accessibilityRole="button" accessibilityLabel="登录" accessibilityState={{disabled:!p.captcha||p.busy,busy:p.busy}} disabled={!p.captcha||p.busy} onPress={p.submit} style={({pressed})=>[styles.submit,{backgroundColor:'#216fc2',opacity:!p.captcha||p.busy?.5:pressed?.8:1}]}>{p.busy?<ActivityIndicator color="#ffffff"/>:<><Text style={styles.submitText}>登录</Text><Icon name="arrow-forward" size={18} color="#ffffff"/></>}</Pressable>
<View style={styles.statusRow}><View style={{flexDirection:'row',alignItems:'center',gap:6,flex:1,minWidth:0}}>{p.connecting?<ActivityIndicator size="small" color="#66829d"/>:<Icon name={p.captcha?'shield-checkmark-outline':'cloud-offline-outline'} size={15} color={p.captcha?'#298c73':'#8497a8'}/>}<Text style={styles.status}>{p.connecting?'正在连接内网服务…':p.captcha?'内网连接正常':'暂未连接服务'}</Text></View><Pressable accessibilityRole="button" accessibilityLabel="重新连接" disabled={p.busy||p.connecting} onPress={p.refresh} style={styles.reconnect}><Text style={{fontSize:12,color:'#246db4'}}>重新连接</Text></Pressable></View>
</View>
{dev&&!!p.connection&&<><Pressable accessibilityRole="button" accessibilityLabel="开发服务设置" accessibilityState={{expanded:settings}} onPress={()=>setSettings(v=>!v)} style={styles.settings}><Icon name="settings-outline" size={15} color="#66839f"/><Text style={{fontSize:12,color:'#4e7195'}}>开发服务设置</Text><Icon name={settings?'chevron-up':'chevron-down'} size={14} color="#66839f"/></Pressable>{settings&&<View style={{borderRadius:14,overflow:'hidden'}}>{p.connection}</View>}</>}
<View style={styles.footer}><View style={{height:1,width:24,backgroundColor:'#cddbe8'}}/><Text style={{fontSize:11,lineHeight:17,color:'#849bb1',textAlign:'center'}}>CMVR · 设备与研发同行</Text><View style={{height:1,width:24,backgroundColor:'#cddbe8'}}/></View>
</ScrollView>
</KeyboardAvoidingView>;
}
const styles=StyleSheet.create({page:{flex:1,minHeight:0,backgroundColor:'#f3f7fb'},heroImage:{position:'absolute',top:0,left:0,right:0,height:260,overflow:'hidden',backgroundColor:'#0a2844'},scroll:{paddingHorizontal:22,paddingTop:24,paddingBottom:24,flexGrow:1,width:'100%',maxWidth:480,alignSelf:'center'},brand:{flexDirection:'row',alignItems:'center',gap:10},mark:{width:46,height:46,borderRadius:12},brandName:{color:'#f5faff',fontSize:21,lineHeight:29,fontWeight:'700',letterSpacing:2},department:{color:'#bbcfdf',fontSize:12,lineHeight:19},badge:{flexDirection:'row',alignItems:'center',gap:5,borderWidth:1,borderRadius:20,paddingHorizontal:8,paddingVertical:4,backgroundColor:'#071b31'},intro:{paddingTop:54,paddingBottom:25,gap:6},title:{color:'#f1faff',fontSize:24,lineHeight:34,fontWeight:'700',letterSpacing:1,textShadowColor:'#001122',textShadowRadius:8,textShadowOffset:{width:0,height:1}},subtitle:{color:'#d8e8f3',fontSize:12,lineHeight:20,textShadowColor:'#001122',textShadowRadius:8,textShadowOffset:{width:0,height:1}},card:{borderWidth:1,borderColor:'#e2ebf4',borderRadius:20,padding:20,gap:16,backgroundColor:'#ffffff',shadowColor:'#244769',shadowOpacity:.12,shadowRadius:24,elevation:5},cardTitle:{color:'#1b344b',fontSize:18,lineHeight:25,fontWeight:'600'},hint:{color:'#71869a',fontSize:12,lineHeight:19},label:{color:'#405a71',fontSize:13,lineHeight:19},inputWrap:{flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:'#d8e4ef',borderRadius:10,backgroundColor:'#f7fafe',paddingLeft:12,minHeight:48},input:{flex:1,minWidth:0,paddingHorizontal:10,paddingVertical:11,minHeight:48,color:'#263e54',fontSize:14,lineHeight:22},iconButton:{minWidth:44,minHeight:46,justifyContent:'center',alignItems:'center'},captcha:{width:108,minHeight:48,borderRadius:10,overflow:'hidden',backgroundColor:'#e9f2fa',alignItems:'center',justifyContent:'center'},submit:{minHeight:48,flexDirection:'row',gap:10,justifyContent:'center',alignItems:'center',borderRadius:10,marginTop:3,padding:10},submitText:{color:'#ffffff',fontSize:15,lineHeight:22,fontWeight:'700'},statusRow:{flexDirection:'row',alignItems:'center',gap:6,marginTop:-7,marginBottom:-10},status:{color:'#71899e',fontSize:11,lineHeight:18,flexShrink:1},reconnect:{minHeight:44,justifyContent:'center',paddingLeft:8},error:{flexDirection:'row',alignItems:'flex-start',gap:7,backgroundColor:'#fff1f1',borderRadius:9,padding:10},settings:{minHeight:44,flexDirection:'row',gap:7,alignItems:'center',justifyContent:'center',marginTop:5},footer:{flexDirection:'row',gap:12,alignItems:'center',justifyContent:'center',paddingTop:26}});

View File

@ -0,0 +1,14 @@
import React,{useEffect,useRef,useState} from 'react';
import {View} from 'react-native';
import {Text} from '../typography';
import {Button,Icon,Note,useTheme} from '../ui';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {downloadManagedFile} from '../managed-files';
import {fileSize} from '../core/managed-transfer';
export function ManagedAttachments({api,files}:{api:ApiClient;files:Row[]}){
const t=useTheme(),[job,setJob]=useState<{id:string;progress:number}|null>(null),[error,setError]=useState(''),ctl=useRef<AbortController|null>(null),alive=useRef(true);
useEffect(()=>{alive.current=true;return()=>{alive.current=false;ctl.current?.abort();};},[api]);
async function download(file:Row,action:'open'|'save'){if(ctl.current)return;const controller=new AbortController();ctl.current=controller;setError('');setJob({id:file.id,progress:0});try{await downloadManagedFile(api,file,controller.signal,n=>{if(alive.current)setJob({id:file.id,progress:n});},action);}catch(e){if(alive.current)setError(controller.signal.aborted?'下载已取消':(e as Error).message);}finally{ctl.current=null;if(alive.current)setJob(null);}}
return <View style={{gap:10}}>{files.map(file=><View key={file.id} style={{paddingVertical:8,borderTopWidth:1,borderColor:t.line,gap:5}}><View style={{flexDirection:'row',alignItems:'center',gap:8}}><Icon name="document-outline" size={18}/><Text selectable style={{flex:1,fontSize:14,color:t.text,lineHeight:21}}>{file.name}</Text></View><View style={{flexDirection:'row',alignItems:'center',gap:8}}><Text style={{flex:1,color:t.muted,fontSize:12}}>{fileSize(file.size)}{job?.id===file.id?` · ${job?.progress}%`:''}</Text>{file.canDownload!==false&&<><Button title="打开" secondary disabled={!!job} onPress={()=>void download(file,'open')}/><Button title="下载" secondary disabled={!!job} onPress={()=>void download(file,'save')}/></>}</View>{job?.id===file.id&&<Button title="取消下载" secondary onPress={()=>ctl.current?.abort()}/>}</View>)}{!!error&&<Note>{error}</Note>}</View>;
}

View File

@ -0,0 +1,7 @@
import React,{useState} from 'react';
import {Image,Linking,Pressable,View} from 'react-native';
import {Text} from '../typography';
import {Note,useTheme} from '../ui';
import {noticeBlocks,safeNoticeUrl} from '../core/notice-content';
function NoticeImage({src,label}:{src:string;label:string}){const [failed,setFailed]=useState(false),[ratio,setRatio]=useState(1.6);return failed?<Note>图片暂不可用</Note>:<Pressable accessibilityRole="button" accessibilityLabel={label} onPress={()=>void Linking.openURL(src).catch(()=>setFailed(true))}><Image accessibilityLabel={label} source={{uri:src}} onError={()=>setFailed(true)} onLoad={e=>{const s=e.nativeEvent.source;if(s.width&&s.height)setRatio(s.width/s.height);}} style={{width:'100%',aspectRatio:ratio,maxHeight:420,borderRadius:6}} resizeMode="contain"/></Pressable>;}
export function NoticeContent({html,baseUrl}:{html:string;baseUrl:string}){const t=useTheme();return <View style={{gap:8}}>{noticeBlocks(html).map((block,i)=>block.kind==='image'?(()=>{const src=safeNoticeUrl(block.src,baseUrl);return src?<NoticeImage key={i} src={src} label={block.parts[0].text}/>:null;})():<View key={i} style={{flexDirection:'row',gap:7,paddingLeft:Math.min(block.indent,8)*12}}>{!!block.prefix&&<Text style={{minWidth:20,color:t.text,fontSize:14,lineHeight:22}}>{block.prefix}</Text>}<Text selectable style={{flex:1,color:t.text,fontSize:block.heading?16:14,lineHeight:block.heading?25:22,fontWeight:block.heading?'600':'400',textAlign:block.align||'left'}}>{block.parts.map((part,j)=>{const href=part.href?safeNoticeUrl(part.href,baseUrl):null;return <Text key={j} accessibilityRole={href?'link':undefined} onPress={href?()=>void Linking.openURL(href).catch(()=>{}):undefined} style={{fontWeight:part.bold?'700':undefined,fontStyle:part.italic?'italic':undefined,textDecorationLine:part.underline||href?'underline':undefined,color:href?t.accent:part.color||t.text}}>{part.text}</Text>;})}</Text></View>)}</View>;}

View File

@ -0,0 +1,6 @@
import React from 'react';
import {BatchOperation} from './BatchOperation';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import type {OperationKind} from '../core/stock-operations';
export function StockOperation({row,...props}:{api:ApiClient;row:Row;kind:OperationKind;scope:string;close:()=>void;done:()=>void}){return <BatchOperation {...props} input={[row]}/>;}

View File

@ -0,0 +1,14 @@
import React,{createContext,useContext,forwardRef} from 'react';
import {Text as NativeText,TextInput as NativeInput,StyleSheet,type TextProps,type TextInputProps,type TextStyle} from 'react-native';
export type ReadingSize='compact'|'standard'|'large';
export const readingScales={compact:1,standard:1.1,large:1.22};
export const ReadingContext=createContext<{size:ReadingSize;setSize:(size:ReadingSize)=>void}>({size:'compact',setSize(){}});
export function useReadingScale(){return readingScales[useContext(ReadingContext).size];}
function textStyle(style:TextProps['style'],scale:number){
const flat=StyleSheet.flatten(style)||{};
return [style,{fontSize:Math.round((flat.fontSize??14)*scale*10)/10,lineHeight:Math.round((flat.lineHeight??Math.max(20,(flat.fontSize??14)*1.4))*scale*10)/10} as TextStyle];
}
// RN already applies the system's font scale. Only the explicit in-app preference
// is applied here; never multiply by PixelRatio/fontScale a second time.
export function Text({style,...props}:TextProps){return <NativeText {...props} style={textStyle(style,useReadingScale())}/>;}
export const TextInput=forwardRef<React.ComponentRef<typeof NativeInput>,TextInputProps>(function TextInput({style,...props},ref){return <NativeInput {...props} ref={ref} style={textStyle(style,useReadingScale())}/>;});

View File

@ -0,0 +1,44 @@
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 {createDraftStore} from '../src/core/drafts.ts';
const require=createRequire(import.meta.url),ts=require('typescript');
const settle=()=>new Promise(resolve=>setImmediate(resolve));
function harness(initial){
const data=new Map(),storage={get:async k=>data.get(k)??null,set:async(k,v)=>{data.set(k,v);},remove:async k=>{data.delete(k);}},store=createDraftStore(storage),slots=[],effects=[],timers=new Map();
let cursor=0,nextTimer=1,options=initial,prompt,result;
const same=(a,b)=>a&&b&&a.length===b.length&&a.every((v,i)=>Object.is(v,b[i]));
const react={useState:initial=>{const i=cursor++;if(!(i in slots))slots[i]=typeof initial==='function'?initial():initial;return [slots[i],value=>{slots[i]=typeof value==='function'?value(slots[i]):value;}];},useRef:initial=>{const i=cursor++;return slots[i]??={current:initial};},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 code=ts.transpileModule(readFileSync(new URL('../src/hooks/useOperationDraft.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,exports={};
vm.runInNewContext(code,{exports,require:name=>({react,'react-native':{Platform:{OS:'web'},AppState:{addEventListener:()=>({remove(){}})}},'expo-secure-store':{},'../core/drafts':{createDraftStore:()=>store},'../dialogs':{Dialog:{alert:(...args)=>{prompt=args;}}}}[name]||require(name)),setTimeout:fn=>{const id=nextTimer++;timers.set(id,fn);return id;},clearTimeout:id=>timers.delete(id)});
function render(){cursor=0;result=exports.useOperationDraft(options);while(effects.length)effects.shift()();return result;}
return {store,render,get prompt(){return prompt;},get result(){return result;},set value(v){options={...options,value:v};},set suspendAutosave(v){options={...options,suspendAutosave:v};},flushTimers(){const callbacks=[...timers.values()];timers.clear();callbacks.forEach(fn=>fn());},destroy(){slots.forEach(slot=>slot?.cleanup?.());}};
}
test('pending submission survives an older debounce autosave before React catches up',async()=>{
const original={quantity:'2',attempted:false,key:'stable'},h=harness({scope:'dev/user',kind:'out',id:11,value:original,onRestore(){},isPending:v=>v.attempted});
h.render();await settle();h.render();assert.equal(h.result.ready,true);
await h.result.saveNow({...original,attempted:true});
// The component has not re-rendered its attempted=true state yet.
h.flushTimers();await settle();assert.equal((await h.store.load('dev/user','out',11)).value.attempted,true);
await h.result.clear();h.flushTimers();await settle();assert.equal(await h.store.load('dev/user','out',11),null);h.destroy();
});
test('uncertain draft requires recovery and keeps the original request key',async()=>{
let restored;const saved={quantity:'5',attempted:true,key:'pending-key'},h=harness({scope:'dev/user',kind:'out',id:15,value:{quantity:'',attempted:false,key:'new-key'},onRestore:v=>{restored=v;},isPending:v=>v.attempted});
await h.store.save('dev/user','out',15,saved);h.render();await settle();h.render();assert.equal(h.result.ready,false);
assert.equal(h.prompt[2].length,1);assert.equal(h.prompt[2][0].text,'恢复并核对');
h.prompt[2][0].onPress();h.value=restored;h.render();assert.equal(h.result.ready,true);assert.equal(restored.key,'pending-key');h.destroy();
});
test('unsubmitted draft can be discarded without restoring business values',async()=>{
let restored=false;const h=harness({scope:'dev/user',kind:'move',id:2,value:{quantity:''},onRestore(){restored=true;}});
await h.store.save('dev/user','move',2,{quantity:'3'});h.render();await settle();h.render();
assert.equal(h.prompt[2][0].text,'丢弃草稿');h.prompt[2][0].onPress();await settle();h.render();assert.equal(h.result.ready,true);assert.equal(restored,false);assert.equal(await h.store.load('dev/user','move',2),null);h.destroy();
});
test('large batch can suspend debounce writes while explicit frozen requests remain durable',async()=>{
const initial={rows:[{key:'original',status:'editing'}]},h=harness({scope:'dev/user',kind:'batch',id:'active',value:initial,onRestore(){}});
h.render();await settle();h.render();h.suspendAutosave=true;h.render();h.flushTimers();await settle();assert.equal(await h.store.load('dev/user','batch','active'),null);
const frozen={rows:[{key:'original',status:'pending'}]};await h.result.saveNow(frozen);h.value=frozen;h.render();
h.value={rows:[{key:'original',status:'success'}]};h.render();h.flushTimers();await settle();assert.equal((await h.store.load('dev/user','batch','active')).value.rows[0].status,'pending');
h.suspendAutosave=false;h.render();h.flushTimers();await settle();assert.equal((await h.store.load('dev/user','batch','active')).value.rows[0].status,'success');await h.result.clear();h.destroy();
});

View File

@ -0,0 +1,42 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createDraftStore,draftKey} from '../src/core/drafts.ts';
import {calendarDate,calendarDays,dateParts} from '../src/core/calendar.ts';
function memory(){const data=new Map();return {data,get:async k=>data.get(k)??null,set:async(k,v)=>{data.set(k,v);},remove:async k=>{data.delete(k);}};}
test('drafts isolate accounts, environments and business ids and preserve unknown submit keys',async()=>{
const storage=memory(),store=createDraftStore(storage),value={quantity:'4',attempted:true,key:'original-idempotency-key',payload:{quantity:4}};
await store.save('http://dev|user-7','use',21,value);
assert.deepEqual((await store.load('http://dev|user-7','use',21)).value,value);
for(const [scope,kind,id] of [['http://prod|user-7','use',21],['http://dev|user-8','use',21],['http://dev|user-7','move',21],['http://dev|user-7','use',22]])assert.equal(await store.load(scope,kind,id),null);
assert.notEqual(draftKey('a|b','c','d'),draftKey('a','b|c','d'));
});
test('chunked drafts preserve emoji and Chinese text without exceeding secure item limits',async()=>{
const storage=memory(),store=createDraftStore(storage),value={remark:'资料📷'.repeat(2500),photos:[{id:'photo-id',name:'收货现场.jpg'}]};
await store.save('dev/user','arrival','11',value);
assert.deepEqual((await store.load('dev/user','arrival','11')).value,value);
assert.ok([...storage.data.values()].every(value=>Buffer.byteLength(value,'utf8')<2000));
await store.clear('dev/user','arrival','11');assert.equal(storage.data.size,0);
});
test('failed storage commit retains previous pending payload and clears partial chunks',async()=>{
const storage=memory(),store=createDraftStore(storage);await store.save('dev/1','use',4,{key:'original',attempted:true});
const old=new Map(storage.data),set=storage.set;let writes=0;storage.set=async(k,v)=>{if(++writes===2)throw Error('disk full');await set(k,v);};
await assert.rejects(store.save('dev/1','use',4,{key:'replacement',remark:'x'.repeat(2000)}),/disk full/);
assert.deepEqual(storage.data,old);assert.equal((await store.load('dev/1','use',4)).value.key,'original');
});
test('queued saves followed by clear cannot revive a completed business draft',async()=>{
const storage=memory(),store=createDraftStore(storage);
await Promise.all([store.save('dev/2','receive',9,{attempted:false}),store.save('dev/2','receive',9,{attempted:true,key:'stable'}),store.clear('dev/2','receive',9)]);
assert.equal(await store.load('dev/2','receive',9),null);assert.equal(storage.data.size,0);
});
test('corrupted pending drafts fail closed and credentials cannot enter persistent storage',async()=>{
const storage=memory(),store=createDraftStore(storage),key=draftKey('dev/1','move',1);
storage.data.set(key,'invalid');await assert.rejects(store.load('dev/1','move',1),/草稿索引异常/);
await assert.rejects(store.save('dev/1','move',1,{payload:{Authorization:'Bearer secret'}}),/登录凭据/);
assert.equal(storage.data.size,1);
});
test('calendar starts on Monday, includes leap day and crosses month/year correctly',()=>{
const feb=calendarDays(2024,1);assert.equal(feb[0],null);assert.equal(feb[3],'2024-02-01');assert.equal(feb.filter(Boolean).length,29);assert.ok(feb.includes('2024-02-29'));
assert.equal(calendarDays(2025,1).filter(Boolean).length,28);
assert.equal(calendarDate(2026,11,31),'2026-12-31');assert.deepEqual(dateParts('2026-12-31'),{year:2026,month:11,day:31});
for(const invalid of ['2025-02-29','2026-13-01','2026-04-31','2026-1-1','oops'])assert.equal(dateParts(invalid),null);
});

View File

@ -0,0 +1,24 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {draftReviewEntries,incompleteRecipientReview,reviewComplete} from '../src/core/draft-review.ts';
import {workspaceTasks,shortcutOrder} from '../src/core/workspace-tasks.ts';
import {modules} from '../src/core/modules.ts';
test('long mobile drafts retain every nested change and require every review page',()=>{
const prices=Array.from({length:54},(_,id)=>({id}));const draft={rows:[{_referencePricePreview:prices,_quotePreview:[{name:'末尾报价'}]},{_historyPreview:{name:'末尾历史'}}]};
const entries=draftReviewEntries(draft);assert.equal(entries.filter(e=>e.kind==='reference').length,54);assert.equal(entries.at(-1).value.name,'末尾历史');
const pages=Math.ceil(entries.length/20);assert.equal(reviewComplete(pages,[0,2]),false);assert.equal(reviewComplete(pages,[0,1,2]),true);assert.equal(reviewComplete(0,[]),false);
});
test('large broadcasts cannot execute against a partial recipient preview',()=>{
const row={_notificationPreview:{recipientCount:50,recipients:Array.from({length:20},(_,id)=>({id}))}};
assert.equal(incompleteRecipientReview({action:'notification.send',rows:[row]}),true);
row._notificationPreview.recipients=Array.from({length:50},(_,id)=>({id}));assert.equal(incompleteRecipientReview({action:'notification.send',rows:[row]}),false);
assert.equal(draftReviewEntries({rows:[row]}).filter(e=>e.kind==='recipient').length,50);
});
test('workspace tasks count only allowed modules using list-compatible server filters',()=>{
assert.deepEqual(workspaceTasks(modules.filter(m=>m.key==='stock')),[]);
const tasks=workspaceTasks(modules);assert.equal(tasks.length,4);assert.deepEqual(tasks.find(t=>t.id==='accept').query,{pendingAcceptance:true,priceLocked:true});
assert.deepEqual(tasks.find(t=>t.id==='check').openQuery,{checkStatus:0});assert.equal(tasks.find(t=>t.id==='pending').query.inStatus,0);
});
test('personal shortcuts cannot restore forbidden entries and preserve user order',()=>{
const permitted=modules.filter(m=>['stock','use'].includes(m.key));assert.deepEqual(shortcutOrder(['use','arrival','stock','use',null],permitted),['use','stock']);assert.deepEqual(shortcutOrder([],permitted),[]);
});

View File

@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {uploadManagedFile} from '../src/core/managed-transfer.ts';
import {ApiClient} from '../src/core/network.ts';
import {noticeBlocks,safeNoticeUrl} from '../src/core/notice-content.ts';
import {createMessageCenter} from '../src/core/message-center.ts';
test('notice rendering preserves ordered/bullet lists and excludes executable elements and unsafe URLs',()=>{
const html='<p>标题<strong>加粗</strong></p><ol><li data-list="ordered"><span class="ql-ui"></span>第一项</li><li data-list="bullet">小点</li><li data-list="ordered">重新编号</li></ol><ul><li><p>带段落</p></li></ul><script>bad()</script><img src="javascript:bad()">';
const rows=noticeBlocks(html);assert.deepEqual(rows.filter(r=>r.prefix).map(r=>r.prefix),['1.','•','1.','•']);assert.ok(rows[0].parts.some(p=>p.bold));assert.ok(!JSON.stringify(rows).includes('bad()"}'));assert.equal(safeNoticeUrl('javascript:alert(1)','http://127.0.0.1:8080'),null);assert.equal(safeNoticeUrl('https://user:pass@example.com','http://127.0.0.1'),null);assert.equal(safeNoticeUrl('/profile/a.png','http://127.0.0.1:8080'),'http://127.0.0.1:8080/profile/a.png');
});
test('history announcement pagination carries query, keeps attachments and never marks read automatically',async()=>{
const calls=[];let page=0;const center=createMessageCenter({request:async(p,o)=>{calls.push([p,o]);return p==='/system/notice/published'?{data:++page===1?{items:[{noticeId:9}],hasMore:true,nextCursor:9}:{items:[{noticeId:8}],hasMore:false,nextCursor:8}}:{data:{noticeContent:'<ol><li>A</li></ol>',attachments:[{id:'file'}]}};}},()=>{});
await center.tab('notices');await center.load(true);assert.equal(calls[1][1].query.beforeId,'9');assert.equal(center.snapshot().notices.length,2);await center.detail({noticeId:9});assert.equal(center.snapshot().detail.attachments[0].id,'file');assert.match(center.snapshot().detail.html,/<ol>/);assert.ok(calls.every(([,o])=>!o?.method));
});
test('resumable upload bounds reads to 1MB and skips acknowledged chunks, then revalidates completion',async()=>{
const bytes=Buffer.alloc(2*1024**2+17,42),calls=[],reads=[],progress=[];let closed=false;
const api={captureSession:()=>1,isSessionCurrent:()=>true,request:async(path,o)=>{calls.push([path,o]);if(path==='/common/file-transfers'){assert.equal(o.body.sha256,createHash('sha256').update(bytes).digest('hex'));return {data:{id:'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',size:bytes.length,chunkSize:1024**2,totalChunks:3,uploaded:[0]}};}return path.endsWith('/complete')?{data:{complete:true,result:{id:'saved'}}}:{code:200};}};
const saved=await uploadManagedFile(api,{name:'large.apk',size:bytes.length,read:async(start,n)=>{reads.push(n);return bytes.subarray(start,start+n);},close:()=>{closed=true;}},new AbortController().signal,p=>progress.push(p));
assert.equal(saved.id,'saved');assert.ok(closed);assert.ok(reads.every(n=>n<=1024**2));assert.equal(calls.filter(([p])=>p.includes('/chunks/')).length,2);assert.ok(calls.at(-1)[0].endsWith('/complete'));assert.equal(progress.at(-1).percent,100);
});
test('upload cancellation and account changes do not complete a transfer',async()=>{
let closed=false;const ctl=new AbortController();const api={captureSession:()=>1,isSessionCurrent:()=>false,request:()=>{throw Error('must not send');}};await assert.rejects(uploadManagedFile(api,{name:'x',size:1,read:async()=>new Uint8Array([1]),close:()=>closed=true},ctl.signal,()=>{}),/账号/);assert.ok(closed);
});
test('download streams to sink, rejects JSON errors, limits and session changes',async()=>{
const make=(headers,body)=>new Response(body,{status:200,headers}),out=[];
const api=new ApiClient('http://127.0.0.1:8080',()=>{},async(_url,o)=>{assert.equal(o.redirect,'error');assert.equal(o.headers.Authorization,'Bearer fake');return make({'Content-Length':'4','Content-Type':'application/octet-stream'},new Uint8Array([1,2,3,4]));});api.authenticate('fake');assert.equal(await api.download('/system/files/id/content',async b=>out.push(...b)),4);assert.deepEqual(out,[1,2,3,4]);
await assert.rejects(api.download('/system/files/id/content',async()=>{}, {maxBytes:2}),/大小限制/);
const denied=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>make({'Content-Type':'application/json'},'{"code":403}'));await assert.rejects(denied.download('/system/files/id/content',async()=>{throw Error('must not write');}),/权限/);
const stale=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>{stale.clear();return make({'Content-Type':'application/octet-stream'},'abc');});await assert.rejects(stale.download('/system/files/id/content',async()=>{}),/账号/);
});

View File

@ -0,0 +1,21 @@
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),ts=require('typescript');
function setup(){
const writes=[],removed=[],previews=[];
class File{constructor(root,name){this.uri=name?`${root.uri}/${name}`:root;this.size=3*1024**2;this.exists=true;}open(){return {offset:0,readBytes:async n=>new Uint8Array(n),writeBytes:async b=>writes.push(b.length),close(){}};}write(b){writes.push(b.length);}delete(){removed.push(this.uri);}create(){}async canPreview(){return true;}async preview(){previews.push(this.uri);}}
class Directory{constructor(root,name){this.uri=root.uri+'/'+name;}create(){}}
const exports={},code=ts.transpileModule(readFileSync(new URL('../src/managed-files.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
vm.runInNewContext(code,{exports,require:n=>({'react-native':{Platform:{OS:'android'}},'expo-document-picker':{getDocumentAsync:async()=>({canceled:false,assets:[{uri:'file:///cache/picked.apk',name:'picked.apk'}]})},'expo-file-system':{File,Directory,FileMode:{ReadOnly:'r',WriteOnly:'w'},Paths:{cache:{uri:'file:///cache'}}},'expo-sharing':{isAvailableAsync:async()=>true,shareAsync:async()=>{}},'expo/fetch':{fetch:async()=>{}}}[n]||{})});return {api:exports,writes,removed,previews};
}
test('Android upload reads requested chunks through FileHandle and uses local URI multipart parts',async()=>{
const {api,writes,removed}=setup(),source=await api.pickManagedFile();assert.equal(source.size,3*1024**2);assert.equal((await source.read(1024**2,1024**2)).length,1024**2);const part=await source.part(new Uint8Array(1024));assert.equal(part.type,'application/octet-stream');assert.match(part.uri,/^file:\/\/\/cache\/upload-chunk-/);assert.deepEqual(writes,[1024]);source.close();assert.ok(removed.some(p=>p.endsWith('/picked.apk')));
});
test('Android downloads write streamed chunks directly to disk and only preview after successful completion',async()=>{
const {api,writes,removed,previews}=setup(),signal=new AbortController().signal;
await api.downloadManagedFile({download:async(_p,sink)=>{await sink(new Uint8Array(1024));await sink(new Uint8Array(512));}}, {id:'file',name:'a.pdf'},signal,()=>{},'open');assert.deepEqual(writes,[1024,512]);assert.equal(previews.length,1);assert.equal(removed.length,0);
await assert.rejects(api.downloadManagedFile({download:async()=>{throw Error('offline');}}, {id:'file',name:'a.pdf'},signal,()=>{},'open'),/offline/);assert.equal(previews.length,1);assert.equal(removed.length,1);
});

View File

@ -0,0 +1,41 @@
import test from 'node:test';import assert from 'node:assert/strict';import {createHash} from 'node:crypto';
import {newerPackage,packageVerifier,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`};
test('uses installed version and environment, rejects arbitrary download paths and oversized files',()=>{
assert.equal(newerPackage(release,3,'dev'),release);assert.equal(newerPackage(release,4,'dev'),null);assert.equal(newerPackage(release,3,'prod'),null);assert.equal(newerPackage(release,0,'dev'),null);
assert.throws(()=>newerPackage({...release,downloadPath:'https://evil.example/apk'},3,'dev'),/无效/);assert.throws(()=>newerPackage({...release,size:251*1024**2},3,'dev'),/无效/);
});
test('only the complete byte-for-byte matching package is accepted',()=>{
let v=packageVerifier(release);v.write(bytes.subarray(0,5));v.write(bytes.subarray(5));assert.doesNotThrow(()=>v.finish());
v=packageVerifier(release);v.write(bytes.subarray(0,5));assert.throws(()=>v.finish(),/校验/);
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('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),/无法验证/);
await assert.rejects(verifyInstalledPackage({verify:async()=>{throw Error('signature mismatch')}},'file:///cache/one.apk',4),/signature mismatch/);
await assert.rejects(verifyInstalledPackage({verify:async()=>true},'https://elsewhere/one.apk',4),/无法验证/);
let argumentsSeen;await verifyInstalledPackage({verify:async(...args)=>{argumentsSeen=args;return true}},'file:///cache/one.apk',4);assert.deepEqual(argumentsSeen,['file:///cache/one.apk',4]);
});
test('package downloads stay on authenticated API and reject unsafe paths and changed accounts',async()=>{
let written='';const api=new ApiClient('http://127.0.0.1:8080',()=>{},async(_url,o)=>{assert.equal(o.headers.Authorization,'Bearer token');assert.equal(o.redirect,'error');return new Response(bytes,{headers:{'Content-Length':String(bytes.length),'Content-Type':'application/vnd.android.package-archive'}})});api.authenticate('token');
assert.equal(await api.download(release.downloadPath,async b=>written+=Buffer.from(b).toString()),bytes.length);assert.equal(written,bytes.toString());
await assert.rejects(api.download('/system/mobile-release/../other/content',async()=>{}),/无效/);
const stale=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>{stale.clear();return new Response(bytes)});stale.authenticate('one');await assert.rejects(stale.download(release.downloadPath,async()=>{}),/账号/);
});
test('switching account while checking does not lose the new check or show the old result',async()=>{
const require=createRequire(import.meta.url),ts=require('typescript'),slots=[],effects=[],pending=[];let cursor=0,scope='user-one',result;
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 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});
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);
pending[1]({data:{...release,versionCode:5}});await new Promise(r=>setImmediate(r));render();assert.equal(result.release.versionCode,5);assert.equal(result.visible,true);
});

View File

@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {available,validateOperation,operationPayload,runOperations} from '../src/core/stock-operations.ts';
const form={date:'2026-10-28',remark:'现场测试',project:{id:2}};
const source={id:1,projectId:1,productId:3,areaId:4,stockNum:10,inNum:10,receiptRoot:true,productName:'测试物品'};
const row=(patch={})=>({source:{...source},quantity:'4',area:{id:5},key:'stable-request',status:'editing',error:'',...patch});
test('quantities preserve 4 decimals and identify original invalid row',()=>{
assert.equal(validateOperation('use',[row({quantity:'0.0001'})],form),'');
for(const invalid of ['0','-1','1.00001','Infinity','1e1','11','abc'])assert.match(validateOperation('use',[row(),row({quantity:invalid})],form),/第 2 项/);
assert.match(validateOperation('use',[row(),row({quantity:'7'})],form),/合计数量超过/);
assert.match(validateOperation('use',[row()],{...form,date:'2026-02-30'}),/日期/);
assert.equal(validateOperation('use',[row({source:{...source,stockNum:0.3},quantity:'0.1'}),row({source:{...source,stockNum:0.3},quantity:'0.2'})],form),'');
});
test('movement, borrowing and historical receipt maintain business restrictions',()=>{
assert.match(validateOperation('move',[row({area:{id:4}})],form),/不能与来源相同/);
assert.match(validateOperation('borrow',[row()],{...form,project:{id:1}}),/不同的借入项目/);
assert.match(validateOperation('receive',[row({source:{...source,receiptRoot:false}})],form),/整单/);
assert.equal(validateOperation('check',[row({quantity:'0'})],form),'');
assert.match(validateOperation('check',[row({quantity:'0'})],{...form,remark:''}),/差异/);
});
test('return quantity is limited by both outstanding loan and current source stock',()=>{
const loan={id:5,active:true,outstandingQuantity:8};const stock={id:99,stockNum:5,areaId:6};
assert.equal(available('return',row({source:loan,stock})),5);
assert.match(validateOperation('return',[row({source:loan,stock,quantity:'6'})],form),/超过未还数量或取料库存/);
assert.match(validateOperation('return',[row({source:loan,stock,quantity:'5'}),row({source:loan,stock:{...stock,id:100},quantity:'4'})],form),/合计归还数量超过/);
assert.equal(validateOperation('return',[row({source:loan,stock,quantity:'5'}),row({source:loan,stock:{...stock,id:100},quantity:'3'})],form),'');
});
test('requests retain all warehouse and project identifiers',()=>{
assert.deepEqual(operationPayload('move',row(),form)[0].body,{quantity:4,key:'stable-request',date:form.date,remark:form.remark,projectId:1,itemId:3,fromAreaId:4,toAreaId:5});
assert.equal(operationPayload('use',row(),form)[0].body.outNo,'MOUT-stable-request');
assert.equal(operationPayload('borrow',row(),form)[0].body.borrowerProjectId,2);
assert.equal(operationPayload('receive',row(),form)[0].path,'/warehouse/in/receive/1');
const returned=operationPayload('return',row({stock:{areaId:9}}),form)[0];assert.equal(returned.path,'/project/loans/1/return');assert.equal(returned.body.fromAreaId,9);
});
test('partial failure retries only unsuccessful rows using exactly the original payload',async()=>{
const rows=[row(),row({source:{...source,id:2},key:'second'})],calls=[],saved=[];
const first=await runOperations('use',rows,form,async(path,options)=>{calls.push(options.body);if(options.body.id===2)throw new Error('response lost');},async next=>saved.push(JSON.parse(JSON.stringify(next))));
assert.equal(first[0].status,'success');assert.equal(first[1].status,'failed');assert.ok(saved.some(s=>s[1].status==='pending'));
const second=await runOperations('use',first,{...form,date:'2027-01-01'},async(path,options)=>calls.push(options.body),async()=>{});
assert.equal(calls.length,3);assert.deepEqual(calls[1],calls[2]);assert.ok(second.every(r=>r.status==='success'));
});
test('persisting request identity must succeed before any write',async()=>{
let writes=0;await assert.rejects(runOperations('move',[row()],form,async()=>writes++,async()=>{throw new Error('disk full');}),/disk full/);assert.equal(writes,0);
});
test('100 idempotent rows need only initial and final durable snapshots, not 200 rewrites',async()=>{
const rows=Array.from({length:100},(_,i)=>row({source:{...source,id:i+1},key:'batch-'+i}));let writes=0,durable=0;
await runOperations('use',rows,form,async()=>writes++,async(next,persist)=>{if(persist)durable++;});assert.equal(writes,100);assert.equal(durable,2);
});
test('uncertain stock-count requests are never automatically retried',async()=>{
let writes=0;const first=await runOperations('check',[row()],form,async()=>{writes++;throw new Error('timeout');},async()=>{});
assert.equal(first[0].status,'uncertain');await runOperations('check',first,form,async()=>writes++,async()=>{});assert.equal(writes,1);
// A crash can leave a persisted pending record; this is also not retryable.
await runOperations('check',[{...first[0],status:'pending'}],form,async()=>writes++,async()=>{});assert.equal(writes,1);
});
test('legacy receipt partial transition does not repeat confirmation after lost response',async()=>{
const calls=[];const first=await runOperations('receive',[row({quantity:'10',source:{...source,receiptRoot:false}})],form,async path=>{calls.push(path);if(path.includes('confirm'))throw new Error('timeout');},async()=>{});
assert.deepEqual(calls,['/warehouse/in','/warehouse/in/confirm/1']);assert.equal(first[0].status,'uncertain');
await runOperations('receive',first,form,async path=>calls.push(path),async()=>{});assert.equal(calls.length,2);
});

View File

@ -0,0 +1,12 @@
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 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',()=>{
assert.equal(render({visible:false}).tree,null);const r=render();assert.deepEqual(r.called,[]);assert.equal(r.tree.type,'Modal');const buttons=r.nodes.filter(n=>n.type==='Button');assert.deepEqual(buttons.map(n=>n.props.title),['重启并更新','稍后再说']);buttons[1].props.onPress();buttons[0].props.onPress();assert.deepEqual(r.called,['later','restart']);assert(r.nodes.some(n=>n.type==='Note'&&String(n.props.children).includes('未提交的内容不会保留')));
});
test('reload progress disables postponing; failure stays visible with retry instructions',()=>{
const busy=render({restarting:true});assert.equal(busy.nodes.find(n=>n.type==='Button'&&n.props.title==='稍后再说').props.disabled,true);assert.equal(busy.nodes.find(n=>n.type==='Button'&&n.props.title==='正在重启…').props.busy,true);
const failed=render({error:'请重试'});assert(failed.nodes.some(n=>n.type==='Text'&&n.props.children==='请重试'));assert.equal(failed.tree.props.onRequestClose instanceof Function,true);
});

View File

@ -0,0 +1,36 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {createRequire} from 'node:module';
import vm from 'node:vm';
import {ApiClient} from '../src/core/network.ts';
import {readableMultipart} from '../src/core/upload-file.ts';
const require=createRequire(import.meta.url),ts=require('typescript');
function compile(text,imports={}){const module={exports:{}};vm.runInNewContext(ts.transpileModule(text,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{module,exports:module.exports,require:name=>imports[name],Blob,FileReader:undefined,TextEncoder,Uint8Array,Math});return module.exports;}
// Exercise the installed SDK's serializer and FormData patch, including the branch
// that rejects React Native URI objects before the HTTP request is sent.
const {convertFormDataAsync}=compile(await readFile(new URL('../node_modules/expo/src/winter/fetch/convertFormData.ts',import.meta.url),'utf8'),{'../../utils/blobUtils':{blobToArrayBufferAsync:blob=>blob.arrayBuffer()}});
const {installFormDataPatch}=compile(await readFile(new URL('../node_modules/expo/src/winter/FormData.ts',import.meta.url),'utf8'));
class NativeFormData {constructor(){this._parts=[];}}
installFormDataPatch(NativeFormData);
const bytes=Uint8Array.from([137,80,78,71,13,10,26,10,1,2,3]);
async function native(run,{fail=false,hold=false}={}){const oldForm=globalThis.FormData,oldXhr=globalThis.XMLHttpRequest,reads=[];globalThis.FormData=NativeFormData;
class Reader {status=0;response=null;open(method,uri){reads.push({method,uri});}send(){if(hold)return;queueMicrotask(()=>{if(fail){this.onerror?.();return;}this.response=new Blob([bytes],{type:'application/octet-stream'});this.onload?.();});}abort(){this.onabort?.();}}
globalThis.XMLHttpRequest=Reader;try{return await run(reads);}finally{globalThis.FormData=oldForm;globalThis.XMLHttpRequest=oldXhr;}}
test('SDK regression: native URI parts fail, while prepared camera and album files serialize with their actual bytes',async()=>{
for(const uri of ['file:///cache/camera.jpg','content://media/picker/123'])await native(async reads=>{const body=new FormData();body.append('uploadId','same-upload-id');body.append('file',{uri,type:'image/jpeg',name:'arrival.jpg'});
await assert.rejects(convertFormDataAsync(body),/Unsupported FormDataPart/);
const ready=await readableMultipart(body,new AbortController().signal),serialized=await convertFormDataAsync(ready,'test-boundary'),text=new TextDecoder().decode(serialized.body);
assert.deepEqual(reads,[{method:'GET',uri}]);assert.match(text,/name="uploadId"\r\n\r\nsame-upload-id/);assert.match(text,/filename="arrival.jpg"/);assert.match(text,/image\/jpeg/);assert.notEqual(Buffer.from(serialized.body).indexOf(Buffer.from(bytes)),-1);assert.equal(body.get('file').uri,uri);
});
});
test('ApiClient sends the prepared file through the same authenticated transport without setting a multipart boundary manually',async()=>native(async()=>{
let calls=0;const api=new ApiClient('http://192.168.28.10/prod-api',()=>{},async(url,init)=>{calls++;assert.equal(init.headers.Authorization,'Bearer fake-test-token');assert.equal(init.headers['Content-Type'],undefined);assert.equal(init.redirect,'error');const {body}=await convertFormDataAsync(init.body);assert.notEqual(Buffer.from(body).indexOf(Buffer.from(bytes)),-1);return new Response(JSON.stringify({code:200,data:{id:'test-photo'}}));});api.authenticate('fake-test-token');
const body=new FormData();body.append('file',{uri:'file:///cache/photo.jpg',name:'photo.jpg',type:'image/jpeg'});const result=await api.request('/warehouse/purchase/arrival/photos/10',{method:'POST',body});assert.equal(result.data.id,'test-photo');assert.equal(calls,1);
}));
test('unreadable files and cancellation never reach the upload endpoint; external URI reads are rejected',async()=>{
await native(async()=>{let calls=0;const api=new ApiClient('http://192.168.28.10/prod-api',()=>{},async()=>{calls++;});const body=new FormData();body.append('file',{uri:'file:///missing.jpg'});await assert.rejects(api.request('/warehouse/purchase/arrival/photos/10',{method:'POST',body}),e=>e.code===400&&e.message.includes('本地附件'));assert.equal(calls,0);},{fail:true});
await native(async()=>{const body=new FormData();body.append('file',{uri:'file:///cache/photo.jpg'});const ctl=new AbortController(),pending=readableMultipart(body,ctl.signal);ctl.abort();await assert.rejects(pending,/取消/);},{hold:true});
await native(async reads=>{const body=new FormData();body.append('file',{uri:'https://example.com/private.jpg'});await assert.rejects(readableMultipart(body,new AbortController().signal),/地址无效/);assert.equal(reads.length,0);});
});
test('ordinary web Blob uploads are preserved without reading local URIs',async()=>{const body=new FormData();body.append('file',new Blob([bytes],{type:'image/png'}),'test.png');assert.equal(await readableMultipart(body,new AbortController().signal),body);});

View File

@ -0,0 +1,24 @@
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.ManagedFileService;
import java.nio.charset.StandardCharsets;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@RestController
@RequestMapping("/system/files")
public class ManagedFileController {
private final ManagedFileService files;
public ManagedFileController(ManagedFileService files){this.files=files;}
@GetMapping @PreAuthorize("@ss.hasAnyPermi('system:file:list,system:file:manage')")
public AjaxResult list(@RequestParam(defaultValue="")String keyword,@RequestParam(defaultValue="false")boolean mine,@RequestParam(defaultValue="1")int page,@RequestParam(defaultValue="20")int size){return AjaxResult.success(files.page(keyword,mine,page,size));}
@GetMapping("/{id}/content")
public ResponseEntity<StreamingResponseBody> download(@PathVariable String id){var file=files.open(id);return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(file.size()).cacheControl(CacheControl.noStore()).header("X-Content-Type-Options","nosniff").header("Content-Security-Policy","sandbox; default-src 'none'").header("Content-Disposition",ContentDisposition.attachment().filename(file.name(),StandardCharsets.UTF_8).build().toString()).body(output->{try(var in=file.input()){in.transferTo(output);}});}
@DeleteMapping("/{id}") @Log(title="删除文件",businessType=BusinessType.DELETE)
public AjaxResult remove(@PathVariable String id){files.remove(id);return AjaxResult.success();}
}

View File

@ -0,0 +1,18 @@
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.MobileReleaseService;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
@RestController @RequestMapping("/system/mobile-release")
public class MobileReleaseController {
private final MobileReleaseService releases;
public MobileReleaseController(MobileReleaseService releases){this.releases=releases;}
@GetMapping public AjaxResult latest(){return AjaxResult.success(releases.latest());}
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);}});}
}

View File

@ -17,7 +17,7 @@ public class AssistantQuotationContext {
@Autowired private PurchaseSheetService sheets;
@Autowired private IProjectInfoService projects;
public List<Map<String,Object>> targets(List<Map<String,Object>> messages) {
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
if(!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())
throw new ServiceException("价格更正请由采购管理员协助办理",403);
var codes=new LinkedHashSet<String>();var pattern=Pattern.compile("(?i)(?<![A-Za-z0-9])CG[0-9]{8,20}(?![A-Za-z0-9])");
// The latest explicit scope replaces previous batches, rather than silently combining old tasks.

View File

@ -60,8 +60,7 @@ public class AssistantReferencePriceService {
private boolean clearsQuote(Map<String,Object> input) { return Set.of("COPY_QUOTE_CLEAR_QUOTE","CLEAR_QUOTE").contains(Objects.toString(input.get("mode"),"")); }
private void correctionPermission(Map<String,Object> input) {
if("COPY_QUOTE".equals(input.get("mode")))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
if(clearsQuote(input)&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))
throw new ServiceException("清空报价涉及金额及成本更正,请采购管理员协助办理",403);
if(clearsQuote(input))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
}
private PurchasePriceCorrectionService.Correction correction(Map<String,Object> input,String version) {
return new PurchasePriceCorrectionService.Correction(null,

View File

@ -118,7 +118,7 @@ public class BusinessActionRegistry {
if(AssistantMessages.administratorOnly(action) && !supplementalAllowed(definition))
throw new ServiceException(AssistantMessages.forAction(action),403);
if(!supplementalAllowed(definition)) {
if(Set.of("purchase.lock","purchase.supplierExport").contains(action))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
if(Set.of("purchase.lock","purchase.confirm","purchase.supplierExport","batch.confirm","purchase.correctPrice","purchase.importQuote").contains(action))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
throw new ServiceException("当前账号暂无项目物资使用权限",403);
}
}
@ -141,7 +141,7 @@ public class BusinessActionRegistry {
}
private boolean supplementalAllowed(Action action) {
if(Set.of("purchase.lock","purchase.confirm","purchase.supplierExport","batch.confirm").contains(action.key()))return com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed();
if(Set.of("purchase.lock","purchase.confirm","purchase.supplierExport","batch.confirm","purchase.correctPrice","purchase.importQuote").contains(action.key()))return com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed();
if("role.dataScope".equals(action.key()))return com.ruoyi.common.utils.SecurityUtils.isAdmin();
if(!Set.of("material.issue","material.return","material.revoke","material.revokeReturn").contains(action.key()))return true;
Set<String> current=com.ruoyi.common.utils.SecurityUtils.getLoginUser().getPermissions();

View File

@ -0,0 +1,20 @@
package com.ruoyi.projectdev;
import com.ruoyi.common.utils.PersonNameOrder;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import static org.junit.jupiter.api.Assertions.*;
class PersonNameOrderTest {
@Test void pinyinPrecedesPaginationAndDuplicateNamesKeepStableIdentityOrder(){
var db=new PinyinJdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""));
db.execute("create table sys_user(user_id bigint,user_name varchar(64),nick_name varchar(64))");
db.execute("insert into sys_user values(9,'zhang','张三'),(8,'wang-b','王五'),(7,'wang-a','王五'),(6,'li','李四'),(5,'chen','陈六'),(4,'a','阿明')");
String sql="select u.user_id from sys_user u order by "+PersonNameOrder.sql("u")+" limit ? offset ?";
assertEquals(List.of(4L,5L,6L),db.queryForList(sql,3,0).stream().map(row->((Number)row.get("USER_ID")).longValue()).toList());
assertEquals(List.of(7L,8L,9L),db.queryForList(sql,3,3).stream().map(row->((Number)row.get("USER_ID")).longValue()).toList());
assertThrows(IllegalArgumentException.class,()->PersonNameOrder.sql("u;delete from sys_user"));
}
}

View File

@ -0,0 +1,12 @@
package com.ruoyi.projectdev;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/** H2 equivalent of the MySQL Chinese collation; production SQL is also checked against MySQL. */
public class PinyinJdbcTemplate extends JdbcTemplate {
public PinyinJdbcTemplate(DataSource source){super(source);execute("SET COLLATION CHINESE STRENGTH SECONDARY");}
@Override public List<Map<String,Object>> queryForList(String sql,Object... args){return super.queryForList(sql.replace(" collate utf8mb4_zh_0900_as_cs",""),args);}
}

View File

@ -0,0 +1,14 @@
package com.ruoyi.system;
import com.ruoyi.system.service.impl.ManagedFileService;
import com.ruoyi.web.controller.system.ManagedFileController;
import java.io.ByteArrayInputStream;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
class ManagedFileControllerTest {
@Test void arbitraryFilesAreAttachmentOnlyAndStreamsAreClosed()throws Exception{
var files=mock(ManagedFileService.class);byte[] bytes="<script>test</script>".getBytes();var stream=spy(new ByteArrayInputStream(bytes));when(files.open("one")).thenReturn(new ManagedFileService.Download("资料.html",bytes.length,stream));var mvc=MockMvcBuilders.standaloneSetup(new ManagedFileController(files)).build();var pending=mvc.perform(get("/system/files/one/content")).andExpect(request().asyncStarted()).andReturn();mvc.perform(asyncDispatch(pending)).andExpect(status().isOk()).andExpect(header().string("Content-Type","application/octet-stream")).andExpect(header().string("Content-Length",Integer.toString(bytes.length))).andExpect(header().string("X-Content-Type-Options","nosniff")).andExpect(header().string("Content-Security-Policy","sandbox; default-src 'none'")).andExpect(header().string("Content-Disposition",org.hamcrest.Matchers.startsWith("attachment;"))).andExpect(content().bytes(bytes));verify(stream).close();
}
}

View File

@ -0,0 +1,74 @@
package com.ruoyi.system;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.config.SecurityConfig;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.impl.ManagedFileService;
import com.ruoyi.system.service.impl.MobileReleaseService;
import com.ruoyi.web.controller.system.ManagedFileController;
import com.ruoyi.web.controller.system.MobileReleaseController;
import jakarta.servlet.Filter;
import java.io.ByteArrayInputStream;
import java.util.List;
import org.junit.jupiter.api.*;
import org.springframework.context.annotation.*;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
class ManagedFileSecurityTest {
AnnotationConfigWebApplicationContext context;MockMvc mvc;ManagedFileService files;
@Configuration @EnableWebSecurity @EnableWebMvc
static class Dependencies {
@Bean ManagedFileService files(){return mock(ManagedFileService.class);}
@Bean ManagedFileController controller(ManagedFileService files){return new ManagedFileController(files);}
@Bean MobileReleaseService mobileReleases(){return mock(MobileReleaseService.class);}
@Bean MobileReleaseController mobileController(MobileReleaseService service){return new MobileReleaseController(service);}
@Bean GlobalExceptionHandler errors(){return new GlobalExceptionHandler();}
@Bean TokenService tokens(){var token=mock(TokenService.class);var user=mock(LoginUser.class);when(user.getAuthorities()).thenReturn(List.of());when(token.getLoginUser(any())).thenAnswer(call->"Bearer audit-valid".equals(((jakarta.servlet.http.HttpServletRequest)call.getArgument(0)).getHeader("Authorization"))?user:null);return token;}
@Bean JwtAuthenticationTokenFilter jwt(){return new JwtAuthenticationTokenFilter();}
@Bean AuthenticationEntryPointImpl entry()throws Exception{var entry=mock(AuthenticationEntryPointImpl.class);doAnswer(call->{((jakarta.servlet.http.HttpServletResponse)call.getArgument(1)).setStatus(401);return null;}).when(entry).commence(any(),any(),any());return entry;}
@Bean LogoutSuccessHandlerImpl logout(){return mock(LogoutSuccessHandlerImpl.class);}
@Bean CorsFilter cors(){return new CorsFilter(new UrlBasedCorsConfigurationSource());}
@Bean PermitAllUrlProperties permits(){var permits=mock(PermitAllUrlProperties.class);when(permits.getUrls()).thenReturn(List.of());return permits;}
@Bean UserDetailsService users(){return new InMemoryUserDetailsManager(User.withUsername("isolated-test").password("{noop}unused").roles("USER").build());}
}
@BeforeEach void start(){context=new AnnotationConfigWebApplicationContext();context.setServletContext(new MockServletContext());context.getEnvironment().getPropertySources().addFirst(new org.springframework.core.env.MapPropertySource("isolated-token-properties",java.util.Map.of("token.header","Authorization","token.secret","isolated-test-secret","token.expireTime","30")));context.addBeanFactoryPostProcessor(factory->factory.registerSingleton("redisCache",mock(com.ruoyi.common.core.redis.RedisCache.class)));context.register(Dependencies.class,SecurityConfig.class);context.refresh();files=context.getBean(ManagedFileService.class);mvc=MockMvcBuilders.webAppContextSetup(context).addFilters(context.getBean("springSecurityFilterChain",Filter.class)).build();}
@AfterEach void stop(){SecurityContextHolder.clearContext();context.close();}
@Test void anonymousAndInvalidTokensCannotOpenAFile()throws Exception{
mvc.perform(get("/system/files/one/content")).andExpect(status().isUnauthorized());
mvc.perform(get("/system/files/one/content").header("Authorization","Bearer invalid")).andExpect(status().isUnauthorized());verifyNoInteractions(files);
}
@Test void anonymousCannotCheckOrDownloadMobileRelease()throws Exception{
mvc.perform(get("/system/mobile-release")).andExpect(status().isUnauthorized());
mvc.perform(get("/system/mobile-release/"+"0".repeat(64)+"/content")).andExpect(status().isUnauthorized());
mvc.perform(post("/system/mobile-release").contentType("application/json").content("{\"fileId\":\"x\"}")).andExpect(status().isUnauthorized());
verifyNoInteractions(context.getBean(MobileReleaseService.class));
}
@Test void authorizedDownloadCompletesItsAsyncDispatchWithoutReopeningTheFile()throws Exception{
byte[] bytes="authenticated download".getBytes();when(files.open("one")).thenAnswer(call->{Assertions.assertNotNull(SecurityContextHolder.getContext().getAuthentication());return new ManagedFileService.Download("one.txt",bytes.length,new ByteArrayInputStream(bytes));});
var pending=mvc.perform(get("/system/files/one/content").header("Authorization","Bearer audit-valid")).andExpect(request().asyncStarted()).andReturn();
SecurityContextHolder.clearContext();mvc.perform(asyncDispatch(pending)).andExpect(status().isOk()).andExpect(content().bytes(bytes));verify(files,times(1)).open("one");
}
@Test void businessAccessDenialStillRunsBeforeAsyncStreaming()throws Exception{
when(files.open("denied")).thenThrow(new ServiceException("无权访问该文件",403));mvc.perform(get("/system/files/denied/content").header("Authorization","Bearer audit-valid")).andExpect(request().asyncNotStarted()).andExpect(jsonPath("$.code").value(403));verify(files).open("denied");
}
}

View File

@ -0,0 +1,63 @@
package com.ruoyi.system;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.storage.BusinessFileStorage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.mapper.SysNoticeMapper;
import com.ruoyi.system.service.impl.ManagedFileService;
import com.ruoyi.system.service.impl.SysNoticeServiceImpl;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import org.junit.jupiter.api.*;
import org.mockito.MockedStatic;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.support.TransactionTemplate;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ManagedFileTest {
JdbcTemplate db;BusinessFileStorage storage;ManagedFileService files;TransactionTemplate tx;MockedStatic<SecurityUtils> security;Map<String,byte[]> objects;long actor=2;Set<String> grants;
static final String A="11111111-1111-4111-8111-111111111111",B="22222222-2222-4222-8222-222222222222";
@BeforeEach void setup()throws Exception{
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,'上传人'),(3,'同事')");
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)));
}
@AfterEach void close(){security.close();}
MockMultipartFile document(String name){return new MockMultipartFile("file",name,"application/octet-stream","isolated file bytes".getBytes());}
@Test void sharedFilesRequireDownloadAndOnlyUploaderWithDeleteAuthorityOrAdministratorMayRemove()throws Exception{
var file=files.upload(false,A,document("文件.zip"));assertEquals(A,file.id());assertEquals("上传人",file.uploadedBy());assertEquals(1L,files.page("文件",false,1,20).get("total"));
actor=3;assertEquals(1L,files.page("",false,1,20).get("total"));assertEquals(0L,files.page("",true,1,20).get("total"));try(var read=files.open(A).input()){assertArrayEquals("isolated file bytes".getBytes(),read.readAllBytes());}assertThrows(ServiceException.class,()->files.remove(A));
grants.remove("system:file:download");assertThrows(ServiceException.class,()->files.open(A));actor=1;files.remove(A);assertThrows(ServiceException.class,()->files.open(A));assertEquals(0L,files.page("",false,1,20).get("total"));
}
@Test void noticeDraftsCannotBeStolenAndPublishedAttachmentsAreReadableWithoutFileLibraryPermissions()throws Exception{
files.upload(true,A,document("说明.pdf"));assertTrue(files.alive(true,A));actor=3;assertThrows(ServiceException.class,()->files.open(A));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(A))));
actor=2;tx.executeWithoutResult(s->files.bindNotice(10,List.of(A)));assertFalse(files.alive(true,A));grants.clear();actor=3;assertEquals(1,files.noticeFiles(10).size());try(var in=files.open(A).input()){assertTrue(in.readAllBytes().length>0);}assertThrows(ServiceException.class,()->files.noticeFiles(20));
actor=2;grants.add("system:notice:edit");assertThrows(ServiceException.class,()->files.remove(A));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(20,List.of(A))));assertEquals(1,files.noticeFiles(10).size());
db.update("update sys_notice set status='1' where notice_id=10");actor=3;grants.clear();assertThrows(ServiceException.class,()->files.open(A));actor=2;grants.add("system:notice:edit");assertEquals(1,files.noticeFiles(10).size());
}
@Test void noticeUpdatesKeepExistingAttachmentsForOldClientsAndValidateBeforeReplacingAllLinks(){
files.upload(true,A,document("附件.txt"));tx.executeWithoutResult(s->files.bindNotice(10,List.of(A)));files.bindNotice(10,null);assertEquals(1,files.noticeFiles(10).size());
assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(B))));assertEquals(1,files.noticeFiles(10).size());
tx.executeWithoutResult(s->files.bindNotice(10,List.of()));assertEquals(0,files.noticeFiles(10).size());assertTrue(files.alive(true,A));files.remove(A);assertThrows(ServiceException.class,()->files.open(A));
}
@Test void invalidAttachmentRollsBackNewNoticeAndUploadMetadataFailureRollsBackNewObject(){
var mapper=mock(SysNoticeMapper.class);when(mapper.insertNotice(any())).thenAnswer(c->{SysNotice notice=c.getArgument(0);notice.setNoticeId(30L);db.update("insert into sys_notice values(30,'0')");return 1;});var notices=new SysNoticeServiceImpl();ReflectionTestUtils.setField(notices,"noticeMapper",mapper);ReflectionTestUtils.setField(notices,"files",files);var notice=new SysNotice();notice.setAttachmentIds(List.of(B));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->notices.insertNotice(notice)));assertEquals(0,db.queryForObject("select count(*) from sys_notice where notice_id=30",Integer.class));
assertThrows(IllegalStateException.class,()->tx.executeWithoutResult(s->{files.upload(false,A,document("test.txt"));throw new IllegalStateException("rollback");}));assertFalse(objects.containsKey("managed-file/"+A+".bin"));assertEquals(0,db.queryForObject("select count(*) from sys_managed_file",Integer.class));
}
@Test void uploadRetriesAreIdempotentAndFileNamesAreSafeWithoutRequiringAnExtension()throws Exception{
files.upload(false,A,document("LICENSE"));files.upload(false,A,document("LICENSE"));verify(storage,times(1)).saveStream(anyString(),any(),anyLong(),anyString());
assertThrows(ServiceException.class,()->files.upload(false,A,document("different.txt")));assertThrows(ServiceException.class,()->ManagedFileService.safeName("../secret"));assertThrows(ServiceException.class,()->ManagedFileService.safeName("a\r\nHeader.txt"));assertThrows(ServiceException.class,()->files.open("../"));
var large=mock(org.springframework.web.multipart.MultipartFile.class);when(large.isEmpty()).thenReturn(false);when(large.getSize()).thenReturn((long)ManagedFileService.MAX_BYTES+1);assertThrows(ServiceException.class,()->files.upload(false,B,large));
}
@Test void fileLibraryObjectCannotBeReclassifiedAsPublicNoticeEvidence(){files.upload(false,A,document("private.txt"));assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->files.bindNotice(10,List.of(A))));assertTrue(files.noticeFiles(10).isEmpty());}
}

View File

@ -0,0 +1,42 @@
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 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.DriverManagerDataSource;
import static org.junit.jupiter.api.Assertions.*;
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);}
@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);
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());
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{
Path apk=Path.of(System.getProperty("user.dir"));if(!Files.exists(apk.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk")))apk=apk.getParent();apk=apk.resolve(".codex-tmp/releases/cmvr-wms-prod-20261028-12dd6893.apk");Assumptions.assumeTrue(Files.isRegularFile(apk),"Optional real signed build fixture not present");var json=new ObjectMapper();var result=MobileReleaseService.inspect(apk,"prod",json,PROD);assertEquals(2L,result.get("v"));Path finalApk=apk;
assertThrows(Exception.class,()->MobileReleaseService.inspect(finalApk,"prod",json,"0".repeat(64)));
assertThrows(Exception.class,()->MobileReleaseService.inspect(finalApk,"dev",json,PROD));
Path tampered=Files.createTempFile("tampered-apk-",".apk");try{byte[] bytes=Files.readAllBytes(apk);bytes[bytes.length/3]^=1;Files.write(tampered,bytes);assertThrows(Exception.class,()->MobileReleaseService.inspect(tampered,"prod",json,PROD));}finally{Files.deleteIfExists(tampered);}
}
}

View File

@ -0,0 +1,28 @@
package com.ruoyi.system;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.mapper.SysNoticeReadMapper;
import com.ruoyi.system.service.impl.SysNoticeReadServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class NoticeHistoryTest {
@Test void historyIsBoundedAndUsesLookaheadWithoutLosingCursor() {
var mapper=mock(SysNoticeReadMapper.class);var service=new SysNoticeReadServiceImpl();
ReflectionTestUtils.setField(service,"noticeReadMapper",mapper);
var rows=new ArrayList<SysNotice>();for(long i=100;i>=50;i--){var row=new SysNotice();row.setNoticeId(i);rows.add(row);}
when(mapper.selectPublishedPage(2L,110L,"公告",true,51)).thenReturn(rows);
var page=service.publishedPage(2L,110L," 公告 ",true,10000);
assertEquals(50,((java.util.List<?>)page.get("items")).size());assertEquals(true,page.get("hasMore"));assertEquals(51L,page.get("nextCursor"));
verify(mapper).selectPublishedPage(2L,110L,"公告",true,51);verifyNoMoreInteractions(mapper);
}
@Test void rejectsAnonymousAndInvalidCursorBeforeQuery() {
var mapper=mock(SysNoticeReadMapper.class);var service=new SysNoticeReadServiceImpl();ReflectionTestUtils.setField(service,"noticeReadMapper",mapper);
assertThrows(RuntimeException.class,()->service.publishedPage(null,null,"",false,20));
assertThrows(RuntimeException.class,()->service.publishedPage(2L,-1L,"",false,20));
assertThrows(RuntimeException.class,()->service.publishedPage(2L,null,"x".repeat(101),false,20));verifyNoInteractions(mapper);
}
}

View File

@ -1,11 +1,13 @@
package com.ruoyi.web.controller.warehouse;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.warehouse.domain.*;
import com.ruoyi.warehouse.service.*;
import com.ruoyi.warehouse.service.impl.PurchaseSheetService;
import com.ruoyi.warehouse.service.impl.PurchaseHistoryCorrectionService;
import com.ruoyi.warehouse.util.PurchaseQuoteAccess;
import org.junit.jupiter.api.*;
import org.springframework.mock.web.MockHttpServletResponse;
@ -33,6 +35,10 @@ class PurchaseQuoteAccessTest {
}
@AfterEach void cleanup(){SecurityContextHolder.clearContext();}
private void login(Long id,Set<String> permissions){var user=new SysUser();user.setUserId(id);user.setUserName("test");SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(id,1L,user,permissions),null));}
private void loginRole(Long id,Set<String> permissions,String roleKey,String status,String delFlag){
var user=new SysUser();user.setUserId(id);user.setUserName("test");var role=new SysRole();role.setRoleKey(roleKey);role.setStatus(status);role.setDelFlag(delFlag);user.setRoles(List.of(role));
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(new LoginUser(id,1L,user,permissions),null));
}
@Test void employeeViewsMaskAllQuoteAliasesWithoutMutatingCostingObjects(){
var result=PurchaseQuoteAccess.view(source);
@ -42,11 +48,21 @@ class PurchaseQuoteAccessTest {
source.setFinalUnitPrice(BigDecimal.ZERO);assertTrue(PurchaseQuoteAccess.view(source).getQuoteAvailable());
source.setFinalUnitPrice(null);assertFalse(PurchaseQuoteAccess.view(source).getQuoteAvailable());
}
@Test void onlyManagementPermissionOrSuperAdministratorRevealsQuotes(){
@Test void onlyActivePurchaseManagerRoleOrSuperAdministratorRevealsQuotes(){
assertFalse(PurchaseQuoteAccess.allowed());
login(10L,Set.of("warehouse:purchase:manage"));assertSame(source,PurchaseQuoteAccess.view(source));
login(10L,Set.of("warehouse:purchase:manage"));assertFalse(PurchaseQuoteAccess.allowed());
login(1L,Set.of());assertTrue(PurchaseQuoteAccess.allowed());
login(10L,Set.of("*:*:*"));assertTrue(PurchaseQuoteAccess.allowed());
login(10L,Set.of("*:*:*"));assertFalse(PurchaseQuoteAccess.allowed());
loginRole(10L,Set.of(),"admin","0","0");assertFalse(PurchaseQuoteAccess.allowed());
loginRole(10L,Set.of(),"purchase_*","0","0");assertFalse(PurchaseQuoteAccess.allowed());
loginRole(10L,Set.of(),"purchase_manager","1","0");assertFalse(PurchaseQuoteAccess.allowed());
loginRole(10L,Set.of(),"purchase_manager","0","2");assertFalse(PurchaseQuoteAccess.allowed());
loginRole(10L,Set.of(),"purchase_manager","0","0");assertSame(source,PurchaseQuoteAccess.view(source));
}
@Test void missingAuthenticationCannotAccessQuotes(){
SecurityContextHolder.clearContext();
assertFalse(PurchaseQuoteAccess.allowed());
assertThrows(ServiceException.class,PurchaseQuoteAccess::require);
}
@Test void employeeEditPreservesHiddenQuoteAndRejectsPriceTampering(){
var edit=new PurchaseRequest();edit.setId(1L);edit.setActualUnitPrice(new BigDecimal("7"));
@ -63,6 +79,15 @@ class PurchaseQuoteAccessTest {
var log=new PurchaseOperationLog();log.setOperationDetail("单价891.25");assertFalse(PurchaseQuoteAccess.view(log).getOperationDetail().contains("891.25"));
var snapshot=Map.<String,Object>of("finalUnitPrice",891.25,"actualUnitPrice",100,"_snapshot",Map.of("currentRecord",Map.of("estimatedAmount",1782.5,"id",1)));
var masked=PurchaseQuoteAccess.viewMap(snapshot);assertFalse(masked.containsKey("finalUnitPrice"));assertEquals(100,masked.get("actualUnitPrice"));assertFalse(masked.toString().contains("1782.5"));
var historical=Map.<String,Object>of("oldAmount",1782.5,"newAmount",2000,"oldActualAmount",200,"changes",List.of(Map.of("field","finalUnitPrice","before",891.25,"after",1000),Map.of("field","actualUnitPrice","before",100,"after",110)));
var historyView=PurchaseQuoteAccess.viewMap(historical);assertFalse(historyView.containsKey("oldAmount"));assertFalse(historyView.containsKey("newAmount"));assertEquals(200,historyView.get("oldActualAmount"));assertFalse(historyView.toString().contains("891.25"));assertTrue(historyView.toString().contains("actualUnitPrice"));
}
@Test void managementPermissionCannotChangeHistoricalQuoteWithoutRole(){
login(10L,Set.of("warehouse:purchase:manage"));
var service=new PurchaseHistoryCorrectionService();
var entry=new PurchaseHistoryCorrectionService.Entry(1L,Map.of("finalUnitPrice",10),null);
var command=new PurchaseHistoryCorrectionService.Command(null,"更正",List.of(entry),false);
assertThrows(ServiceException.class,()->service.preview(command));
}
@Test void httpDetailSheetListTotalsAndBatchResponsesApplyTheSamePolicy() throws Exception {
var controller=new PurchaseRequestController();var purchases=mock(IPurchaseRequestService.class);var sheets=mock(PurchaseSheetService.class);var batches=mock(IPurchaseBatchService.class);

View File

@ -12,6 +12,18 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class AssistantQuotationContextTest {
@Test void managePermissionWithoutPurchaseManagerRoleCannotReadQuotationContext() {
var context=new AssistantQuotationContext();var db=mock(JdbcTemplate.class);var sheets=mock(PurchaseSheetService.class);
ReflectionTestUtils.setField(context,"db",db);ReflectionTestUtils.setField(context,"sheets",sheets);
try(var security=mockStatic(SecurityUtils.class)) {
security.when(SecurityUtils::isAdmin).thenReturn(false);
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setRoles(List.of());
security.when(SecurityUtils::getLoginUser).thenReturn(new com.ruoyi.common.core.domain.model.LoginUser(10L,1L,user,Set.of("warehouse:purchase:manage")));
assertThrows(ServiceException.class,()->context.targets(List.of(Map.of("role","user","content","CG2026100001 按PDF更新价格"))));
verifyNoInteractions(db,sheets);
}
}
@Test void unknownExplicitBatchStopsBeforeAnyGlobalNameMatchingOrFileReading() {
var context=new AssistantQuotationContext();var db=mock(JdbcTemplate.class);var sheets=mock(PurchaseSheetService.class);
ReflectionTestUtils.setField(context,"db",db);ReflectionTestUtils.setField(context,"sheets",sheets);

View File

@ -108,8 +108,12 @@ class AssistantReferencePriceServiceTest {
}
@Test void purchaseEditAloneCannotClearOrReadCostPreviewButStillCanMaintainReferenceAmounts() {
security.when(SecurityUtils::isAdmin).thenReturn(false);security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
var user=new com.ruoyi.common.core.domain.entity.SysUser();user.setRoles(List.of());
security.when(SecurityUtils::getLoginUser).thenReturn(new com.ruoyi.common.core.domain.model.LoginUser(10L,1L,user,Set.of("warehouse:purchase:manage")));
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("CLEAR_QUOTE"))).getCode());verifyNoInteractions(corrections,sheets);
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("COPY_QUOTE"))).getCode());
assertEquals(403,assertThrows(ServiceException.class,()->service.preview(input("COPY_QUOTE_CLEAR_QUOTE"))).getCode());
var values=input("SET");values.put("actualUnitPrice",8);var rows=preview(values);assertEquals(3,rows.size());
assertEquals(new BigDecimal("8"),rows.get(0).get("newActualPrice"));
for(var row:rows)for(String field:List.of("quotePrice","newQuotePrice","oldQuoteAmount","newQuoteAmount"))assertFalse(row.containsKey(field));

View File

@ -0,0 +1,11 @@
package com.ruoyi.common.utils;
/** Database-side pinyin ordering, applied before paging and candidate limits. */
public final class PersonNameOrder {
private PersonNameOrder() {}
public static String sql(String alias) {
if (alias == null || !alias.matches("[A-Za-z_][A-Za-z0-9_]*|")) throw new IllegalArgumentException("Invalid user alias");
String p=alias.isEmpty()?"":alias+".";
return "lower(coalesce(nullif(trim("+p+"nick_name),''),"+p+"user_name)) collate utf8mb4_zh_0900_as_cs,"+p+"user_name,"+p+"user_id";
}
}

View File

@ -0,0 +1,3 @@
package com.ruoyi.system.domain;
public record ManagedFileInfo(String id,String name,long size,String uploadedBy,String uploadedAt,boolean canDownload,boolean canRemove) {}

View File

@ -0,0 +1,95 @@
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.security.MessageDigest;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;
/** Private file bytes; notice drafts stay owner-bound until their notice is saved. */
@Service
public class ManagedFileService {
public static final int MAX_BYTES=1024*1024*1024;
private final JdbcTemplate db;private final BusinessFileStorage storage;
public ManagedFileService(JdbcTemplate db,BusinessFileStorage storage){this.db=db;this.storage=storage;}
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 '!')";
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;
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);}
String key=key(id);boolean ours=false;
try{
if(storage.exists(key,null)){try(var in=storage.openStream(key)){if(!sha.equals(digest(in,file.getSize())))throw new ServiceException("文件校验标识冲突,请重新上传");}ours=true;}
else{ours=true;try(var in=file.getInputStream()){storage.saveStream(key,in,file.getSize(),"application/octet-stream");}}
if(TransactionSynchronizationManager.isSynchronizationActive())TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCompletion(int status){if(status!=STATUS_COMMITTED)storage.discardFailedUpload(key,null);}});
db.update("insert into sys_managed_file(id,file_kind,name,byte_size,sha256,owner_id,create_by) values(?,?,?,?,?,?,?)",id,kind,name,file.getSize(),sha,actor(),SecurityUtils.getUsername());
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 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();
}
@Transactional public void bindNotice(long notice,List<String> ids){
if(ids==null)return;require("system:notice:add","system:notice:edit");if(ids.size()>20||new HashSet<>(ids).size()!=ids.size())throw new ServiceException("每份公告最多20个不重复附件");ids.forEach(ManagedFileService::uuid);
if(db.queryForList("select notice_id from sys_notice where notice_id=? for update",notice).isEmpty())throw missing();
for(String id:ids.stream().sorted().toList()){
var rows=db.queryForList("select f.*,a.notice_id bound_notice from sys_managed_file f left join sys_notice_attachment a on a.file_id=f.id where f.id=? for update",id);if(rows.isEmpty())throw missing();var row=rows.get(0);
boolean same=row.get("bound_notice") instanceof Number n&&n.longValue()==notice;
if(!"NOTICE".equals(row.get("file_kind"))||number(row,"deleted")!=0||!same&&(row.get("bound_notice")!=null||number(row,"owner_id")!=actor()))throw new ServiceException("请选择本人上传且未被其他公告使用的附件");
}
db.update("delete from sys_notice_attachment where notice_id=?",notice);for(int i=0;i<ids.size();i++)db.update("insert into sys_notice_attachment(notice_id,file_id,sort_order) values(?,?,?)",notice,ids.get(i),i);
}
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");
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("已保存的公告附件请在公告编辑中移除");}
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);}});
else storage.discardFailedUpload(key(id),null);
}
@Scheduled(initialDelay=3600000,fixedDelay=3600000) public void cleanup(){
if(!storage.isEnabled())return;
try{var rows=db.queryForList("select f.id from sys_managed_file f where f.deleted=1 or (f.file_kind='NOTICE' and f.create_time<date_sub(current_timestamp,interval 7 day) and not exists(select 1 from sys_notice_attachment a where a.file_id=f.id)) order by f.create_time limit 50",String.class);
for(String id:rows){db.update("update sys_managed_file set deleted=1,delete_time=coalesce(delete_time,current_timestamp) where id=? and not exists(select 1 from sys_notice_attachment where file_id=?)",id,id);if(db.queryForObject("select count(*) from sys_managed_file where id=? and deleted=1",Long.class,id)==1){storage.discardFailedUpload(key(id),null);if(!storage.exists(key(id),null))db.update("delete from sys_managed_file where id=? and deleted=1 and not exists(select 1 from sys_notice_attachment where file_id=?)",id,id);}}
}catch(Exception error){org.slf4j.LoggerFactory.getLogger(getClass()).warn("Managed file cleanup will retry");}
}
public static String safeName(String name){if(name==null||name.isBlank()||name.length()>180||name.matches("(?s).*[\\p{Cntrl}/\\\\].*")||name.equals(".")||name.equals("..")||name.endsWith("."))throw new ServiceException("文件名称无效或超过180个字符");return name;}
private static String digest(InputStream input,long expected)throws Exception{var digest=MessageDigest.getInstance("SHA-256");byte[] bytes=new byte[65536];long size=0;for(int n;(n=input.read(bytes))!=-1;){size+=n;if(size>MAX_BYTES)throw new IOException();digest.update(bytes,0,n);}if(size!=expected)throw new IOException();return HexFormat.of().formatHex(digest.digest());}
private void readableNotice(long id){var rows=db.queryForList("select status from sys_notice where notice_id=?",String.class,id);if(rows.isEmpty()||!"0".equals(rows.get(0))&&!has("system:notice:list","system:notice:query","system:notice:edit"))throw missing();actor();}
private ManagedFileInfo info(Map<String,Object> row){boolean library="LIBRARY".equals(row.get("file_kind"));return new ManagedFileInfo(row.get("id").toString(),row.get("name").toString(),number(row,"byte_size"),Objects.toString(row.get("uploaded_by"),Objects.toString(row.get("create_by"),"")),Objects.toString(row.get("create_time"),""),!library||has("system:file:download","system:file:manage"),library&&(has("system:file:manage")||number(row,"owner_id")==actor()&&has("system:file:remove")));}
private static String select(){return "select f.*,coalesce(nullif(u.nick_name,''),f.create_by) uploaded_by from sys_managed_file f left join sys_user u on u.user_id=f.owner_id";}
private static String key(String id){return "managed-file/"+id+".bin";}
private static long number(Map<String,Object> row,String key){return ((Number)row.get(key)).longValue();}
private static long actor(){return SecurityUtils.getUserId();}
private static boolean has(String... permissions){return SecurityUtils.isAdmin()||Arrays.stream(permissions).anyMatch(SecurityUtils::hasPermi);}
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();}
}

View File

@ -0,0 +1,75 @@
package com.ruoyi.system.service.impl;
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.android.apksig.ApkVerifier;
import com.android.apksig.internal.apk.AndroidBinXmlParser;
import java.io.*;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;
import java.util.zip.ZipFile;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** An environment-bound immutable APK in private object storage; only user 1 can publish. */
@Service
public class MobileReleaseService {
private static final long MAX=250L*1024*1024;
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);}
@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(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;
try{
temp=Files.createTempFile("cmvr-apk-",".apk");var digest=MessageDigest.getInstance("SHA-256");long received=0;
try(var in=storage.openStream("managed-file/"+id+".bin");var out=Files.newOutputStream(temp)){byte[] bytes=new byte[65536];for(int n;(n=in.read(bytes))!=-1;){received+=n;if(received>size||received>MAX)throw new IOException();digest.update(bytes,0,n);out.write(bytes,0,n);}}
if(received!=size||!hash.equals(HexFormat.of().formatHex(digest.digest())))throw new ServiceException("安装包文件校验失败,请重新上传");
var parsed=inspect(temp,environment,json,signer);var prior=stored(true);long version=((Number)parsed.get("v")).longValue();
if(!prior.isEmpty()&&version<=number(prior,"v")){if(version==number(prior,"v")&&hash.equals(prior.get("h")))return view(prior);throw new ServiceException("新版安装版本号必须高于已发布版本;请重新打包,不要只修改文件名");}
var value=new LinkedHashMap<String,Object>(parsed);value.put("h",hash);value.put("s",size);value.put("note",notes);
String encoded=json.writeValueAsString(value);if(encoded.length()>500)throw new ServiceException("版本说明过长");
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);
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 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");}
private String object(Map<String,Object> v){return "managed-file/app-"+environment+"-"+number(v,"v")+"-"+v.get("h")+".apk";}
private static long number(Map<String,Object> value,String k){return ((Number)value.get(k)).longValue();}
private static void admin(){if(!SecurityUtils.isAdmin())throw new ServiceException("仅超级管理员可以发布App安装包",403);}
public static Map<String,Object> inspect(Path path,String environment,ObjectMapper json,String expectedSigner)throws Exception{
if(!Set.of("dev","prod").contains(environment)||expectedSigner==null||!expectedSigner.matches("[a-f0-9]{64}"))throw new ServiceException("安装包签名校验配置无效");
var verified=new ApkVerifier.Builder(path.toFile()).build().verify();
if(!verified.isVerified()||verified.getSignerCertificates().size()!=1||!expectedSigner.equals(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(verified.getSignerCertificates().get(0).getEncoded()))))throw new ServiceException("安装包签名不匹配,请使用本系统的正式签名或开发签名打包");
try(var zip=new ZipFile(path.toFile())){
if(zip.getEntry("AndroidManifest.xml")==null||zip.getEntry("classes.dex")==null)throw new ServiceException("文件不是有效的Android安装包");
var entry=zip.getEntry("assets/app.config");var runtime=zip.getEntry("assets/fingerprint");if(entry==null||runtime==null)throw new ServiceException("仅支持本系统打包的安装包");
byte[] config;String fingerprint;
try(var in=zip.getInputStream(entry)){config=in.readNBytes(32769);}try(var in=zip.getInputStream(runtime)){fingerprint=new String(in.readNBytes(201),java.nio.charset.StandardCharsets.UTF_8).trim();}
if(config.length>32768||!fingerprint.matches("[a-f0-9]{40,64}"))throw new ServiceException("安装包版本信息无效");
var cfg=json.readTree(config);String expected=environment.equals("prod")?"cn.cmvr.wms":"cn.cmvr.wms.dev";
if(!expected.equals(cfg.path("android").path("package").asText())||!environment.equals(cfg.path("extra").path("environment").asText()))throw new ServiceException("安装包环境不匹配,请区分开发包和正式包");
long version=cfg.path("android").path("versionCode").asLong();String name=cfg.path("version").asText();if(version<1||version>Integer.MAX_VALUE||name.isBlank()||name.length()>32)throw new ServiceException("安装包版本号无效");
byte[] binaryManifest;try(var in=zip.getInputStream(zip.getEntry("AndroidManifest.xml"))){binaryManifest=in.readNBytes(5*1024*1024+1);}if(binaryManifest.length>5*1024*1024)throw new ServiceException("安装包清单过大");
var parser=new AndroidBinXmlParser(java.nio.ByteBuffer.wrap(binaryManifest));String nativePackage=null;long nativeVersion=-1;
while(parser.next()!=AndroidBinXmlParser.EVENT_END_DOCUMENT){if(parser.getEventType()!=AndroidBinXmlParser.EVENT_START_ELEMENT||!"manifest".equals(parser.getName()))continue;for(int i=0;i<parser.getAttributeCount();i++){String attr=parser.getAttributeName(i),ns=parser.getAttributeNamespace(i);if("package".equals(attr)&&(ns==null||ns.isEmpty()))nativePackage=parser.getAttributeStringValue(i);if("versionCode".equals(attr)&&"http://schemas.android.com/apk/res/android".equals(ns))nativeVersion=Integer.toUnsignedLong(parser.getAttributeIntValue(i));}break;}
if(!expected.equals(nativePackage)||nativeVersion!=version)throw new ServiceException("安装包原生包名或版本与配置不一致");
return Map.of("v",version,"n",name,"r",fingerprint);
}
}
}

View File

@ -55,6 +55,7 @@ public class PurchaseHistoryCorrectionService {
Set<Long> seen=new HashSet<>();for(var entry:command.rows()){
if(entry==null||entry.id()==null||!seen.add(entry.id()))throw new ServiceException("采购明细无效或重复");
if(entry.changes()==null||entry.changes().isEmpty()||!FIELDS.keySet().containsAll(entry.changes().keySet()))throw new ServiceException("仅可更正明确列出的业务字段,不能更改编号、状态、到货或入库数量");
if(entry.changes().containsKey("finalUnitPrice"))com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();
}
}
@Transactional public Map<String,Object> preview(Command command){
@ -78,7 +79,7 @@ public class PurchaseHistoryCorrectionService {
for(var entry:command.rows()){var row=requests.selectPurchaseRequestById(entry.id(),null);if(row==null)throw new ServiceException("采购记录已不存在");projects.requireProjectAccess(row.getProjectId());}
Map<String,Object> saved;try{saved=json.readValue(receipt.get("response_json").toString(),LinkedHashMap.class);}catch(Exception e){throw new IllegalStateException(e);}
for(var result:(List<Map<String,Object>>)saved.get("rows"))for(var change:(List<Map<String,Object>>)result.get("changes"))if("projectId".equals(change.get("field")))for(String side:List.of("before","after"))if(change.get(side) instanceof Number id)projects.requireProjectAccess(id.longValue());
return saved;
return com.ruoyi.warehouse.util.PurchaseQuoteAccess.viewMap(saved);
}
List<Plan> plans=new ArrayList<>();
for(var entry:command.rows()){
@ -186,7 +187,7 @@ public class PurchaseHistoryCorrectionService {
}
private Map<String,Object> view(Plan plan){
var row=new LinkedHashMap<String,Object>();row.put("id",plan.before().getId());row.put("name",plan.before().getMaterialName());row.put("spec",plan.before().getMaterialParams());row.put("version",plan.version());row.put("changes",plan.differences());row.put("receiptCount",plan.receipts().size());row.put("costSourceCount",plan.events().size());row.put("createItem",plan.createItem());row.put("categoryUpdatesArchive",plan.categoryUpdate());row.put("priceImpact",plan.pricePreview());row.put("errors",List.of());row.put("skipped",plan.differences().isEmpty());
row.put("oldActualAmount",plan.before().getActualAmount());row.put("newActualAmount",plan.after().getActualAmount());row.put("oldAmount",plan.before().getFinalUnitPrice()==null?null:PurchasePriceRules.amount(plan.before().getQuantity(),plan.before().getFinalUnitPrice()));row.put("newAmount",plan.after().getFinalUnitPrice()==null?null:PurchasePriceRules.amount(plan.after().getQuantity(),plan.after().getFinalUnitPrice()));row.put("oldStatus",plan.before().getPurchaseStatus());row.put("newStatus",plan.after().getPurchaseStatus());return row;
row.put("oldActualAmount",plan.before().getActualAmount());row.put("newActualAmount",plan.after().getActualAmount());row.put("oldAmount",plan.before().getFinalUnitPrice()==null?null:PurchasePriceRules.amount(plan.before().getQuantity(),plan.before().getFinalUnitPrice()));row.put("newAmount",plan.after().getFinalUnitPrice()==null?null:PurchasePriceRules.amount(plan.after().getQuantity(),plan.after().getFinalUnitPrice()));row.put("oldStatus",plan.before().getPurchaseStatus());row.put("newStatus",plan.after().getPurchaseStatus());return com.ruoyi.warehouse.util.PurchaseQuoteAccess.viewMap(row);
}
private boolean missingAck(Plan plan,Command command){return plan.pricePreview().get("archiveOnlyCount") instanceof Number count&&count.intValue()>0&&!Boolean.TRUE.equals(command.acknowledgeArchiveOnly());}
private boolean equivalent(Object a,Object b){if(a instanceof Number&&b instanceof Number)return new BigDecimal(a.toString()).compareTo(new BigDecimal(b.toString()))==0;return Objects.equals(a,b);}

View File

@ -161,7 +161,7 @@ public class PurchasePriceCorrectionService {
if(Boolean.TRUE.equals(input.copyQuoteToActual())&&!Boolean.TRUE.equals(input.clearQuote()))throw new ServiceException("复制并清空须作为一个组合操作核对");
if(input.reason()==null||input.reason().isBlank()||input.reason().trim().length()>300)throw new ServiceException("请填写价格更正原因,最多300字");
}
private void requirePermission(){if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("价格更正请由采购管理员协助办理",403);}
private void requirePermission(){com.ruoyi.warehouse.util.PurchaseQuoteAccess.require();}
private static BigDecimal amount(BigDecimal quantity,BigDecimal price){return com.ruoyi.warehouse.util.MovingAverageCost.receiptAmount(quantity,price);}
private static boolean equalPrice(BigDecimal a,BigDecimal b){return a==null||b==null?a==b:a.compareTo(b)==0;}
private String previewVersion(Snapshot snapshot,Correction input){return hash(snapshot.version()+"|"+(input.finalUnitPrice()==null?"NULL":input.finalUnitPrice().stripTrailingZeros().toPlainString())+"|"+input.clearQuote()+"|"+input.copyQuoteToActual()+"|"+input.reason().trim()+"|"+SecurityUtils.getUserId());}

View File

@ -14,7 +14,15 @@ public final class PurchaseQuoteAccess {
private PurchaseQuoteAccess() { }
public static boolean allowed() {
try { return SecurityUtils.isAdmin() || SecurityUtils.hasPermi("warehouse:purchase:manage"); }
try {
if (SecurityUtils.isAdmin()) return true;
var login = SecurityUtils.getLoginUser();
if (login == null || login.getUser() == null) return false;
var roles = login.getUser().getRoles();
return roles != null && roles.stream().anyMatch(role -> role != null
&& "purchase_manager".equals(role.getRoleKey())
&& "0".equals(role.getStatus()) && "0".equals(role.getDelFlag()));
}
catch(ServiceException unauthenticated) { return false; }
}
public static void require() {
@ -72,7 +80,7 @@ public final class PurchaseQuoteAccess {
if(allowed())return source;
var result=new LinkedHashMap<String,Object>();
var confidential=Set.of("finalUnitPrice","estimatedUnitPrice","estimatedAmount","lockedAmount","lockedTotal","totalAmount","amount",
"quotePrice","newQuotePrice","oldQuoteAmount","newQuoteAmount");
"quotePrice","newQuotePrice","oldQuoteAmount","newQuoteAmount","oldPrice","newPrice","oldAmount","newAmount","oldLockedAmount","newLockedAmount");
source.forEach((key,value)->{
if(confidential.contains(key))return;
result.put(key,viewValue(value));
@ -81,7 +89,7 @@ public final class PurchaseQuoteAccess {
}
private static Object viewValue(Object value) {
if(value instanceof Map<?,?> map){var copy=new LinkedHashMap<String,Object>();map.forEach((key,item)->copy.put(key.toString(),item));return viewMap(copy);}
if(value instanceof List<?> list)return list.stream().map(PurchaseQuoteAccess::viewValue).toList();
if(value instanceof List<?> list)return list.stream().filter(item -> !(item instanceof Map<?,?> map && "finalUnitPrice".equals(map.get("field")))).map(PurchaseQuoteAccess::viewValue).toList();
return value;
}
}

View File

@ -0,0 +1,10 @@
import request from '@/utils/request'
import {saveAs} from 'file-saver'
export const listFiles=(params,signal)=>request({url:'/system/files',params,signal})
export const removeFile=id=>request({url:'/system/files/'+id,method:'delete'})
export async function downloadFile(file,signal){
const blob=await request({url:'/system/files/'+file.id+'/content',responseType:'blob',signal,timeout:900000})
if(/application\/(?:json|problem\+json)/i.test(blob.type)){let result;try{result=JSON.parse(await blob.text())}catch{}throw new Error(result?.msg||'下载未完成,请稍后重试')}
saveAs(blob,file.name)
}
export function fileSize(bytes){const n=Number(bytes);if(!Number.isFinite(n)||n<0)return '—';if(n>=1024**3)return (n/1024**3).toFixed(2)+' GB';if(n>=1024**2)return (n/1024**2).toFixed(1)+' MB';if(n>=1024)return (n/1024).toFixed(1)+' KB';return n+' B'}

View File

@ -0,0 +1,17 @@
<template>
<div class="managed-attachments"><div v-for="file in modelValue" :key="file.id" class="attachment-row"><el-icon class="attachment-icon"><Document/></el-icon><button type="button" class="attachment-name" :title="file.name" :disabled="downloading.has(file.id)" @click="download(file)">{{ file.name }}</button><span class="attachment-size">{{ fileSize(file.size) }}</span><el-button link type="primary" :loading="downloading.has(file.id)" :disabled="disabled" @click="download(file)">下载</el-button><el-button v-if="editable" link type="danger" :disabled="disabled" @click="$emit('update:modelValue',modelValue.filter(f=>f.id!==file.id))">移除</el-button></div><span v-if="!modelValue.length&&!editable" class="attachments-empty">暂无附件</span></div>
</template>
<script setup>
import {onBeforeUnmount,reactive} from 'vue'
import {Document} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {downloadFile,fileSize} from '@/api/system/files'
defineProps({modelValue:{type:Array,default:()=>[]},editable:Boolean,disabled:Boolean})
defineEmits(['update:modelValue'])
const downloading=reactive(new Set()),controllers=new Set()
async function download(file){if(downloading.has(file.id))return;const ctl=new AbortController();controllers.add(ctl);downloading.add(file.id);try{await downloadFile(file,ctl.signal)}catch(error){if(!ctl.signal.aborted)ElMessage.error(error.message||'下载失败,请重试')}finally{controllers.delete(ctl);downloading.delete(file.id)}}
onBeforeUnmount(()=>controllers.forEach(c=>c.abort()))
</script>
<style scoped>
.managed-attachments{width:100%;min-width:0}.attachment-row{display:flex;align-items:center;gap:10px;padding:9px 12px;margin-top:7px;background:var(--el-fill-color-light);border:1px solid var(--el-border-color-lighter);border-radius:6px}.attachment-icon{color:var(--el-color-primary);flex-shrink:0}.attachment-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:none;padding:0;text-align:left;cursor:pointer;color:var(--el-color-primary);font:inherit;font-size:13px}.attachment-name:hover{text-decoration:underline}.attachment-size,.attachments-empty{font-size:12px;color:var(--el-text-color-secondary);white-space:nowrap}.attachment-row :deep(.el-button+.el-button){margin-left:0}@media(max-width:550px){.attachment-row{gap:6px;padding:8px}.attachment-size{display:none}}
</style>

View File

@ -0,0 +1,32 @@
<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 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>
<script setup>
import {computed,nextTick,onBeforeUnmount,reactive,ref,watch} from 'vue'
import {UploadFilled} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {cancelFileTransfer,uploadFileResumable} from '@/api/common/file-transfers'
const props=defineProps({purpose:{type:String,required:true},modelValue:{type:Array,default:()=>[]},limit:{type:Number,default:20},showCompleted:{type:Boolean,default:true},disabled:Boolean,buttonText:{type:String,default:'上传文件'}})
const emit=defineEmits(['update:modelValue','uploaded','pending'])
// Render-only keys; the backend generates the owner-bound upload identifiers.
const input=ref(),jobs=ref([]),running=ref(false);let disposed=false,nextJob=0
const pending=computed(()=>running.value||jobs.value.some(j=>j.status==='failed'||j.status==='queued'))
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 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()}
catch(error){if(!disposed){job.status='failed';job.error=ctl.signal.aborted?'已暂停,重试或重新选择同一文件可继续':error.message||'上传失败,请重试'}}
finally{if(!disposed)running.value=false;job.controller=null}
}
onBeforeUnmount(()=>{disposed=true;jobs.value.forEach(j=>j.controller?.abort())})
defineExpose({pending,running})
</script>
<style scoped>
.upload-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.upload-hint{font-size:12px;color:var(--el-text-color-secondary)}.upload-jobs{margin-top:12px;max-height:210px;overflow:auto;border:1px solid var(--el-border-color-lighter);border-radius:8px;background:var(--el-fill-color-lighter)}.upload-job{display:flex;align-items:center;gap:14px;padding:10px 14px;min-height:56px;border-bottom:1px solid var(--el-border-color-lighter)}.upload-job:last-child{border:0}.upload-name{flex:1;min-width:0;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.upload-stage{width:260px;max-width:48%;flex-shrink:0}.upload-stage small{font-size:12px;color:var(--el-text-color-secondary);overflow-wrap:anywhere}.upload-job :deep(.el-button+.el-button){margin-left:0}@media(max-width:650px){.upload-job{flex-wrap:wrap;gap:8px}.upload-name{flex-basis:100%}.upload-stage{flex:1;max-width:none;width:auto}}
</style>

View File

@ -0,0 +1,20 @@
<template><div class="ql-editor notice-richtext" aria-label="公告正文" v-html="safeHtml" /></template>
<script setup>
import {computed} from 'vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {noticeHtml} from '@/utils/notice-html'
const props=defineProps({html:{type:String,default:''}})
const safeHtml=computed(()=>noticeHtml(props.html)||'暂无正文')
</script>
<style scoped>
.notice-richtext{height:auto;min-height:0;min-width:0;padding:0;overflow:visible;font:inherit;line-height:1.9;color:var(--el-text-color-primary);overflow-wrap:anywhere;counter-reset:list-0}
.notice-richtext :deep(img){max-width:100%;height:auto;vertical-align:middle}
.notice-richtext :deep(a){color:var(--el-color-primary);text-decoration:underline;overflow-wrap:anywhere}
.notice-richtext :deep(pre){white-space:pre-wrap;overflow-wrap:anywhere}
.notice-richtext :deep(table){border-collapse:collapse;max-width:100%;font-size:inherit}
.notice-richtext :deep(th),.notice-richtext :deep(td){border:1px solid var(--el-border-color);padding:6px 10px;overflow-wrap:anywhere}
.notice-richtext :deep(th){background:var(--el-fill-color-light)}
.notice-richtext :deep(.ql-ui){display:none}
.notice-richtext :deep(li[data-list="bullet"]){counter-increment:none}
.notice-richtext :deep(li[data-list="bullet"]::before){content:'\2022'}
</style>

View File

@ -41,6 +41,7 @@
</template>
<script setup>
import { canViewPurchaseQuotes } from '@/utils/purchase-quote-permission'
import { formatDateTime } from '@/utils/display-format'
import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
@ -51,7 +52,7 @@ import { purchaseDocumentKinds, purchaseAttachmentAccept, purchaseAttachmentErro
const DocumentPdfPreview = defineAsyncComponent(()=>import('@/components/SupplierLicenseAttachment/PdfPreview.vue'))
const user = useUserStore()
const visibleKinds = computed(()=>purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||user.permissions.includes('*:*:*')||user.permissions.includes('warehouse:purchase:manage')))
const visibleKinds = computed(()=>purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||canViewPurchaseQuotes(user.id,user.roles)))
const visible = ref(false), type = ref('batch'), targetId = ref(), context = ref(''), activeKind = ref('REQUEST'), groups = ref([])
const loading = ref(false), busy = ref(false), uploading = ref(false), error = ref(''), closeWarning = ref(false)
const previewFile = ref(null), previewBlob = shallowRef(null), previewUrl = ref('')

View File

@ -65,8 +65,8 @@
<el-row :gutter="10" class="mb8">
<el-col :span="24" class="sheet-toolbar">
<el-button v-if="canEdit && !editing" type="primary" plain size="small" icon="el-icon-edit" :disabled="saving" @click="startEditing">编辑</el-button>
<el-button v-if="!isEditing&&$can(['warehouse:purchase:manage'])" size="small" title="选择一条已保存且未取消的明细,预览并更正报价及关联金额" :disabled="saving||dirty||selected.length!==1||!selected[0]?.id||Number(selected[0]?.purchaseStatus)===5" @click="$refs.priceCorrection.open(selected[0])">更正价格</el-button>
<el-button v-if="!isEditing&&$can(['warehouse:purchase:manage'])" size="small" title="选择1至100条明细,预览并更正历史字段及关联金额" :disabled="saving||dirty||!selected.length||selected.length>100||selected.some(row=>!row.id||Number(row.purchaseStatus)===5)" @click="$refs.historyCorrection.open(selected)">历史更正</el-button>
<el-button v-if="!isEditing&&canViewQuotes" size="small" title="选择一条已保存且未取消的明细,预览并更正报价及关联金额" :disabled="saving||dirty||selected.length!==1||!selected[0]?.id||Number(selected[0]?.purchaseStatus)===5" @click="$refs.priceCorrection.open(selected[0])">更正价格</el-button>
<el-button v-if="!isEditing&&canViewQuotes" size="small" title="选择1至100条明细,预览并更正历史字段及关联金额" :disabled="saving||dirty||!selected.length||selected.length>100||selected.some(row=>!row.id||Number(row.purchaseStatus)===5)" @click="$refs.historyCorrection.open(selected)">历史更正</el-button>
<el-button v-if="canEdit && !isEditing && !sheet.unbatched" size="small" :disabled="saving||selected.length!==1||!canReopen(selected[0])" title="选择一条未到货的已确认采购,撤销后保留数量和报价" @click="reopen(selected[0])">撤销确认</el-button>
<template v-if="isEditing">
<el-button size="small" :disabled="saving" @click="cancelEditing">取消编辑</el-button>
@ -170,6 +170,7 @@ import PurchaseCell from './Cell.vue'
import PriceCorrection from './PriceCorrection.vue'
import HistoryCorrection from './HistoryCorrection.vue'
import PurchaseDocuments from '@/components/PurchaseDocuments'
import { canViewPurchaseQuotes } from '@/utils/purchase-quote-permission'
import SupplierQuotation from './SupplierQuotation.vue'
import { supplierInquiryRows, quotationReady } from '@/utils/supplier-quotation'
import { purchaseDocumentKinds } from '@/utils/purchase-documents'
@ -199,7 +200,7 @@ export default {
data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,batches:[],total:0,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
computed:{
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
canViewQuotes(){return this.$auth.hasPermiOr(['warehouse:purchase:manage'])},
canViewQuotes(){const user=this.$store.getters;return canViewPurchaseQuotes(user.userId,user.roles)},
compactAmounts(){return this.canViewQuotes&&amountDisplay.enabled},
actualTotal(){return purchaseActualTotal(this.sheet?.rows||[])},
baselineRowMap(){return new Map((this.baseline?JSON.parse(this.baseline).rows||[]:[]).map(row=>[row._key,row]))},

View File

@ -0,0 +1,25 @@
import createDOMPurify from 'dompurify'
const purifier=createDOMPurify(window)
const quillClass=/^ql-(?:align-(?:center|right|justify)|direction-rtl|indent-[1-8]|size-(?:small|large|huge)|font-(?:serif|monospace)|syntax|ui)$/
const color=/^(?:#[\da-f]{3,8}|[a-z]+|(?:rgb|hsl)a?\([\d.,%\s]+\))$/i
function safeStyle(value){
const source=document.createElement('span').style;source.cssText=value
const target=document.createElement('span').style
for(const name of ['color','background-color']){const v=source.getPropertyValue(name);if(color.test(v))target.setProperty(name,v)}
const align=source.getPropertyValue('text-align');if(/^(left|right|center|justify)$/.test(align))target.textAlign=align
const size=source.getPropertyValue('font-size'),match=size.match(/^(\d+(?:\.\d+)?)(px|pt|em|rem|%)$/)
if(match){const n=Number(match[1]),unit=match[2],bounds=unit==='em'||unit==='rem'?[.5,4]:unit==='%'?[50,300]:[8,72];if(n>=bounds[0]&&n<=bounds[1])target.fontSize=size}
return target.cssText
}
purifier.addHook('uponSanitizeAttribute',(_node,data)=>{
if(data.attrName==='style'){data.attrValue=safeStyle(data.attrValue);if(!data.attrValue)data.keepAttr=false}
if(data.attrName==='class'){data.attrValue=data.attrValue.split(/\s+/).filter(name=>quillClass.test(name)).join(' ');if(!data.attrValue)data.keepAttr=false}
})
purifier.addHook('afterSanitizeAttributes',node=>{if(node.tagName==='A'&&node.hasAttribute('href')){node.setAttribute('target','_blank');node.setAttribute('rel','noopener noreferrer')}})
/** Keep editor formatting while excluding executable HTML, controls and page-level CSS. */
export function noticeHtml(value){return purifier.sanitize(String(value??''),{
ALLOWED_TAGS:['p','br','div','span','strong','b','em','i','u','s','strike','blockquote','pre','code','h1','h2','h3','h4','h5','h6','ol','ul','li','a','img','table','thead','tbody','tr','th','td','sub','sup','hr'],
ALLOWED_ATTR:['href','target','rel','src','alt','title','class','style','start','value','type','colspan','rowspan','width','height','data-list','data-checked'],
ALLOW_DATA_ATTR:false,ALLOW_ARIA_ATTR:false,FORBID_TAGS:['style','script','iframe','object','embed','form','input','button','textarea','select'],
})}

View File

@ -0,0 +1,3 @@
const pinyin=new Intl.Collator('zh-Hans-CN-u-co-pinyin',{sensitivity:'base',numeric:true})
const name=p=>String(p.name||p.nickName||p.nick_name||p.userName||p.account||p.user_name||'').trim()
export const sortPeople=people=>[...people].sort((a,b)=>pinyin.compare(name(a),name(b))||pinyin.compare(String(a.account||a.userName||a.user_name||''),String(b.account||b.userName||b.user_name||''))||String(a.id??a.userId??'').localeCompare(String(b.id??b.userId??''),undefined,{numeric:true}))

View File

@ -0,0 +1,4 @@
// Quote visibility is independent of menu permissions.
export function canViewPurchaseQuotes(userId, roles) {
return Number(userId) === 1 || (Array.isArray(roles) && roles.includes('purchase_manager'))
}

View File

@ -0,0 +1,22 @@
<template>
<el-dialog v-model="open" title="发布 App 安装包" width="560px" append-to-body :close-on-click-modal="false" :before-close="close">
<div class="release-file"><el-icon><Cellphone/></el-icon><div><strong>{{ file?.name }}</strong><span>{{ fileSize(file?.size) }} · 系统将自动读取环境和安装版本号</span></div></div>
<el-form label-position="top"><el-form-item label="更新说明"><el-input v-model="notes" type="textarea" :rows="4" maxlength="140" show-word-limit placeholder="告诉使用者这次更新了什么" :disabled="busy"/></el-form-item></el-form>
<el-alert type="info" :closable="false" title="仅发布到当前环境"><template #default>安装包须由本系统打包,版本号应高于已发布版本。发布后,员工登录 App 或回到前台时会收到更新提示;下载校验通过后由手机系统确认安装。文件库删除原文件不影响已发布安装包。</template></el-alert>
<p v-if="error" role="alert" class="release-error">{{ error }}</p>
<template #footer><el-button :disabled="busy" @click="open=false">取消</el-button><el-button type="primary" :loading="busy" @click="publish">确认发布新版</el-button></template>
</el-dialog>
</template>
<script setup>
import {ref} from 'vue'
import {Cellphone} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import request from '@/utils/request'
import {fileSize} from '@/api/system/files'
const open=ref(false),file=ref(null),notes=ref(''),busy=ref(false),error=ref('')
function show(value){file.value=value;notes.value='';error.value='';open.value=true}
function close(done){if(!busy.value)done()}
async function publish(){if(busy.value||!file.value)return;busy.value=true;error.value='';try{const result=await request({url:'/system/mobile-release',method:'post',data:{fileId:file.value.id,notes:notes.value},timeout:180000});ElMessage.success(`已发布 ${result.data.versionName}(安装版本 ${result.data.versionCode})`);open.value=false}catch(e){error.value=e.message||'发布失败,请重试'}finally{busy.value=false}}
defineExpose({show})
</script>
<style scoped>.release-file{display:flex;gap:14px;align-items:center;padding:16px;background:var(--el-fill-color-light);border-radius:12px;margin-bottom:20px}.release-file>.el-icon{font-size:32px;color:var(--el-color-primary)}.release-file>div{display:flex;flex-direction:column;min-width:0;gap:6px}.release-file strong{overflow-wrap:anywhere}.release-file span{font-size:12px;color:var(--el-text-color-secondary)}.release-error{color:var(--el-color-danger);line-height:1.6}</style>

View File

@ -0,0 +1,39 @@
<template>
<business-list-page class="app-container file-library">
<template #header>
<el-form :inline="true" @submit.prevent="search"><el-form-item label="文件"><el-input v-model="query.keyword" placeholder="搜索文件名或上传人" clearable style="width:280px" @keyup.enter="search"/></el-form-item><el-form-item><el-checkbox v-model="query.mine" @change="search">仅看我的上传</el-checkbox></el-form-item><el-form-item><el-button type="primary" :icon="Search" @click="search">查询</el-button><el-button :icon="Refresh" @click="reset">重置</el-button></el-form-item></el-form>
<div class="library-toolbar"><file-upload v-if="canUpload" purpose="fileLibrary" @uploaded="uploaded"/><span v-else class="library-hint">共享文件库 · {{ total }} 个文件</span></div>
<el-alert v-if="error" type="error" :title="error" :closable="false" class="library-error"><template #default><el-button link type="primary" @click="load">重新加载</el-button></template></el-alert>
</template>
<template #default="{tableHeight}"><business-table v-loading="loading" :data="rows" :height="tableHeight" empty-text="暂无文件,可上传文件后在这里统一查找和下载">
<el-table-column label="文件名称" min-width="300" show-overflow-tooltip class-name="business-control-cell"><template #default="{row}"><el-link v-if="row.canDownload" type="primary" :underline="false" :disabled="downloading.has(row.id)" @click="download(row)"><el-icon class="file-icon"><Document/></el-icon>{{ row.name }}</el-link><span v-else>{{ row.name }}</span></template></el-table-column>
<el-table-column label="大小" width="115" align="right"><template #default="{row}">{{ fileSize(row.size) }}</template></el-table-column>
<el-table-column label="上传人" prop="uploadedBy" width="150" show-overflow-tooltip/>
<el-table-column label="上传时间" width="180"><template #default="{row}">{{ formatDateTime(row.uploadedAt) }}</template></el-table-column>
<el-table-column label="操作" :width="isAdmin?240:150" fixed="right" class-name="business-operation-cell"><template #default="{row}"><el-button v-if="row.canDownload" link type="primary" :icon="Download" :loading="downloading.has(row.id)" @click="download(row)">下载</el-button><el-button v-if="isAdmin&&/\.apk$/i.test(row.name)" link type="primary" @click="releaseDialog.show(row)">发布新版</el-button><el-button v-if="row.canRemove" link type="danger" :icon="Delete" @click="remove(row)">删除</el-button></template></el-table-column>
</business-table></template>
<template #footer><pagination v-show="total>0" v-model:page="query.page" v-model:limit="query.size" :total="total" @pagination="load"/></template>
</business-list-page>
<app-release ref="releaseDialog"/>
</template>
<script setup name="FileLibrary">
import {computed,onBeforeUnmount,reactive,ref} from 'vue'
import AppRelease from './AppRelease.vue'
import useUserStore from '@/store/modules/user'
import {Delete,Document,Download,Refresh,Search} from '@element-plus/icons-vue'
import {ElMessage,ElMessageBox} from 'element-plus'
import FileUpload from '@/components/ManagedFiles/Upload.vue'
import {listFiles,removeFile,downloadFile,fileSize} from '@/api/system/files'
import {formatDateTime} from '@/utils/display-format'
const user=useUserStore(),isAdmin=computed(()=>Number(user.id)===1),releaseDialog=ref()
const rows=ref([]),total=ref(0),loading=ref(false),error=ref(''),canUpload=ref(false),query=reactive({keyword:'',mine:false,page:1,size:20}),downloading=reactive(new Set()),downloads=new Set();let controller,generation=0,disposed=false
async function load(){controller?.abort();controller=new AbortController();const current=++generation;loading.value=true;error.value='';try{const result=await listFiles({...query},controller.signal);if(disposed||current!==generation)return;rows.value=result.data.rows;total.value=result.data.total;canUpload.value=result.data.canUpload;if(!rows.value.length&&total.value&&(query.page-1)*query.size>=total.value){query.page=Math.max(1,Math.ceil(total.value/query.size));return load()}}catch(e){if(!disposed&&current===generation&&e.code!=='ERR_CANCELED')error.value=e.message||'文件加载失败'}finally{if(current===generation)loading.value=false}}
function search(){query.page=1;load()}
function reset(){query.keyword='';query.mine=false;search()}
function uploaded(){query.page=1;load()}
async function download(file){if(downloading.has(file.id))return;const ctl=new AbortController();downloads.add(ctl);downloading.add(file.id);try{await downloadFile(file,ctl.signal)}catch(e){if(!ctl.signal.aborted)ElMessage.error(e.message||'下载失败')}finally{downloads.delete(ctl);downloading.delete(file.id)}}
async function remove(file){try{await ElMessageBox.confirm('确定删除“'+file.name+'”?','删除文件',{type:'warning'});await removeFile(file.id);ElMessage.success('文件已删除');load()}catch{}}
onBeforeUnmount(()=>{disposed=true;controller?.abort();downloads.forEach(c=>c.abort())})
load()
</script>
<style scoped>.library-toolbar{display:flex;align-items:center;justify-content:space-between;gap:16px;padding-bottom:12px}.library-toolbar>section{width:100%}.library-hint{font-size:13px;color:var(--el-text-color-secondary)}.library-error{margin-bottom:12px}.file-icon{margin-right:7px}.file-library :deep(.el-link){max-width:100%;vertical-align:middle}.file-library :deep(.el-link__inner){overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block}</style>

View File

@ -69,7 +69,7 @@
<el-table-column label="项目" prop="projectName" :min-width="arrivalMode?120:150" show-overflow-tooltip />
<el-table-column v-if="!arrivalMode" label="费用分类" prop="expenseCategoryName" width="110" show-overflow-tooltip/>
<el-table-column v-if="!arrivalMode" label="用途" width="110" show-overflow-tooltip><template #default="s">{{ s.row.purchasePurpose==='REPAY'?'归还借用':'本项目使用' }}</template></el-table-column>
<el-table-column v-if="!arrivalMode&&canManageAll" label="报价金额" width="126" align="right" class-name="business-status-cell">
<el-table-column v-if="!arrivalMode&&canViewQuotes" label="报价金额" width="126" align="right" class-name="business-status-cell">
<template #default="scope">
<div class="primary-text">{{ scope.row.finalUnitPrice === null ? '待定价' : '¥ ' + money(scope.row.estimatedAmount) }}</div>
<el-tag size="small" :type="(scope.row.priceLocked ? 'success' : 'info') || 'primary'">{{ scope.row.priceLocked ? '价格已锁定' : '价格未锁定' }}</el-tag>
@ -78,7 +78,7 @@
</el-table-column>
<el-table-column :label="arrivalMode ? '采购数量' : '数量'" :width="arrivalMode?95:135" class-name="business-control-cell"><template #default="s"><el-input-number v-if="!arrivalMode && inlineEdit && canOperate(s.row)" v-model="s.row.quantity" :precision="4" :min="0.0001" :controls="false" :disabled="s.row._saving" style="width:110px"/><span v-else>{{ s.row.quantity }}{{ arrivalMode?' '+(s.row.unit || ''):'' }}</span></template></el-table-column>
<el-table-column v-if="!arrivalMode" label="单位" prop="unit" width="70" show-overflow-tooltip/>
<el-table-column v-if="!arrivalMode&&canManageAll" label="报价单价" width="145" class-name="business-control-cell"><template #default="s"><el-input-number v-if="inlineEdit && canOperate(s.row)" v-model="s.row.finalUnitPrice" :precision="6" :min="0" :controls="false" :disabled="s.row._saving || !canEditPrice(s.row)" style="width:120px"/><span v-else>{{ s.row.finalUnitPrice==null?'未定价':s.row.finalUnitPrice }}</span><div v-if="Number(s.row.receivedQuantity)>0" class="secondary-text">已入库,价格锁定</div></template></el-table-column>
<el-table-column v-if="!arrivalMode&&canViewQuotes" label="报价单价" width="145" class-name="business-control-cell"><template #default="s"><el-input-number v-if="inlineEdit && canOperate(s.row)" v-model="s.row.finalUnitPrice" :precision="6" :min="0" :controls="false" :disabled="s.row._saving || !canEditPrice(s.row)" style="width:120px"/><span v-else>{{ s.row.finalUnitPrice==null?'未定价':s.row.finalUnitPrice }}</span><div v-if="Number(s.row.receivedQuantity)>0" class="secondary-text">已入库,价格锁定</div></template></el-table-column>
<el-table-column v-if="!arrivalMode && inlineEdit" label="保存修改" width="100" class-name="business-operation-cell"><template #default="s"><el-button v-if="canOperate(s.row)" link type="primary" :loading="s.row._saving" @click="saveInline(s.row)">保存本行</el-button><span v-else>-</span></template></el-table-column>
<el-table-column v-if="!arrivalMode" label="供应商" prop="supplierName" min-width="120" show-overflow-tooltip/>
<el-table-column v-if="!arrivalMode" label="采购批次" min-width="165">
@ -156,8 +156,8 @@
<div class="detail-grid">
<div><span>采购项目</span><strong>{{ detailRequest.projectName || '-' }}</strong></div>
<div><span>经费科目</span><strong>{{ detailRequest.expenseCategoryName || '-' }}</strong></div>
<div v-if="canManageAll"><span>报价金额</span><strong>{{ detailRequest.finalUnitPrice === null ? '待定价' : '¥ ' + money(detailRequest.estimatedAmount) }}</strong></div>
<div v-if="canManageAll"><span>计入项目费用</span><strong>¥ {{ money(detailRequest.lockedAmount) }}({{ detailRequest.priceLocked ? '已锁价' : '未锁价' }})</strong></div>
<div v-if="canViewQuotes"><span>报价金额</span><strong>{{ detailRequest.finalUnitPrice === null ? '待定价' : '¥ ' + money(detailRequest.estimatedAmount) }}</strong></div>
<div v-if="canViewQuotes"><span>计入项目费用</span><strong>¥ {{ money(detailRequest.lockedAmount) }}({{ detailRequest.priceLocked ? '已锁价' : '未锁价' }})</strong></div>
<div><span>采购批次</span><strong>{{ detailRequest.purchaseBatchNo ? [detailRequest.purchaseBatchNo, detailRequest.purchaseBatchName].filter(Boolean).join(' / ') : '未分配' }}</strong></div>
<div><span>创建时间</span><strong>{{ parseTime(detailRequest.createTime) || '-' }}</strong></div>
</div>
@ -271,8 +271,8 @@
</el-form-item>
</el-col>
<el-col :span="12"><el-form-item label="需求数量" prop="quantity"><el-input-number v-model="form.quantity" :min="0.0001" :precision="4" :controls="false" /></el-form-item></el-col>
<el-col v-if="canManageAll" :span="12"><el-form-item label="最终含税单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" placeholder="可暂不填写" /><div v-if="Number(form.receivedQuantity||0)>0" class="product-meta">已有确认入库,需先逐步撤销到待入库后才能修改价格。</div></el-form-item></el-col>
<el-col v-if="canManageAll" :span="12"><el-form-item label="采购总金额"><el-input :model-value="money(Number(form.quantity || 0) * Number(form.finalUnitPrice || 0))" disabled /></el-form-item></el-col>
<el-col v-if="canViewQuotes" :span="12"><el-form-item label="最终含税单价" prop="finalUnitPrice"><el-input-number v-model="form.finalUnitPrice" :min="0" :precision="6" :controls="false" :disabled="Number(form.receivedQuantity||0)>0" placeholder="可暂不填写" /><div v-if="Number(form.receivedQuantity||0)>0" class="product-meta">已有确认入库,需先逐步撤销到待入库后才能修改价格。</div></el-form-item></el-col>
<el-col v-if="canViewQuotes" :span="12"><el-form-item label="采购总金额"><el-input :model-value="money(Number(form.quantity || 0) * Number(form.finalUnitPrice || 0))" disabled /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="采购链接" prop="purchaseLink"><el-input v-model="form.purchaseLink" placeholder="请输入商品或供应商链接" /></el-form-item></el-col>
<el-col :span="24"><el-form-item label="申请备注" prop="remark"><el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入用途、预算等补充信息" /></el-form-item></el-col>
</el-row>
@ -387,7 +387,7 @@
<el-table-column label="需求数量" min-width="110" class-name="business-control-cell">
<template #default="scope"><el-input v-model="scope.row.quantity" @paste="handleGridPaste($event, scope.$index, 8)" /></template>
</el-table-column>
<el-table-column v-if="canManageAll" label="最终含税单价" min-width="130" class-name="business-control-cell">
<el-table-column v-if="canViewQuotes" label="最终含税单价" min-width="130" class-name="business-control-cell">
<template #default="scope"><el-input v-model="scope.row.finalUnitPrice" @paste="handleGridPaste($event, scope.$index, 9)" /></template>
</el-table-column>
<el-table-column label="采购链接" min-width="210" class-name="business-control-cell">
@ -461,6 +461,7 @@
</template>
<script>
import { canViewPurchaseQuotes } from '@/utils/purchase-quote-permission'
import { formatDateTime } from '@/utils/display-format'
import { runLatest, invalidateQuery } from '@/utils/query-session'
import { defineAsyncComponent } from 'vue'
@ -616,6 +617,7 @@ export default {
canBulkEditSelection() { return this.selectedPurchaseRows.length > 0 && this.selectedPurchaseRows.every(this.canBulkEditPurchase) },
canLockSelection() { return this.selectedPurchaseRows.length > 0 && this.selectedPurchaseRows.every(this.canLockPurchase) },
canDeleteSelection() { return this.selectedPurchaseRows.length > 0 && this.selectedPurchaseRows.every(this.canDeletePurchase) },
canViewQuotes() { const user=this.$store.getters; return canViewPurchaseQuotes(user.userId,user.roles) },
canManageAll() {
const permissions = this.$store.getters.permissions || []
return permissions.includes('*:*:*') || permissions.includes('warehouse:purchase:manage')
@ -1443,7 +1445,7 @@ export default {
},
canEditPrice(row) { return this.canOperate(row) && Number(row.receivedQuantity || 0) <= 0 },
canBulkEditPurchase(row) { return this.canOperate(row) && Number(row.receivedQuantity || 0) <= 0 },
canLockPurchase(row) { return this.canManageAll && this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
canLockPurchase(row) { return this.canViewQuotes && this.canOperate(row) && !row.priceLocked && row.finalUnitPrice !== null && row.finalUnitPrice !== undefined && row.finalUnitPrice !== '' },
canDeletePurchase(row) { return this.canOperate(row) && Number(row.acceptedQuantity || 0) <= 0 && Number(row.pendingArrivalQuantity || 0) <= 0 },
canSelectArrival(row) {
if (!this.canOperate(row) || !row || row.historical || Number(row.purchaseStatus) === 5) return false

View File

@ -0,0 +1,28 @@
import {afterEach,beforeEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import {h,reactive} from 'vue'
import ElementPlus from 'element-plus'
import AppRelease from '@/views/system/file/AppRelease.vue'
import Library from '@/views/system/file/index.vue'
const state=vi.hoisted(()=>({user:{id:1},request:vi.fn(),list:vi.fn(),message:vi.fn(),row:{id:'test-file',name:'release.apk',size:128,canDownload:true,canRemove:true}}))
vi.mock('@/store/modules/user',()=>({default:()=>state.user}))
vi.mock('@/utils/request',()=>({default:state.request}))
vi.mock('@/api/system/files',()=>({listFiles:state.list,downloadFile:vi.fn(),removeFile:vi.fn(),fileSize:n=>`${n} B`}))
vi.mock('element-plus',async importOriginal=>({...await importOriginal(),ElMessage:{success:state.message,error:vi.fn()}}))
let wrapper
beforeEach(()=>{state.user.id=1;state.request.mockReset();state.list.mockResolvedValue({data:{rows:[state.row],total:1,canUpload:true}});state.message.mockReset()})
afterEach(()=>{wrapper?.unmount();document.body.innerHTML=''})
const modal={props:['modelValue'],template:'<div v-if="modelValue"><slot/><slot name="footer"/></div>'}
function dialog(){wrapper=mount(AppRelease,{attachTo:document.body,global:{plugins:[ElementPlus],stubs:{ElDialog:modal}}});wrapper.vm.show(state.row);return wrapper}
it('publishes the selected APK only after confirmation and passes the release notes',async()=>{
state.request.mockResolvedValue({data:{versionName:'1.0.0',versionCode:3}});dialog();await flushPromises();await wrapper.find('textarea').setValue('完善现场操作');expect(state.request).not.toHaveBeenCalled();await wrapper.findAll('button').find(b=>b.text().includes('确认发布新版')).trigger('click');await flushPromises();expect(state.request).toHaveBeenCalledWith(expect.objectContaining({url:'/system/mobile-release',method:'post',data:{fileId:'test-file',notes:'完善现场操作'}}));expect(state.message).toHaveBeenCalled();expect(wrapper.text()).not.toContain('release.apk')
})
it('shows backend validation errors and allows a retry without losing the notes',async()=>{
state.request.mockRejectedValueOnce(new Error('安装包环境不匹配')).mockResolvedValueOnce({data:{versionName:'1.0.0',versionCode:3}});dialog();await flushPromises();await wrapper.find('textarea').setValue('机器人更新');await wrapper.findAll('button').find(b=>b.text().includes('确认发布新版')).trigger('click');await flushPromises();expect(wrapper.text()).toContain('安装包环境不匹配');expect(wrapper.find('textarea').element.value).toBe('机器人更新');await wrapper.findAll('button').find(b=>b.text().includes('确认发布新版')).trigger('click');await flushPromises();expect(state.request).toHaveBeenCalledTimes(2)
})
it.each([[1,true],[2,false]])('only the super administrator sees the APK publish entry (user %s)',async(id,allowed)=>{
state.user.id=id;const column={setup(_,ctx){return()=>h('div',ctx.slots.default?.({row:state.row}))}};
wrapper=mount(Library,{global:{plugins:[ElementPlus],stubs:{BusinessListPage:{template:'<div><slot name="header"/><slot :tableHeight="400"/><slot name="footer"/></div>'},BusinessTable:{template:'<div><slot/></div>'},ElTableColumn:column,Pagination:true,FileUpload:true,AppRelease:true}}});await flushPromises();expect(wrapper.text().includes('发布新版')).toBe(allowed)
})
it('does not offer publishing for ordinary documents',async()=>{const old=state.row.name;state.row.name='说明.pdf';const column={setup(_,ctx){return()=>h('div',ctx.slots.default?.({row:state.row}))}};wrapper=mount(Library,{global:{plugins:[ElementPlus],stubs:{BusinessListPage:{template:'<div><slot :tableHeight="400"/></div>'},BusinessTable:{template:'<div><slot/></div>'},ElTableColumn:column,Pagination:true,AppRelease:true}}});await flushPromises();expect(wrapper.text()).not.toContain('发布新版');state.row.name=old})

View File

@ -0,0 +1,8 @@
import {beforeEach,expect,it,vi} from 'vitest'
const mocks=vi.hoisted(()=>({request:vi.fn(),saveAs:vi.fn()}))
vi.mock('@/utils/request',()=>({default:mocks.request}))
vi.mock('file-saver',()=>({saveAs:mocks.saveAs}))
import {downloadFile} from '@/api/system/files'
beforeEach(()=>vi.resetAllMocks())
it('a permission error returned as a blob is surfaced instead of downloading an error document',async()=>{mocks.request.mockResolvedValue({type:'application/json',text:async()=>JSON.stringify({code:403,msg:'没有附件权限'})});await expect(downloadFile({id:'one',name:'data.zip'})).rejects.toThrow('没有附件权限');expect(mocks.saveAs).not.toHaveBeenCalled()})
it('a legitimate JSON document is downloaded using its original name and a private authenticated endpoint',async()=>{const blob=new Blob(['{}'],{type:'application/octet-stream'}),signal=new AbortController().signal;mocks.request.mockResolvedValue(blob);await downloadFile({id:'one',name:'资料.json'},signal);expect(mocks.request).toHaveBeenCalledWith(expect.objectContaining({url:'/system/files/one/content',responseType:'blob',signal}));expect(mocks.saveAs).toHaveBeenCalledWith(blob,'资料.json')})

View File

@ -0,0 +1,39 @@
import {afterEach,beforeEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Uploader from '@/components/ManagedFiles/Upload.vue'
import Attachments from '@/components/ManagedFiles/Attachments.vue'
import Library from '@/views/system/file/index.vue'
const api=vi.hoisted(()=>({upload:vi.fn(),download:vi.fn(),list:vi.fn(),remove:vi.fn(),cancel:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({id:2})}))
vi.mock('@/api/common/file-transfers',()=>({uploadFileResumable:api.upload,cancelFileTransfer:api.cancel}))
vi.mock('@/api/system/files',()=>({downloadFile:api.download,listFiles:api.list,removeFile:api.remove,fileSize:n=>n+' B'}))
let w
beforeEach(()=>{vi.resetAllMocks();api.download.mockResolvedValue();api.cancel.mockResolvedValue();api.list.mockResolvedValue({data:{rows:[],total:0,canUpload:true}})})
afterEach(()=>{w?.unmount();vi.unstubAllGlobals();document.body.innerHTML=''})
function editor(props={}){w=mount(Uploader,{props:{purpose:'noticeAttachment',modelValue:[],...props,'onUpdate:modelValue':value=>w.setProps({modelValue:value})},global:{plugins:[ElementPlus]}});return w}
async function choose(files){const input=w.find('input[type=file]');Object.defineProperty(input.element,'files',{value:files,configurable:true});await input.trigger('change');await flushPromises()}
it('uploads multiple notice attachments and emits their IDs while progress never moves backwards',async()=>{
api.upload.mockImplementation(async(file,target,{onProgress})=>{expect(target.purpose).toBe('noticeAttachment');onProgress({phase:'uploading',percent:80});await flushPromises();expect(w.text()).toContain('78%');onProgress({phase:'hashing',percent:10});await flushPromises();expect(w.text()).toContain('78%');return {data:{id:file.name,name:file.name,size:file.size}}});editor();await choose([new File(['a'],'a.txt'),new File(['b'],'b.txt')]);await vi.waitFor(()=>expect(w.props('modelValue').map(f=>f.id),w.text()).toEqual(['a.txt','b.txt']));expect(w.vm.pending).toBe(false);expect(w.emitted('uploaded')).toHaveLength(2)
})
it.each(['noticeAttachment','fileLibrary'])('uploads multiple files over internal HTTP without Web Crypto (%s)',async purpose=>{
vi.stubGlobal('crypto',undefined);api.upload.mockImplementation(async file=>({data:{id:file.name,name:file.name,size:file.size}}));editor({purpose});const apk=new File(['APK'],'app.apk');Object.defineProperty(apk,'size',{value:25*1024*1024});await choose([apk,new File(['guide'],'guide.txt')]);await vi.waitFor(()=>expect(w.props('modelValue').map(f=>f.id)).toEqual(['app.apk','guide.txt']));expect(api.upload).toHaveBeenCalledTimes(2);expect(w.findAll('.upload-job')).toHaveLength(2);expect(w.vm.pending).toBe(false)
})
it('failed uploads remain visible and block publishing until retried or explicitly removed',async()=>{
api.upload.mockRejectedValueOnce(new Error('upload failed')).mockResolvedValueOnce({data:{id:'one',name:'a.txt',size:1}});editor();await choose([new File(['a'],'a.txt')]);expect(w.vm.pending).toBe(true);expect(w.text()).toContain('upload failed');await w.findAll('button').find(b=>b.text()==='重试').trigger('click');await flushPromises();expect(w.vm.pending).toBe(false);expect(w.props('modelValue')[0].id).toBe('one')
})
it('notice editor hides completed transfer history once the attachment list has its file',async()=>{
api.upload.mockResolvedValue({data:{id:'one',name:'a.txt',size:1}});editor({showCompleted:false});await choose([new File(['a'],'a.txt')]);await vi.waitFor(()=>expect(w.props('modelValue')).toHaveLength(1));expect(w.find('.upload-jobs').exists()).toBe(false);expect(w.vm.pending).toBe(false)
})
it('existing attachment count is respected and empty files are rejected',async()=>{
editor({modelValue:[{id:'old'}],limit:1});await choose([new File(['a'],'a.txt')]);expect(api.upload).not.toHaveBeenCalled();w.unmount();editor();await choose([new File([],'empty.txt')]);expect(api.upload).not.toHaveBeenCalled()
})
it('notice readers download attachments without editable controls and editors remove links in their draft',async()=>{
const file={id:'one',name:'说明.pdf',size:2};w=mount(Attachments,{props:{modelValue:[file]},global:{plugins:[ElementPlus]}});await w.find('.attachment-name').trigger('click');await flushPromises();expect(api.download).toHaveBeenCalledWith(file,expect.anything());expect(w.text()).not.toContain('移除');w.unmount();w=mount(Attachments,{props:{modelValue:[file],editable:true},global:{plugins:[ElementPlus]}});await w.findAll('button').find(b=>b.text()==='移除').trigger('click');expect(w.emitted('update:modelValue')).toEqual([[[]]])
})
it('file search preserves filters, resets page and cancels superseded list requests',async()=>{
w=mount(Library,{global:{plugins:[ElementPlus],stubs:{BusinessListPage:{template:'<div><slot name="header"/></div>'},Pagination:true,BusinessTable:true}}});await flushPromises();expect(api.list).toHaveBeenCalledWith(expect.objectContaining({page:1,size:20}),expect.anything());const state=w.vm.$.setupState;state.query.keyword='说明';state.query.page=4;state.search();await flushPromises();expect(api.list).toHaveBeenLastCalledWith(expect.objectContaining({keyword:'说明',page:1}),expect.anything())
})
it('removing a paused file also releases its resumable session, and a 1GB file is accepted without allocating it',async()=>{
const sessionId='11111111-1111-4111-8111-111111111111';api.upload.mockImplementationOnce(async(file,target,{onProgress})=>{onProgress({phase:'uploading',percent:1,sessionId});throw new Error('paused')});editor();const large=new File(['a'],'large.bin');Object.defineProperty(large,'size',{value:1024**3});await choose([large]);expect(api.upload).toHaveBeenCalledTimes(1);await w.findAll('button').find(b=>b.text()==='移除').trigger('click');await flushPromises();expect(api.cancel).toHaveBeenCalledWith(sessionId);expect(w.vm.pending).toBe(false);const tooLarge=new File(['a'],'too-large.bin');Object.defineProperty(tooLarge,'size',{value:1024**3+1});await choose([tooLarge]);expect(api.upload).toHaveBeenCalledTimes(1)
})

View File

@ -0,0 +1,14 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import * as icons from '@element-plus/icons-vue'
import Detail from '@/layout/components/HeaderNotice/DetailView.vue'
const api=vi.hoisted(()=>({get:vi.fn()}))
vi.mock('@/api/system/notice',()=>({getNotice:api.get}))
vi.mock('@/api/system/files',()=>({downloadFile:vi.fn(),fileSize:n=>String(n)}))
let w
afterEach(()=>{w?.unmount();document.body.innerHTML='';vi.resetAllMocks()})
function page(){w=mount(Detail,{attachTo:document.body,global:{plugins:[ElementPlus],components:icons,stubs:{ManagedAttachments:{props:['modelValue'],template:'<div class="attachment-fixture">{{ modelValue.map(f=>f.name).join() }}</div>'}}}})}
it('opening a preset notice still fetches its saved attachments and ignores a slower previous notice response',async()=>{
let old;api.get.mockImplementationOnce(()=>new Promise(resolve=>{old=resolve})).mockResolvedValueOnce({data:{noticeId:2,noticeTitle:'第二份公告',noticeContent:'内容',status:'0',attachments:[{id:'two',name:'操作手册.pdf'}]}});page();w.vm.open({noticeId:1,noticeTitle:'旧公告',noticeContent:'已有列表内容'});await w.vm.open({noticeId:2,noticeContent:'列表内容'});await flushPromises();expect(api.get).toHaveBeenCalledTimes(2);expect(document.body.textContent).toContain('操作手册.pdf');old({data:{noticeId:1,noticeTitle:'迟到的内容',attachments:[]}});await flushPromises();expect(document.body.textContent).toContain('操作手册.pdf');expect(document.body.textContent).not.toContain('迟到的内容')
})

View File

@ -0,0 +1,24 @@
import {afterEach,expect,it} from 'vitest'
import {mount} from '@vue/test-utils'
import Content from '@/components/NoticeContent/index.vue'
let w
afterEach(()=>w?.unmount())
it('preserves ordered steps, bullet points, indentation and inline emphasis from the editor',()=>{
w=mount(Content,{props:{html:'<p><strong>使用说明:</strong></p><ol><li>第一步</li><li>第二步</li><li class="ql-indent-1">子步骤</li></ol><ul><li>补充说明</li></ul>'}})
expect(w.classes()).toContain('ql-editor');expect(w.findAll('ol>li')).toHaveLength(3);expect(w.findAll('ul>li')).toHaveLength(1);expect(w.find('li.ql-indent-1').text()).toBe('子步骤');expect(w.find('strong').text()).toBe('使用说明:')
})
it('preserves Quill mixed-list markers and checklist metadata',()=>{
w=mount(Content,{props:{html:'<ol><li data-list="ordered"><span class="ql-ui"></span>编号</li><li data-list="bullet">圆点</li></ol><ul data-checked="true"><li>核对项</li></ul>'}})
expect(w.find('li[data-list="ordered"]').exists()).toBe(true);expect(w.find('li[data-list="bullet"]').exists()).toBe(true);expect(w.find('ul[data-checked="true"]').exists()).toBe(true)
})
it('removes executable elements, event handlers and unsafe links while retaining the readable formatting',()=>{
w=mount(Content,{props:{html:'<p onclick="bad()">正文</p><script>hidden</script><iframe src="https://example.com">hidden frame</iframe><a href="javascript:bad()">坏链接</a><img src="x" onerror="bad()"><svg onload="bad()"/><form><input name="password"></form>'}})
expect(w.find('script,iframe,svg,form,input,[onclick],[onerror],[onload]').exists()).toBe(false);expect(w.find('a').attributes('href')).toBeUndefined();expect(w.text()).toContain('正文');expect(w.text()).not.toContain('hidden')
})
it('retains editor colors and alignment but excludes page layout CSS and unrelated classes',()=>{
w=mount(Content,{props:{html:'<p class="ql-align-center malicious-page-class" style="color:red;background-color:rgb(255,255,0);font-size:16px;position:fixed;inset:0;background-image:url(https://example.com)">彩色说明</p><a href="https://example.com">说明链接</a>'}})
const p=w.find('p');expect(p.classes()).toEqual(['ql-align-center']);expect(p.element.style.color).toBe('red');expect(p.element.style.fontSize).toBe('16px');expect(p.element.style.position).toBe('');expect(p.element.style.backgroundImage).toBe('');expect(w.find('a').attributes()).toMatchObject({target:'_blank',rel:'noopener noreferrer'})
})
it('keeps plain text paragraphs usable and handles empty notices',()=>{
w=mount(Content,{props:{html:'第一行\n第二行'}});expect(w.text()).toContain('第一行\n第二行');w.unmount();w=mount(Content,{props:{html:''}});expect(w.text()).toBe('暂无正文')
})

View File

@ -0,0 +1,2 @@
import test from 'node:test';import assert from 'node:assert/strict';import {sortPeople} from '../../src/utils/person-order.js';
test('selected and newly queried people merge in pinyin order, with stable account/id ties and no source mutation',()=>{const rows=[{id:5,name:'张三'},{id:4,name:'王五'},{id:3,name:'李四'},{id:2,name:'陈六'},{id:1,name:'阿明'},{id:7,name:'王五',account:'b'},{id:6,name:'王五',account:'a'}];const before=structuredClone(rows);assert.deepEqual(sortPeople(rows).map(p=>p.id),[1,2,3,4,6,7,5]);assert.deepEqual(rows,before);assert.deepEqual(sortPeople([{userId:2,nickName:'张三'},{userId:1,nickName:'李四'}]).map(p=>p.userId),[1,2]);});

View File

@ -0,0 +1,19 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { canViewPurchaseQuotes as web } from '../../src/utils/purchase-quote-permission.js'
import { canViewPurchaseQuotes as app } from '../../../mobile-app/src/core/purchase-quote-permission.ts'
test('web and app grant quote visibility only to the purchase role or user 1', () => {
const scenarios = [
{ id: 21, roles: [], permissions: ['warehouse:purchase:manage'], expected: false },
{ id: 21, roles: [], permissions: ['*:*:*'], expected: false },
{ id: 21, roles: ['admin'], permissions: ['*:*:*'], expected: false },
{ id: 21, roles: ['purchase_manager'], permissions: [], expected: true },
{ id: 1, roles: [], permissions: [], expected: true },
{ id: null, roles: null, permissions: [], expected: false }
]
for (const { id, roles, permissions, expected } of scenarios) {
assert.equal(web(id, roles, permissions), expected)
assert.equal(app(id, roles, permissions), expected)
}
})

View File

@ -0,0 +1,38 @@
-- target-database: cmvr-project-dev
-- Development only. Add file metadata, notice links and an unassigned permission menu.
CREATE TABLE IF NOT EXISTS sys_managed_file (
id char(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY,
file_kind varchar(16) CHARACTER SET ascii NOT NULL,
name varchar(180) NOT NULL,
byte_size bigint NOT NULL,
sha256 char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
owner_id bigint NOT NULL,
create_by varchar(64) NOT NULL,
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
deleted tinyint NOT NULL DEFAULT 0,
delete_time datetime NULL,
KEY idx_managed_file_list(file_kind,deleted,create_time,id),
KEY idx_managed_file_owner(owner_id,file_kind,deleted),
CONSTRAINT ck_managed_file_kind CHECK(file_kind IN ('LIBRARY','NOTICE')),
CONSTRAINT ck_managed_file_size CHECK(byte_size>0 AND byte_size<=1073741824)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS sys_notice_attachment (
notice_id int NOT NULL,
file_id char(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
sort_order int NOT NULL DEFAULT 0,
PRIMARY KEY(notice_id,file_id),
UNIQUE KEY uk_notice_attachment_file(file_id),
CONSTRAINT fk_notice_attachment_notice FOREIGN KEY(notice_id) REFERENCES sys_notice(notice_id) ON DELETE CASCADE,
CONSTRAINT fk_notice_attachment_file FOREIGN KEY(file_id) REFERENCES sys_managed_file(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
SELECT '文件管理',0,8,'file-library','system/file/index',1,0,'C','0','0','system:file:list','documentation','admin',now()
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE perms='system:file:list');
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
SELECT v.label,p.menu_id,v.sort_order,'',1,0,'F','0','0',v.permission,'#','admin',now()
FROM sys_menu p JOIN (
SELECT '上传文件' label,1 sort_order,'system:file:upload' permission UNION ALL
SELECT '下载文件',2,'system:file:download' UNION ALL
SELECT '删除本人文件',3,'system:file:remove' UNION ALL
SELECT '管理全部文件',4,'system:file:manage'
) v WHERE p.perms='system:file:list' AND NOT EXISTS(SELECT 1 FROM sys_menu x WHERE x.perms=v.permission);