feat: 完善采购协同、到货照片及验收发票流程

优化采购实时编辑与权限,支持先到货后补报价、按批次补录照片和批量附件上传。更新验收报告模板及明细选择,增加验收发票独立管理和付款前置校验。完善 BOM 数据权限及 App 更新兼容性。
This commit is contained in:
lixiaolong 2026-11-23 14:41:23 +08:00
parent 0238d8198e
commit 771574fef7
152 changed files with 2196 additions and 619 deletions

View File

@ -5,9 +5,9 @@ module.exports = () => {
return {
name: env.variant === 'prod' ? '设备科综合管理系统' : '设备科综合管理系统·开发',
icon: `./assets/brand/app-icon-blue-${env.variant}.png`,
slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.2', orientation: 'portrait', userInterfaceStyle: 'automatic',
slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.4', orientation: 'portrait', userInterfaceStyle: 'automatic',
platforms: ['android', 'web'],
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 7,
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 9,
adaptiveIcon: { foregroundImage: `./assets/brand/app-icon-blue-${env.variant}-adaptive.png`, backgroundColor: '#ffffff' },
permissions: ['android.permission.REQUEST_INSTALL_PACKAGES'], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
plugins: ['./plugins/with-apk-installer.cjs', 'expo-sharing', 'expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }],

View File

@ -1,6 +1,6 @@
[
"修复旧版本安装检查误报,增加官方浏览器升级入口。",
"到货记录支持补录照片,已验收的历史记录也可补拍或从相册上传。",
"新登记到货至少需要1张照片,上传完成后再提交。",
"补录照片自动保存,保留原照片及上传记录;每次最多9张、单张不超过20MB。"
"到货照片按真实图片内容识别,不再因后缀不一致上传失败。",
"网页兼容苹果HEIC/HEIF原图,本地自动转换后上传。",
"增加GIF、BMP、TIFF等常见图片格式兼容。",
"手机相册优先使用兼容格式,保留批量补录和失败重试。"
]

View File

@ -59,7 +59,7 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
const [unreadMessages,setUnreadMessages]=useState({count:0,exact:true});const messageSerial=useRef(0);
const entry=stack[stack.length-1],page=entry?.key;
const scope=server+'|'+String(user?.user.userId||'anonymous');
const epoch=useRef(0),leave=useRef<LeaveGuard|null>(null);
const epoch=useRef(0),leave=useRef<LeaveGuard|null>(null),restoreController=useRef<AbortController|null>(null);
const bindLeave=useCallback((guard:LeaveGuard|null)=>{leave.current=guard;},[]);
const reset=useCallback(()=>{epoch.current++;messageSerial.current++;setUnreadMessages({count:0,exact:true});setUser(null);setTab('home');setStack([]);setAiVisited(false);leave.current=null;void storage.clear();},[storage]);
const api=useMemo(()=>variant==='dev'?connectionClient(server,reset,Platform.OS==='web'?globalThis.location.origin:undefined):new ApiClient(Platform.OS==='web'?base:server,reset),[reset,server]);
@ -82,10 +82,11 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
epoch.current++;api.clear();
}
const connection=variant==='dev'?<ServerConnection address={server} onSave={changeServer}/>:<ProductionConnection address={server} onSave={changeServer}/>;
const identity=useCallback(async()=>{const [info,routes]=await Promise.all([api.request<User>('/getInfo'),api.request<Row>('/getRouters')]);return {...info,pages:routeComponents(routes.data||[])};},[api]);
useEffect(()=>{let alive=true;const current=epoch.current;
void storage.get().then(async token=>{if(!alive||!token)return;api.authenticate(token);try{const data=await identity();if(alive&&epoch.current===current)setUser(data);}catch{api.clear();await storage.clear();}})
.catch(()=>{}).finally(()=>{if(alive)setStarting(false);});return()=>{alive=false;};},[api,identity]);
const identity=useCallback(async(signal?:AbortSignal)=>{const [info,routes]=await Promise.all([api.request<User>('/getInfo',{signal}),api.request<Row>('/getRouters',{signal})]);return {...info,pages:routeComponents(routes.data||[])};},[api]);
useEffect(()=>{let alive=true;const current=epoch.current,controller=new AbortController();restoreController.current=controller;
const timeout=setTimeout(()=>{controller.abort();if(alive)setStarting(false);},8000);
void storage.get().then(async token=>{if(!alive||controller.signal.aborted||!token)return;api.authenticate(token);try{const data=await identity(controller.signal);if(alive&&!controller.signal.aborted&&epoch.current===current)setUser(data);}catch(error){if(alive&&!controller.signal.aborted){api.clear();if([401,403].includes((error as {code:number}).code))await storage.clear();}}})
.catch(()=>{}).finally(()=>{clearTimeout(timeout);if(alive)setStarting(false);});return()=>{alive=false;controller.abort();clearTimeout(timeout);};},[api,identity]);
const back=useCallback(()=>{const proceed=()=>{Keyboard.dismiss();setStack(old=>old.slice(0,-1));};if(leave.current)leave.current(proceed);else proceed();},[]);
useEffect(()=>{const sub=BackHandler.addEventListener('hardwareBackPress',()=>{if(page){back();return true;}if(tab!=='home'){setTab('home');return true;}return false;});return()=>sub.remove();},[page,tab,back]);
useEffect(()=>{const show=Keyboard.addListener('keyboardDidShow',()=>setKeyboard(true)),hide=Keyboard.addListener('keyboardDidHide',()=>setKeyboard(false));return()=>{show.remove();hide.remove();};},[]);
@ -100,7 +101,7 @@ function Root({server,saveServer,updates}:{server:string;saveServer:(value:strin
const titles:Record<string,string>={home:'工作台',business:'业务中心',assistant:'AI 助手',me:'我的',messages:'消息中心',profile:'个人资料',password:'账号与密码',feedback:'问题与建议','feedback-list':'我的反馈',settings:'设置',about:'关于应用'};
const tabs:[string,string,IconName][]=[['home','工作台','grid-outline'],['business','业务','layers-outline'],...(ai?[['assistant','AI','sparkles-outline'] as [string,string,IconName]]:[]),['me','我的','person-outline']];
return <SafeAreaView style={[s.fill,{backgroundColor:!user?'#06152b':t.bg,width:'100%',alignSelf:'center',...(Platform.OS==='web'?{maxWidth:480}:{})}]}><StatusBar style={!user||t.bg==='#101722'?'light':'dark'}/>
{starting?<View style={[s.page,{flex:1,justifyContent:'center'}]}><ActivityIndicator/><Heading>正在连接你的工作空间</Heading><Note>正在恢复登录并核对当前账号信息,请稍候。</Note></View>:
{starting?<ScrollView contentContainerStyle={[s.page,{flexGrow:1,justifyContent:'center'}]}><Card><ActivityIndicator/><Heading>正在恢复登录</Heading><Note>连接不上时,可直接切换网络或返回登录。</Note><Button title="返回登录" secondary onPress={()=>{restoreController.current?.abort();setStarting(false);}}/></Card>{connection}</ScrollView>:
!user?<Login api={api} onLogin={login} server={server} connection={connection}/>:<>
<View style={{paddingHorizontal:12,paddingVertical:7,minHeight:56,backgroundColor:t.bg,flexDirection:'row',alignItems:'center',gap:8}}>
{page&&<Pressable accessibilityRole="button" accessibilityLabel="返回上一页" onPress={back} style={{padding:12}}><Icon name="chevron-back" color={t.text}/></Pressable>}

View File

@ -1,20 +1,32 @@
import React,{useEffect,useState} from 'react';
import {ActivityIndicator,Linking,Pressable,ScrollView,Text,View} from 'react-native';
import React,{useEffect,useRef,useState} from 'react';
import {ActivityIndicator,Pressable,ScrollView,Text,View} from 'react-native';
import {SafeAreaProvider,SafeAreaView} from 'react-native-safe-area-context';
import {getOfficialPackage,officialPackageUrl,type OfficialAppPackage} from './core/official-app-update';
import * as FileSystem from 'expo-file-system/legacy';
import * as SecureStore from 'expo-secure-store';
import {getOfficialPackage,officialAppOrigin,officialAppInternalOrigin,officialDownloadOrigin,type OfficialAppPackage} from './core/official-app-update';
import {downloadLegacyPackage} from './core/legacy-package-download';
/** Recovery entry for signed OTA channels whose APK predates the installer bridge. */
/** Compatibility entry: verified download inside the app, then Android performs the signed upgrade. */
export default function LegacyUpgrade(){
const [release,setRelease]=useState<OfficialAppPackage|null>(null),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[busy,setBusy]=useState(false);
useEffect(()=>{let alive=true;const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);setError('');setRelease(null);void getOfficialPackage(controller.signal).then(value=>{if(alive)setRelease(value);}).catch(()=>{if(alive)setError('暂时无法连接下载服务,请联网后重试。');}).finally(()=>clearTimeout(timer));return()=>{alive=false;controller.abort();clearTimeout(timer);};},[attempt]);
async function open(){if(!release||busy)return;setBusy(true);setError('');try{await Linking.openURL(officialPackageUrl(release));}catch{setError('未能打开浏览器,请确认手机已安装浏览器后重试。');}finally{setBusy(false);}}
const [release,setRelease]=useState<OfficialAppPackage|null>(null),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[busy,setBusy]=useState(false),[progress,setProgress]=useState(0),[phase,setPhase]=useState('正在下载');
const origin=useRef(officialAppOrigin),ctl=useRef<AbortController|null>(null),alive=useRef(true),locked=useRef(false);
const [selectedOrigin,setSelectedOrigin]=useState(officialAppOrigin);
useEffect(()=>{alive.current=true;const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);setError('');setRelease(null);
void(async()=>{const selected=await SecureStore.getItemAsync('cmvr.prod.connection').catch(()=>null);if(controller.signal.aborted)throw Error('取消检查');try{origin.current=officialDownloadOrigin((selected||officialAppOrigin).replace(/\/prod-api$/,''));}catch{origin.current=officialAppOrigin;}if(alive.current)setSelectedOrigin(origin.current);return getOfficialPackage(controller.signal,undefined,fetch,origin.current);})().then(value=>{if(alive.current&&!controller.signal.aborted)setRelease(value);}).catch(()=>{if(alive.current&&!controller.signal.aborted)setError('暂时无法连接更新服务,请检查当前内网或外网连接后重试。');}).finally(()=>clearTimeout(timer));
return()=>{alive.current=false;controller.abort();ctl.current?.abort();clearTimeout(timer);};},[attempt]);
async function install(){if(!release||locked.current)return;locked.current=true;setBusy(true);setError('');setProgress(0);const controller=new AbortController();ctl.current=controller;
try{const uri=await downloadLegacyPackage(release,origin.current,FileSystem,controller.signal,(stage,value)=>{if(alive.current){setPhase(stage==='verifying'?'正在校验':'正在下载');setProgress(value);}});if(controller.signal.aborted||!alive.current)return;const {File}=await import('expo-file-system');await new File(uri).preview({mimeType:'application/vnd.android.package-archive'});}
catch(e){if(alive.current)setError(e instanceof Error?e.message:'更新未完成,请重试。');}finally{locked.current=false;if(alive.current)setBusy(false);}
}
async function changeConnection(value:string){if(busy)return;try{await SecureStore.setItemAsync('cmvr.prod.connection',officialDownloadOrigin(value)+'/prod-api');setSelectedOrigin(value);setAttempt(n=>n+1);}catch{setError('未能保存连接方式,请重试。');}}
return <SafeAreaProvider><SafeAreaView style={{flex:1,backgroundColor:'#f4f7fc'}}><ScrollView contentContainerStyle={{flexGrow:1,justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:420,alignSelf:'center',backgroundColor:'#fff',padding:24,borderRadius:20,gap:18}}>
<Text allowFontScaling={false} style={{fontSize:13,color:'#3563d9'}}>设备科综合管理系统</Text><Text allowFontScaling={false} style={{fontSize:21,fontWeight:'700',color:'#182337'}}>升级至正式新版</Text>
<Text allowFontScaling={false} style={{fontSize:14,lineHeight:23,color:'#526174'}}>当前旧版本需要通过浏览器下载安装包,再由手机系统完成安装。直接覆盖安装即可,无需卸载原应用。</Text>
<View style={{flexDirection:'row',gap:10}}>{[[officialAppOrigin,'外网'],[officialAppInternalOrigin,'公司内网']].map(([value,label])=><Pressable key={value} accessibilityRole="button" accessibilityLabel={label} accessibilityState={{selected:selectedOrigin===value,disabled:busy}} disabled={busy} onPress={()=>void changeConnection(value)} style={{flex:1,padding:12,borderRadius:8,alignItems:'center',backgroundColor:selectedOrigin===value?'#3563d9':'#edf2fb'}}><Text allowFontScaling={false} style={{color:selectedOrigin===value?'#fff':'#3563d9'}}>{label}</Text></Pressable>)}</View>
<Text allowFontScaling={false} style={{fontSize:14,lineHeight:23,color:'#526174'}}>安装包在应用内下载,沿用本机保存的内网或外网连接,下载完成后由手机系统确认安装。</Text>
{release?<><Text allowFontScaling={false} style={{fontSize:14,fontWeight:'600',color:'#182337'}}>版本 {release.versionName} · {(release.size/1024**2).toFixed(1)} MB</Text>{release.notes.map((note,index)=><Text key={index} allowFontScaling={false} style={{fontSize:13,lineHeight:21,color:'#526174'}}>• {note}</Text>)}</>:!error?<ActivityIndicator color="#3563d9"/>:null}
{busy&&<View style={{gap:8}}><Text allowFontScaling={false} style={{color:'#526174'}}>{phase} {progress}%</Text><View accessibilityRole="progressbar" accessibilityValue={{min:0,max:100,now:progress}} style={{height:7,backgroundColor:'#e5ebf5',borderRadius:4,overflow:'hidden'}}><View style={{width:`${progress}%`,height:7,backgroundColor:'#3563d9'}}/></View></View>}
{!!error&&<Text accessibilityRole="alert" allowFontScaling={false} style={{fontSize:13,lineHeight:21,color:'#bc3345'}}>{error}</Text>}
<Pressable accessibilityRole="button" accessibilityLabel="浏览器下载安装" disabled={!release||busy} onPress={()=>void open()} style={{backgroundColor:!release||busy?'#aac0f3':'#3563d9',paddingVertical:14,borderRadius:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#fff',fontWeight:'600',fontSize:15}}>{busy?'正在打开…':'浏览器下载安装'}</Text></Pressable>
<Pressable accessibilityRole="button" accessibilityLabel="重新检查" onPress={()=>setAttempt(n=>n+1)} style={{padding:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#3563d9',fontSize:13}}>重新检查</Text></Pressable>
<Text allowFontScaling={false} style={{fontSize:12,lineHeight:20,color:'#7a8697'}}>下载后在浏览器中打开安装包;如有提示,允许浏览器安装应用。账号和原有数据无需重新录入。</Text>
<Pressable accessibilityRole="button" accessibilityLabel={busy?'取消下载':'下载并安装'} disabled={!release} onPress={()=>{if(busy)ctl.current?.abort();else void install();}} style={{backgroundColor:!release?'#aac0f3':'#3563d9',paddingVertical:14,borderRadius:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#fff',fontWeight:'600',fontSize:15}}>{busy?'取消下载':'下载并安装'}</Text></Pressable>
{!busy&&<Pressable accessibilityRole="button" accessibilityLabel="重新检查" onPress={()=>setAttempt(n=>n+1)} style={{padding:10,alignItems:'center'}}><Text allowFontScaling={false} style={{color:'#3563d9',fontSize:13}}>重新检查</Text></Pressable>}
</View></ScrollView></SafeAreaView></SafeAreaProvider>;
}

View File

@ -1,12 +1,11 @@
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {ActivityIndicator,AppState,DeviceEventEmitter,Linking,Modal,NativeModules,Platform,ScrollView,View} from 'react-native';
import {ActivityIndicator,AppState,DeviceEventEmitter,Modal,NativeModules,Platform,ScrollView,View} from 'react-native';
import Constants from 'expo-constants';
import * as Application from 'expo-application';
import {Directory,File,FileMode,Paths} from 'expo-file-system';
import {fetch as expoFetch} from 'expo/fetch';
import type {ApiClient} from './core/network';
import {newerPackage,packageVerifier,createPackageDownloadProcessor,verifyInstalledPackage,packageInstallError,type PackageRelease} from './core/package-update';
import {getOfficialPackage,officialPackageUrl} from './core/official-app-update';
import {nativePackageDownload,downloadMeter} from './core/native-package-download';
import {readPreference,savePreference} from './core/preferences';
import {ignoredPackageMatches} from './core/package-cache';
@ -22,7 +21,6 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
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 legacyInstaller=environment==='prod'&&Number.isInteger(current)&&current>=1&&current<=6;
const available=enabled&&Platform.OS==='android'&&Number.isInteger(current)&&current>0;
const check=useCallback(async(force=false):Promise<PackageCheckResult|undefined>=>{
if(!available||busy.current||!force&&Date.now()-last.current<15*60*1000)return;
@ -47,7 +45,7 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
finally{if(valid()){busy.current=false;setChecked(true);setPhase(file.current?'ready':'idle');}}
},[api,available,current,environment,scope]);
useEffect(()=>{generation.current++;busy.current=false;shown.current='';last.current=0;file.current=null;fileHash.current='';setRelease(null);setVisible(false);setPhase('idle');setError('');setIgnored(false);setChecked(false);void check();const listener=AppState.addEventListener('change',state=>{if(state==='active')void check();});return()=>{generation.current++;ctl.current?.abort();listener.remove();};},[scope,check]);
async function download(){if(!release||busy.current)return;if(legacyInstaller){await recover();return;}const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);setVerifyProgress(0);setTransfer({bytes:0,total:release.size,bytesPerSecond:0,remainingSeconds:null,connections:1});const meter=downloadMeter(),abort=new AbortController();ctl.current=abort;let output:File|null=null;
async function download(){if(!release||busy.current)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);setVerifyProgress(0);setTransfer({bytes:0,total:release.size,bytesPerSecond:0,remainingSeconds:null,connections:1});const meter=downloadMeter(),abort=new AbortController();ctl.current=abort;let output:File|null=null;
try{const dir=new Directory(Paths.cache,'app-updates');dir.create({idempotent:true,intermediates:true});output=new File(dir,release.sha256+'-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.apk');output.create();
const bridge=NativeModules.CmvrApkVerification;
if(typeof bridge?.download==='function'&&typeof bridge?.cancelDownload==='function'){
@ -69,7 +67,6 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
}
async function install(){
if(!file.current||!release||busy.current)return;
if(legacyInstaller){await recover();return;}
const run=generation.current,valid=()=>generation.current===run,abort=new AbortController();ctl.current=abort;
busy.current=true;setError('');setPhase('installing');await new Promise<void>(resolve=>setTimeout(resolve,0));
try{
@ -85,12 +82,6 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
}catch(error){if(valid()&&!abort.signal.aborted)setError(packageInstallError(error));}
finally{if(valid()){busy.current=false;if(file.current)setPhase('ready');}}
}
async function recover(){
if(!release||environment!=='prod'||busy.current)return;const run=generation.current,valid=()=>run===generation.current,abort=new AbortController();ctl.current=abort;busy.current=true;setError('');setPhase('installing');const timer=setTimeout(()=>abort.abort(),15000);
try{const official=await getOfficialPackage(abort.signal,release);if(valid()&&!abort.signal.aborted)await Linking.openURL(officialPackageUrl(official));}
catch(error){if(valid())setError((error as Error).message||'未能打开官方下载,请稍后重试。');}
finally{clearTimeout(timer);if(valid()){busy.current=false;setPhase(file.current?'ready':'idle');}}
}
function later(){if(['downloading','verifying','restoring'].includes(phase))ctl.current?.abort();setVisible(false);}
async function ignoreVersion(){
if(!release||busy.current)return;const run=generation.current;busy.current=true;
@ -98,7 +89,7 @@ export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
catch{if(generation.current===run)setError('未能保存忽略设置,请重试');}
finally{if(generation.current===run)busy.current=false;}
}
return {release,visible,legacyInstaller,phase,progress,transfer,verifyProgress,error,available,ignored,checked,canRecover:environment==='prod'&&!!release,recover:()=>void recover(),check:()=>check(true),download:()=>void download(),install:()=>void install(),ignoreVersion:()=>void ignoreVersion(),later};
return {release,visible,phase,progress,transfer,verifyProgress,error,available,ignored,checked,check:()=>check(true),download:()=>void download(),install:()=>void install(),ignoreVersion:()=>void ignoreVersion(),later};
}
export type PackageControls=ReturnType<typeof usePackageUpdates>;
function PackageTransferProgress({control:c}:{control:PackageControls}){
@ -118,12 +109,11 @@ export function PackageUpdateDialog({control:c}:{control:PackageControls}){
<UpdateNotes notes={c.release.notes}/>
{['downloading','verifying'].includes(c.phase)&&<PackageTransferProgress control={c}/>}
{c.phase==='restoring'&&<View style={{flexDirection:'row',alignItems:'center',gap:10}}><ActivityIndicator color={t.accent}/><Note>正在核对本地安装包…</Note></View>}
{c.phase==='ready'&&<Note>下载完成,可直接安装。</Note>}{c.legacyInstaller&&<Note>当前旧版将通过浏览器下载安装包,再由手机系统完成更新,无需先卸载。</Note>}
{c.phase==='ready'&&<Note>下载完成,可直接安装。</Note>}
{c.phase==='installing'&&<Note>正在验证安装包,请稍候…</Note>}
{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}
</ScrollView>
{!busy&&<Button title={c.legacyInstaller?'浏览器下载安装':c.phase==='ready'?'立即安装':'立即更新'} onPress={c.phase==='ready'?c.install:c.download}/>}
{!busy&&!!c.error&&c.canRecover&&!c.legacyInstaller&&<Button title="浏览器下载安装" secondary onPress={c.recover}/>}
{!busy&&<Button title={c.phase==='ready'?'立即安装':'立即更新'} onPress={c.phase==='ready'?c.install:c.download}/>}
<View style={{flexDirection:'row',gap:10}}><Button style={{flex:1,paddingHorizontal:8}} title={['downloading','verifying'].includes(c.phase)?'取消下载':'稍后再说'} secondary onPress={c.later}/>{!busy&&<Button style={{flex:1,paddingHorizontal:8}} title="忽略此版本" secondary onPress={c.ignoreVersion}/>}</View>
</View></View>
</Modal>;

View File

@ -15,19 +15,11 @@ export function arrivalActions(row: Row, permissions: string[], queue: ArrivalKi
const common = row.editable===false ? '只能办理自己创建的采购明细,或自己创建的批次中的明细。'
: !canOperate ? '当前账号可查看这条记录;需要办理时,请联系采购负责人协助。'
: !positiveId(row.id) ? '记录信息不完整,请刷新后重试。'
: flag(row.historical) ? '这是历史已入库记录,不重复登记到货或验收。'
: number(row.purchaseStatus) === 5 ? '这条采购已取消,不再办理到货或验收。'
: !flag(row.priceLocked) || !(flag(row.quoteAvailable) || Number.isFinite(number(row.finalUnitPrice)) && number(row.finalUnitPrice) >= 0)
? '请先在 Web 采购明细中确认采购、锁定报价,再回到这里刷新办理。' : '';
: flag(row.historical) ? '这是历史已入库记录,不重复登记到货。'
: number(row.purchaseStatus) === 5 ? '这条采购已取消,不再登记到货。' : '';
const registration = common || (!positiveId(row.purchaseBatchId) || !positiveId(row.supplierId)
? '请先在 Web 端选择采购批次和供应商,再回到这里刷新办理。'
: !Number.isFinite(remaining) ? '可登记到货数量尚未获取完整,请刷新后重试。'
: remaining <= 0 ? pending > 0 ? '本次采购已登记到货,请办理验收。' : '没有剩余可登记数量。' : '');
const acceptance = common || (!Number.isFinite(pending) ? '待验收数量尚未获取完整,请刷新后重试。'
: pending <= 0 ? '还没有待验收的到货记录,请先登记到货。' : '');
const action = (kind: ArrivalKind, reason: string): ArrivalAction => ({kind,
title: kind === 'arrival' ? '登记到货' : '验收到货', enabled: !reason, reason});
return queue === 'arrival'
? [action('arrival', registration), ...(pending > 0 ? [action('accept', acceptance)] : [])]
: [action('accept', acceptance), ...(remaining > 0 ? [action('arrival', registration)] : [])];
: remaining <= 0 ? pending > 0 ? '本次采购已登记到货,请到待入库办理。' : '没有剩余可登记数量。' : '');
return [{kind:'arrival',title:'登记到货',enabled:!registration,reason:registration}];
}

View File

@ -4,6 +4,6 @@ import type {ArrivalKind} from './arrival-actions';
// notArrived is deliberately not used: that also includes registered arrivals awaiting acceptance.
export function arrivalListQuery(queue: ArrivalKind) {
return queue === 'arrival'
? {pendingRegistration:true, arrivalReady:true, priceLocked:true}
: {pendingAcceptance:true, priceLocked:true};
? {pendingRegistration:true, arrivalReady:true}
: {pendingAcceptance:true};
}

View File

@ -0,0 +1,22 @@
import {officialPackage,officialDownloadOrigin,type OfficialAppPackage} from './official-app-update.ts';
import {packageVerifier} from './package-update.ts';
type LegacyFiles={cacheDirectory:string|null;getInfoAsync:(uri:string)=>Promise<{exists:boolean;size?:number}>;deleteAsync:(uri:string,options:{idempotent:boolean})=>Promise<void>;readAsStringAsync:(uri:string,options:{encoding:'base64';position:number;length:number})=>Promise<string>;createDownloadResumable:(url:string,uri:string,options:object,onProgress:(value:{totalBytesWritten:number})=>void)=>{downloadAsync:()=>Promise<{status:number;uri:string}|undefined>;pauseAsync:()=>Promise<unknown>};};
/** Older signed runtimes already have the legacy filesystem. Keep downloads inside the app. */
export async function downloadLegacyPackage(value:OfficialAppPackage,origin:string,fs:LegacyFiles,signal:AbortSignal,onProgress:(phase:'downloading'|'verifying',percent:number)=>void){
const release=officialPackage(value),base=officialDownloadOrigin(origin);if(!fs.cacheDirectory)throw Error('手机存储暂不可用');
const uri=fs.cacheDirectory+'cmvr-update-'+release.sha256+'.apk',check=()=>{if(signal.aborted)throw Error('下载已取消');};check();
let info=await fs.getInfoAsync(uri);
if(!info.exists||info.size!==release.size){
const task=fs.createDownloadResumable(base+release.downloadPath,uri,{},event=>onProgress('downloading',Math.min(100,Math.floor(event.totalBytesWritten/release.size*100))));
const cancel=()=>{void task.pauseAsync().catch(()=>{});};signal.addEventListener('abort',cancel,{once:true});
try{check();const result=await task.downloadAsync();check();if(!result||result.status!==200||result.uri!==uri)throw Error('安装包下载未完成,请重试');}finally{signal.removeEventListener('abort',cancel);}
info=await fs.getInfoAsync(uri);
}
check();if(!info.exists||info.size!==release.size)throw Error('安装包下载不完整,请重新下载');
const verifier=packageVerifier(release);onProgress('verifying',0);
for(let offset=0;offset<release.size;offset+=256*1024){
check();const raw=await fs.readAsStringAsync(uri,{encoding:'base64',position:offset,length:Math.min(256*1024,release.size-offset)}),decoded=atob(raw),bytes=Uint8Array.from(decoded,char=>char.charCodeAt(0));
verifier.write(bytes);onProgress('verifying',Math.min(100,Math.floor((offset+bytes.length)/release.size*100)));
}
check();try{verifier.finish();}catch(error){await fs.deleteAsync(uri,{idempotent:true}).catch(()=>{});throw error;}return uri;
}

View File

@ -4,7 +4,7 @@ export type Module = { key: string; title: string; path: string; permissions: st
search: string; titleKey: string; fields: [string, string][]; query?: Row; pages?: string[]; guide?: string };
export const modules: Module[] = [
{key:'files',title:'共享文件',path:'/system/files',permissions:[['system:file:list','system:file:manage']],search:'keyword',titleKey:'name',fields:[]},
{ key:'arrival',title:'到货验收',path:'/warehouse/purchase/list',permissions:[['warehouse:purchase:list','warehouse:purchase:manage'],['warehouse:purchase:edit','warehouse:purchase:manage']],search:'materialName',titleKey:'materialName',guide:'先确认采购、锁定报价,再登记实际到货,逐次验收合格/不合格数量;合格后进入待入库,不会直接增加库存。',fields:[['purchaseBatchNo','采购批次'],['projectName','所属项目'],['materialParams','规格型号'],['quantity','采购数量'],['remainingQuantity','未登记到货'],['pendingArrivalQuantity','待验收'],['unit','单位']] },
{ key:'arrival',title:'到货登记',path:'/warehouse/purchase/list',permissions:[['warehouse:purchase:list','warehouse:purchase:manage'],['warehouse:purchase:edit','warehouse:purchase:manage']],search:'materialName',titleKey:'materialName',guide:'到货时至少上传1张照片,登记后直接转待入库,无需线下验收;未报价也可入库,成本待后续补齐。',fields:[['purchaseBatchNo','采购批次'],['projectName','所属项目'],['materialParams','规格型号'],['quantity','采购数量'],['remainingQuantity','未登记到货'],['pendingArrivalQuantity','历史到货待衔接'],['unit','单位']] },
{ key:'use',title:'物料领用',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'选择本项目库存,核对数量后领用。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'move',title:'移库',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:stock:out'],['project:inventory:use']],search:'productName',titleKey:'productName',guide:'同项目更换存放库区,物品所属项目和总库存数量不变。',fields:[['projectName','所属项目'],['areaName','来源库区'],['stockNum','可用数量'],['unit','单位'],['spec','规格型号']] },
{ key:'count',title:'现场盘点',path:'/warehouse/stock/list',permissions:[['warehouse:stock:list'],['warehouse:check:add']],search:'productName',titleKey:'productName',guide:'填写实际清点数量;登记后生成待确认记录,确认盘点后才调整库存。',fields:[['projectName','所属项目'],['areaName','库区'],['stockNum','账面数量'],['unit','单位'],['spec','规格型号']] },
@ -12,10 +12,10 @@ export const modules: Module[] = [
guide: '这里用于查询;现场领用、移库、盘点请从对应入口办理。可直接办理领用、移库。',
fields: [['projectName','所属项目'],['areaName','库区'],['stockNum','库存数量'],['unit','单位'],['spec','规格型号'],['brand','品牌'],['averageUnitCost','平均单价'],['stockAmount','库存金额']] },
{ key: 'purchase', title: '采购明细', path: '/warehouse/purchase/list', permissions: [['warehouse:purchase:list','warehouse:purchase:manage']], search: 'materialName', titleKey: 'materialName',
guide: '一批采购对应一个项目;确认采购后再登记到货,验收合格后到「待入库」办理入库。',
fields: [['purchaseStatus','采购状态'],['materialParams','规格型号'],['materialBrand','品牌'],['purchaseBatchName','批次名称'],['supplierName','供应商'],['quantity','采购数量'],['unit','单位'],['projectName','所属项目'],['purchaseBatchNo','批次编号'],['finalUnitPrice','报价'],['actualUnitPrice','实际单价(内部参考)'],['actualAmount','实际金额(内部参考)'],['acceptedQuantity','已验收数量'],['remainingQuantity','未到数量']] },
guide: '一批采购对应一个项目;登记到货后到「待入库」办理入库,允许后补报价。',
fields: [['purchaseStatus','采购状态'],['materialParams','规格型号'],['materialBrand','品牌'],['purchaseBatchName','批次名称'],['supplierName','供应商'],['quantity','采购数量'],['unit','单位'],['projectName','所属项目'],['purchaseBatchNo','批次编号'],['finalUnitPrice','报价'],['actualUnitPrice','实际单价(内部参考)'],['actualAmount','实际金额(内部参考)'],['acceptedQuantity','已到货数量'],['remainingQuantity','未到数量']] },
{ key: 'pending', title: '待入库', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 0 },
guide: '采购验收合格或生产完工验收后,记录才会进入待入库;选择实际存放库区并确认后,才计入库存。',
guide: '采购登记到货或生产完工验收后,记录进入待入库;选择实际存放库区并确认后,才计入库存。',
fields: [['sourceProjectName','来源项目'],['purchaseBatchNo','采购批次'],['spec','规格型号'],['inNum','应入库数量'],['receivedQuantity','已入库数量'],['unit','单位'],['sourceNo','来源单号']] },
{ key: 'in', title: '入库记录', path: '/warehouse/in/list', permissions: [['warehouse:in:list']], search: 'keyword', titleKey: 'productName', query: { inStatus: 1 },
fields: [['sourceProjectName','所属项目'],['areaName','库区'],['inNum','入库数量'],['unit','单位'],['businessDate','业务日期'],['inNo','入库单号']] },

View File

@ -1,4 +1,6 @@
export const officialAppOrigin='https://wms.svc.cmvr-iot.icu';
export const officialAppInternalOrigin='http://192.168.28.10';
export function officialDownloadOrigin(value:string){if(value!==officialAppOrigin&&value!==officialAppInternalOrigin)throw Error('安装包服务地址无效');return value;}
export const productionAppSigner='96ab3e7afc5f60668693feec01140bcf13611f73ed9e76fa806bf9657f3d939b';
export type OfficialAppPackage={environment:'prod';packageName:'cn.cmvr.wms';versionCode:number;versionName:string;sha256:string;size:number;signerSha256:string;downloadPath:string;notes:string[]};
export function officialPackage(value:unknown,expected?:{versionCode:number;sha256:string;size:number}):OfficialAppPackage{
@ -8,8 +10,8 @@ export function officialPackage(value:unknown,expected?:{versionCode:number;sha2
return v;
}
/** A public installer contains no account credentials. Android still verifies the APK. */
export async function getOfficialPackage(signal:AbortSignal,expected?:{versionCode:number;sha256:string;size:number},transport:typeof fetch=fetch){
const response=await transport(officialAppOrigin+'/static/mobile/app-upgrade.json?check='+Date.now(),{signal,redirect:'error',cache:'no-store'});
export async function getOfficialPackage(signal:AbortSignal,expected?:{versionCode:number;sha256:string;size:number},transport:typeof fetch=fetch,origin=officialAppOrigin){
const response=await transport(officialDownloadOrigin(origin)+'/static/mobile/app-upgrade.json?check='+Date.now(),{signal,redirect:'error',cache:'no-store'});
if(!response.ok)throw Error('暂时无法获取官方安装包,请检查网络后重试。');
const body=await response.text();if(body.length>8192)throw Error('官方安装包信息无效,请稍后重试。');
return officialPackage(JSON.parse(body),expected);

View File

@ -38,10 +38,10 @@ export function createPackageDownloadProcessor(write:(chunk:Uint8Array)=>void,on
}
/** 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||typeof bridge.verify!=='function')throw new Error('当前旧版缺少安装检查组件,请通过浏览器下载安装正式新版。');
if(!bridge||typeof bridge.verify!=='function')throw new Error('当前旧版缺少安装检查组件,请联系管理员升级安装包。');
if(!/^file:\/\//.test(uri)||!Number.isInteger(version)||version<1||await bridge.verify(uri,version)!==true)throw new Error('无法验证安装包的包名和签名,请改用官方安装包重新安装。');
}
export function packageInstallError(error:unknown){
if(error instanceof Error&&error.message.includes('缺少安装检查组件'))return error.message;
return '应用内安装检查未通过,可改用浏览器下载官方安装包,由手机系统确认安装。';
return '安装包检查未通过,请重新检查更新后重试;仍无法安装时请联系管理员。';
}

View File

@ -28,7 +28,7 @@ type RecordStatus={label:string;tone:'active'|'warning'|'success'|'muted'};
const purchaseStatuses:Record<number,RecordStatus>={0:{label:'待采购',tone:'muted'},1:{label:'已下单',tone:'active'},2:{label:'采购中',tone:'active'},3:{label:'部分到货',tone:'warning'},4:{label:'已到齐',tone:'success'}};
export function purchaseRecordStatus(row:Row):RecordStatus {
if(Number(row.purchaseStatus)===5)return{label:'已取消',tone:'muted'};
if(Number(row.pendingArrivalQuantity)>0)return{label:'待验收',tone:'warning'};
if(Number(row.pendingArrivalQuantity)>0)return{label:'历史待衔接',tone:'warning'};
if(row.purchaseStatus==null||String(row.purchaseStatus).trim()==='')return{label:'待核对',tone:'muted'};
return purchaseStatuses[Number(row.purchaseStatus)]||{label:'待核对',tone:'muted'};
}

View File

@ -4,7 +4,7 @@ export type WorkspaceTask={id:string;key:string;label:string;path:string;query:R
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('arrival')?[{id:'arrival',key:'arrival',label:'待登记到货',path:'/warehouse/purchase/list',query:arrivalListQuery('arrival'),openQuery:{arrivalQueue:'arrival'}}]:[]),
...(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}}]:[])
];

View File

@ -6,11 +6,16 @@ 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];
export async function pickManagedFiles(multiple=true):Promise<UploadSource[]>{
const chosen=await DocumentPicker.getDocumentAsync({type:'*/*',multiple,copyToCacheDirectory:true});if(chosen.canceled)return [];
const sources:UploadSource[]=[];try{for(const asset of chosen.assets)sources.push(managedSource(asset));return sources;}catch(error){sources.forEach(file=>file.close());throw error;}
}
export async function pickManagedFile():Promise<UploadSource|null>{return (await pickManagedFiles(false))[0]||null;}
function managedSource(asset:DocumentPicker.DocumentPickerAsset):UploadSource{
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{}}};
let closed=false;
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(){if(closed)return;closed=true;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);

View File

@ -0,0 +1,33 @@
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {ActivityIndicator,FlatList,Modal,View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import type {ApiClient} from '../core/network';
import {display,type Row} from '../core/modules';
import {Button,Card,Heading,Note,s,useTheme} from '../ui';
import {Text,TextInput} from '../typography';
export function ArrivalBatchBrowser({api,close,renderDetails}:{api:ApiClient;close:()=>void;renderDetails:(batch:Row)=>React.ReactNode}){
const t=useTheme(),[query,setQuery]=useState(''),[rows,setRows]=useState<Row[]>([]),[page,setPage]=useState(1),[total,setTotal]=useState(0),[batch,setBatch]=useState<Row|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState('');
const active=useRef<AbortController|null>(null),serial=useRef(0),busyRef=useRef(false);
const load=useCallback(async(next:number)=>{
if(next>1&&busyRef.current)return;
const id=++serial.current;active.current?.abort();const ctl=new AbortController();active.current=ctl;busyRef.current=true;setBusy(true);setError('');
try{const response=await api.request<Row>('/warehouse/purchase/batch/photo-records',{query:{keyword:query.trim(),pageNum:next,pageSize:20},signal:ctl.signal});if(id!==serial.current)return;
const data=response.data&&Array.isArray(response.data.rows)?response.data:response;
setRows(old=>next===1?data.rows||[]:[...old,...(data.rows||[]).filter((r:Row)=>!old.some(o=>o.id===r.id))]);setPage(next);setTotal(data.total||0);
}catch(e){if(id===serial.current&&!ctl.signal.aborted)setError((e as Error).message);}
finally{if(id===serial.current){busyRef.current=false;setBusy(false);}}
},[api,query]);
useEffect(()=>{setRows([]);setTotal(0);setPage(1);const timer=setTimeout(()=>void load(1),300);return()=>{clearTimeout(timer);++serial.current;active.current?.abort();busyRef.current=false;};},[load]);
return <Modal visible animationType="slide" onRequestClose={()=>batch?setBatch(null):close()}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}>
<View style={[s.row,{padding:14,justifyContent:'space-between'}]}>{batch?<Button title="返回批次" secondary onPress={()=>setBatch(null)}/>:<Heading>按批次补录照片</Heading>}<Button title="关闭" secondary onPress={close}/></View>
{batch?<><View style={{paddingHorizontal:14,paddingBottom:8,gap:5}}><Text style={{fontSize:14,fontWeight:'600',color:t.text}}>{batch.batchName||batch.batchNo}</Text><Note>整批明细均可查询。点击到货记录,选择一次到货后拍照或从相册补传,上传后自动保存。</Note></View>{renderDetails(batch)}</>:<>
<View style={{paddingHorizontal:14,paddingBottom:10,gap:8}}><TextInput accessibilityLabel="搜索批次名称或编号" placeholder="搜索批次名称或编号" placeholderTextColor={t.muted} value={query} onChangeText={setQuery} style={{minHeight:44,borderWidth:1,borderColor:t.line,borderRadius:9,paddingHorizontal:12,fontSize:14,color:t.text,backgroundColor:t.card}}/><Note>包含已到齐、已入库的批次,选择批次查看全部明细。</Note></View>
{!!error&&<View style={{paddingHorizontal:14,gap:6}}><Note>{error}</Note><Button title="重试" secondary onPress={()=>void load(1)}/></View>}
<FlatList data={rows} keyExtractor={item=>String(item.id)} contentContainerStyle={{paddingHorizontal:14,paddingBottom:14,gap:10}} refreshing={busy&&page===1} onRefresh={()=>void load(1)}
ListEmptyComponent={busy?<ActivityIndicator color={t.accent}/>:<Note>{error?'查询失败,请重试':'暂无匹配批次'}</Note>}
renderItem={({item})=><Card style={{padding:12,gap:7}}><Text style={{fontSize:14,fontWeight:'600',color:t.text}}>{item.batchName||item.batchNo||'未命名批次'}</Text><Note>{display(item.supplierName)} · {item.requestCount||0} 条明细</Note><Button title="查看明细 / 补录照片" secondary onPress={()=>setBatch(item)}/></Card>}
ListFooterComponent={rows.length<total?<Button title={`加载更多(剩余 ${total-rows.length} 批)`} secondary busy={busy} onPress={()=>void load(page+1)}/>:undefined}/>
</>}
</SafeAreaView></Modal>;
}

View File

@ -12,12 +12,13 @@ import {purchaseRecordStatus,recordQuantity,recordType} from '../core/record-pre
export function ArrivalHistory({api,row,close,canSupplement=false}:{api:ApiClient;row:Row;canSupplement?:boolean;close:()=>void}){
const editable=canSupplement&&row.editable!==false;
const t=useTheme(),[records,setRecords]=useState<Row[]>([]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[expanded,setExpanded]=useState<number|null>(null);
const t=useTheme(),[records,setRecords]=useState<Row[]>([]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[attempt,setAttempt]=useState(0),[expanded,setExpanded]=useState<number|null>(null),[transferring,setTransferring]=useState<number|null>(null);
useEffect(()=>{const ctl=new AbortController();setLoading(true);setError('');void api.request<Row>(`/warehouse/purchase/arrival/${row.id}`,{signal:ctl.signal}).then(r=>{if(!ctl.signal.aborted)setRecords(r.data||[]);}).catch(e=>{if(!ctl.signal.aborted)setError(e.message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,row.id,attempt]);
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>到货记录</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}><Card style={{padding:12}}><ItemIdentity item={row} purchase quantity={row.quantity??null} quantityLabel="采购数量" status={purchaseRecordStatus(row)}/></Card>
{loading&&<Note>正在读取到货记录…</Note>}{!!error&&<><Note>{error}</Note><Button title="重新加载" secondary onPress={()=>setAttempt(n=>n+1)}/></>}{!loading&&!error&&!records.length&&<Note>暂无到货记录</Note>}
{records.map(record=><Card key={record.id} style={{padding:12,gap:7}}><Text style={{...recordType.body,fontWeight:'600',color:t.text}}>{record.arrivalNo}</Text><RecordMeta label="到货日期" value={formatDateTime(record.arrivalDate)}/><RecordMeta label="到货数量" value={`${recordQuantity(record.arrivalQuantity)} ${row.unit||''}`}/><RecordMeta label="验收状态" value={['待验收','验收通过','拒收','已撤销'][record.acceptanceStatus]||'已撤销'}/>{!!record.remark&&<Note>{record.remark}</Note>}{!!record.acceptanceRemark&&<Note>验收说明:{record.acceptanceRemark}</Note>}
<Button title={expanded===record.id?'收起照片':editable?`查看 / 补录照片(${(record.photos||[]).length})`:`查看到货照片(${(record.photos||[]).length})`} secondary onPress={()=>setExpanded(expanded===record.id?null:record.id)}/>{expanded===record.id&&<ArrivalPhotos api={api} requestId={row.id} arrivalId={record.id} photos={record.photos||[]} readonly supplemental={editable} onChange={photos=>setRecords(items=>items.map(item=>item.id===record.id?{...item,photos}:item))}/>}
{records.map(record=><Card key={record.id} style={{padding:12,gap:7}}><Text style={{...recordType.body,fontWeight:'600',color:t.text}}>{record.arrivalNo}</Text><RecordMeta label="到货日期" value={formatDateTime(record.arrivalDate)}/><RecordMeta label="到货数量" value={`${recordQuantity(record.arrivalQuantity)} ${row.unit||''}`}/><RecordMeta label="到货状态" value={['历史到货待转入库','已登记','历史拒收','已撤销'][record.acceptanceStatus]||'已撤销'}/>{!!record.remark&&<Note>{record.remark}</Note>}{!!record.acceptanceRemark&&<Note>历史处理说明:{record.acceptanceRemark}</Note>}
{editable&&Number(record.acceptanceStatus)===0&&<Button title="转待入库" secondary busy={transferring===record.id} disabled={transferring!==null} onPress={()=>{if(transferring!==null)return;setTransferring(record.id);setError('');void api.request(`/warehouse/purchase/arrival/${record.id}/ready-for-inbound`,{method:'PUT'}).then(()=>setAttempt(n=>n+1)).catch(e=>setError(e.message)).finally(()=>setTransferring(null));}}/>}
<Button title={expanded===record.id?'收起照片':editable?((record.photos||[]).length?`查看 / 补传照片(${record.photos.length})`:'补传照片(未上传)'):`查看到货照片(${(record.photos||[]).length})`} secondary onPress={()=>setExpanded(expanded===record.id?null:record.id)}/>{expanded===record.id&&<ArrivalPhotos api={api} requestId={row.id} arrivalId={record.id} photos={record.photos||[]} readonly supplemental={editable} onChange={photos=>setRecords(items=>items.map(item=>item.id===record.id?{...item,photos}:item))}/>}
</Card>)}
</ScrollView></SafeAreaView></Modal>;
}

View File

@ -20,13 +20,6 @@ export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,rese
}){
const t=useTheme();
return <View style={{paddingHorizontal:14,paddingTop:8,paddingBottom:8,gap:8}}>
<View accessibilityRole="tablist" style={{flexDirection:'row',padding:4,borderRadius:12,backgroundColor:t.soft,gap:4}}>
{([['arrival','待登记到货'],['accept','待验收']] as const).map(([key,label])=><Pressable key={key} accessibilityRole="tab" accessibilityLabel={label}
accessibilityState={{selected:queue===key,disabled:busy}} disabled={busy} onPress={()=>setQueue(key)}
style={{flex:1,minHeight:44,paddingVertical:9,paddingHorizontal:6,borderRadius:9,alignItems:'center',justifyContent:'center',backgroundColor:queue===key?t.card:'transparent'}}>
<Text style={{color:queue===key?t.accent:t.muted,fontSize:14,lineHeight:22,fontWeight:queue===key?'700':'500',textAlign:'center'}}>{label}</Text>
</Pressable>)}
</View>
<View style={{flexDirection:'row',alignItems:'center',gap:8}}>
<View style={{flex:1,minWidth:0,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:10,backgroundColor:t.card,paddingLeft:11}}>
<Icon name="search-outline" size={18} color={t.muted}/>
@ -45,7 +38,7 @@ export function ArrivalListTools({query,setQuery,queue,setQueue,busy,search,rese
export function ArrivalCard({item,queue,children}:{item:Row;queue:ArrivalKind;children:React.ReactNode}){
const t=useTheme(),key=queue==='accept'?'pendingArrivalQuantity':'remainingQuantity';
return <Card style={{padding:12,gap:9}}>
<ItemIdentity item={item} purchase quantity={item[key]??null} quantityLabel={queue==='accept'?'待验收数量':'可登记到货数量'} status={purchaseRecordStatus(item)}/>
<ItemIdentity item={item} purchase quantity={item[key]??null} quantityLabel={queue==='accept'?'历史到货待衔接':'可登记到货数量'} status={purchaseRecordStatus(item)}/>
<RecordMeta label="项目" value={display(item.projectName)} secondary/>
<RecordMeta label="创建人" value={`批次:${display(item.batchCreatorName||item.batchCreateBy)} · 明细:${display(item.creatorName||item.createBy)}`} secondary/>
<View style={{paddingTop:8,borderTopWidth:1,borderColor:t.line,alignItems:'stretch'}}>{children}</View>

View File

@ -1,3 +1,4 @@
import {ArrivalHistory} from './ArrivalHistory';
import {ArrivalPhotos} from './ArrivalPhotos';
import {formatDateTime} from '../core/date-display';
import React,{useEffect,useRef,useState} from 'react';
@ -12,13 +13,14 @@ import {useOperationDraft} from '../hooks/useOperationDraft';
import {ItemIdentity} from './ItemIdentity';
import {purchaseRecordStatus} from '../core/record-presentation';
export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;row:Row;mode:'arrival'|'accept';close:()=>void;done:()=>void;scope?:string}){
function ArrivalOperationBody({api,row,mode,close,done,scope}:{api:ApiClient;row:Row;mode:'arrival'|'accept';close:()=>void;done:()=>void;scope?:string}){
const t=useTheme(),accept=mode==='accept',lock=useRef(false),alive=useRef(true),requestKey=useRef(Crypto.randomUUID());
const [quantity,setQuantity]=useState(''),[date,setDate]=useState(localDate()),[remark,setRemark]=useState('');
const [records,setRecords]=useState<Row[]>([]),[record,setRecord]=useState<Row|null>(null),[loading,setLoading]=useState(accept);
const [preview,setPreview]=useState<Row|null>(null),[busy,setBusy]=useState(false),[attempted,setAttempted]=useState(false),[error,setError]=useState('');
const [photos,setPhotos]=useState<Row[]>([]),[photosPending,setPhotosPending]=useState(false);
const [checkingPhotos,setCheckingPhotos]=useState(false);
const [recoveredArrival,setRecoveredArrival]=useState<Row|null>(null);
const restoredRecord=useRef<number|null>(null);
const snapshot={quantity,date,remark,record,preview,attempted,photos,requestKey:requestKey.current};
const draft=useOperationDraft({scope,kind:mode,id:row.id,value:snapshot,hasContent:v=>!!(v.quantity||v.remark||v.photos.length||v.preview),isPending:v=>v.attempted,onRestore:v=>{
@ -37,7 +39,7 @@ export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;
function prepare(){
if(!draft.ready||checkingPhotos)return;
if(!accept&&!photos.some(photo=>photo.id))return setError('登记到货至少需要1张照片,请先拍照或选择图片。');
if(!accept&&photosPending)return setError('有照片尚未上传完成,请重试或移除后继续。');
if(photosPending)return setError('有照片尚未上传完成,请重试或移除后继续。');
const amount=Number(quantity||'0');
if(!/^\d+(\.\d{1,4})?$/.test(quantity||'0')||!Number.isFinite(amount)||(accept?amount<0:amount<=0))return setError(accept?'请填写不合格数量,允许为 0,最多 4 位小数。':'请填写大于 0 的到货数量,最多 4 位小数。');
if(accept&&!record)return setError('请选择本次验收的到货记录。');
@ -51,9 +53,30 @@ export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;
catch(e){if(alive.current)setError((e as Error).message+(accept?' 请返回列表刷新到货记录,核对是否已经验收;不会自动重发。':' 请先核对到货记录。重试仅发送相同内容与请求标识,不会新建另一请求。'));}
finally{lock.current=false;if(alive.current)setBusy(false);}
}
async function checkResult(){if(lock.current)return;lock.current=true;setBusy(true);try{const response=await api.request<Row>(`/warehouse/purchase/arrival/${row.id}`),items=response.data||[];const saved=accept?items.find((v:Row)=>v.id===preview?.id&&Number(v.acceptanceStatus)!==0):items.find((v:Row)=>v.requestKey===requestKey.current);if(saved){await draft.clear();done();}else setError(accept?'当前记录仍为待验收。请稍后刷新核对,避免重复操作。':'暂未查到本次登记,可继续用原请求重试。');}catch(e){setError((e as Error).message);}finally{lock.current=false;setBusy(false);}}
async function checkResult(){
if(lock.current)return;lock.current=true;setBusy(true);setError('');
try{
if(accept){
const response=await api.request<Row>(`/warehouse/purchase/arrival/${row.id}`),current=(response.data||[]).find((v:Row)=>v.id===preview?.id);
if(!current)return setError('未找到原到货记录,请返回列表刷新核对。');
if(Number(current.acceptanceStatus)!==0){await draft.clear();done();return;}
setRecord(current);setRecords(items=>items.map(item=>item.id===current.id?current:item));
}else{
const response=await api.request<Row>(`/warehouse/purchase/arrival/${row.id}/submission`,{query:{requestKey:requestKey.current}}),saved=response.data;
if(saved){
await draft.clear();
if((saved.photos||[]).length){done();return;}
setRecoveredArrival(saved);setPreview(null);setAttempted(false);return;
}
}
// Keep the same business key: a delayed original request still cannot create a duplicate.
await draft.saveNow({...snapshot,attempted:false,preview:null});setAttempted(false);setPreview(null);
setError(accept?'当前仍为待验收,已恢复填写,可补传照片后重新核对。':'未生成到货记录,已恢复填写,请补全照片后重新核对。');
}catch(e){setError((e as Error).message);}finally{lock.current=false;setBusy(false);}
}
function requestClose(){if(busy)return;if(preview||quantity||remark||photos.length)Alert.alert('保留填写并返回?',attempted?'将保留原提交内容,下次继续核对结果。':'内容将保存在当前账号的本机草稿中,尚未提交业务。',[{text:'继续填写',style:'cancel'},{text:'保留并返回',onPress:()=>{void draft.saveNow().then(close).catch(()=>{});}}]);else close();}
const title=accept?'验收到货':'登记到货';
if(recoveredArrival)return <Modal visible animationType="slide" onRequestClose={done}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>补传到货照片</Heading><Button title="完成并刷新" secondary onPress={done}/></View><ScrollView contentContainerStyle={s.page}><Card><ItemIdentity item={row} purchase quantity={recoveredArrival.arrivalQuantity} quantityLabel="已登记到货"/><Note>已找到本次到货记录,无需再次登记。请补传照片,上传后自动保存。</Note></Card><ArrivalPhotos api={api} requestId={row.id} arrivalId={recoveredArrival.id} photos={recoveredArrival.photos||[]} readonly supplemental onChange={photos=>setRecoveredArrival(current=>current?{...current,photos}:current)}/></ScrollView></SafeAreaView></Modal>;
return <Modal visible animationType="slide" onRequestClose={requestClose}><SafeAreaView style={[s.fill,{backgroundColor:t.bg,width:'100%',maxWidth:Platform.OS==='web'?480:undefined,alignSelf:'center'}]}><KeyboardAvoidingView style={s.fill} behavior={Platform.OS==='ios'?'padding':undefined}>
<View style={{paddingHorizontal:18,paddingVertical:10,flexDirection:'row',alignItems:'center',justifyContent:'space-between',borderBottomWidth:1,borderColor:t.line}}><Heading>{title}</Heading><Button title="关闭" secondary disabled={busy} onPress={requestClose}/></View>
<ScrollView style={s.fill} keyboardShouldPersistTaps="handled" contentContainerStyle={[s.page,{paddingBottom:18}]}>
@ -63,13 +86,15 @@ export function ArrivalOperation({api,row,mode,close,done,scope}:{api:ApiClient;
{!preview?<>
{accept?<><Choice label="到货记录" items={records} value={record} onChange={setRecord} nameKey="label"/>{!loading&&!records.length&&<Note>暂无待验收记录。尚未登记的货物,请先返回选择“登记到货”。</Note>}<Note>本次到货:{display(record?.arrivalQuantity)} {display(row.unit)};合格数量将按到货数量减去不合格数量计算。</Note></>:<><Note>剩余可登记:{display(row.remainingQuantity)} {display(row.unit)}</Note><Button title="本次全部到齐" secondary onPress={()=>setQuantity(String(row.remainingQuantity))}/><DateField label="到货日期" value={date} onChange={setDate}/></>}
<Field label={accept?'不合格数量(0 表示全部合格)':'本次到货数量'} value={quantity} onChange={setQuantity} keyboard="decimal-pad"/><Field label={accept?'验收说明':'到货备注'} value={remark} onChange={setRemark} multiline/>
</>:<Card><Heading>请核对本次{title}</Heading>{accept?<><Note>到货单:{display(record?.arrivalNo)}</Note><Note>到货数量:{display(record?.arrivalQuantity)} {display(row.unit)}</Note><Note>合格数量:{Number(record?.arrivalQuantity)-Number(preview.body.defectiveQuantity)} {display(row.unit)}</Note><Note>不合格数量:{preview.body.defectiveQuantity} {display(row.unit)}</Note><Note>验收合格后进入待入库,尚不会增加库存。</Note></>:<><Note>到货数量:{preview.body.arrivalQuantity} {display(row.unit)}</Note><Note>到货日期:{formatDateTime(preview.body.arrivalDate)}</Note><Note>本次仅登记到货,之后再办理验收。</Note></>}
</>:<Card><Heading>请核对本次{title}</Heading>{accept?<><Note>到货单:{display(record?.arrivalNo)}</Note><Note>到货数量:{display(record?.arrivalQuantity)} {display(row.unit)}</Note><Note>合格数量:{Number(record?.arrivalQuantity)-Number(preview.body.defectiveQuantity)} {display(row.unit)}</Note><Note>不合格数量:{preview.body.defectiveQuantity} {display(row.unit)}</Note><Note>验收合格后进入待入库,尚不会增加库存。</Note></>:<><Note>到货数量:{preview.body.arrivalQuantity} {display(row.unit)}</Note><Note>到货日期:{formatDateTime(preview.body.arrivalDate)}</Note><Note>登记到货后转待入库,无需线下验收;未报价也能入库,成本之后补齐。</Note></>}
<Note>说明:{remark||'无'}</Note>
</Card>}
<ArrivalPhotos api={api} requestId={row.id} photos={accept?(record?.photos||[]):photos} onChange={setPhotos} onPending={setPhotosPending} readonly={accept||!!preview} disabled={busy||attempted||checkingPhotos||!draft.ready}/>
<ArrivalPhotos api={api} requestId={row.id} arrivalId={accept?record?.id:undefined} supplemental={accept&&!!record&&!preview} photos={accept?(record?.photos||[]):photos} onChange={accept?photos=>{setRecord(current=>current?{...current,photos}:current);setRecords(items=>items.map(item=>item.id===record?.id?{...item,photos}:item));}:setPhotos} onPending={setPhotosPending} readonly={accept||!!preview} disabled={busy||attempted||checkingPhotos||!draft.ready}/>
{!!error&&<Note>{error}</Note>}
{attempted&&<Button title="核对提交结果" secondary busy={busy} onPress={()=>void checkResult()}/>}
</ScrollView><View style={{padding:14,borderTopWidth:1,borderColor:t.line,backgroundColor:t.card}}>
{!preview?<Button title="核对预览" disabled={!draft.ready||checkingPhotos||loading||photosPending||accept&&!record} onPress={prepare}/>:<View style={{flexDirection:'row',gap:10}}><View style={{flex:1}}><Button title="返回修改" secondary disabled={busy||attempted} onPress={()=>setPreview(null)}/></View><View style={{flex:1}}><Button title={attempted?'核对后重试原请求':'确认提交'} busy={busy} disabled={!draft.ready||accept&&attempted} onPress={()=>void submit()}/></View></View>}
</View></KeyboardAvoidingView></SafeAreaView></Modal>;
}
export function ArrivalOperation(props:Parameters<typeof ArrivalOperationBody>[0]){return props.mode==='accept'?<ArrivalHistory api={props.api} row={props.row} canSupplement close={props.done}/>:<ArrivalOperationBody {...props}/>;}

View File

@ -27,19 +27,21 @@ export function ArrivalPhotos({api,requestId,photos,onChange,onPending,readonly=
finally{locked.current=false;if(alive.current)setWorking(false);}
}
async function choose(camera:boolean){
if(disabled||!canUpload||locked.current||photos.length>=9)return;locked.current=true;setWorking(true);setError('');let photo:Row|undefined;
if(disabled||!canUpload||locked.current||photos.length>=9)return;locked.current=true;setWorking(true);setError('');const selectedPhotos:Row[]=[];
try{
if(camera){const permission=await ImagePicker.requestCameraPermissionsAsync();if(!permission.granted){setError('未获得相机权限。可在系统设置中允许拍照,或从相册选择照片。');return;}}
const result=camera?await ImagePicker.launchCameraAsync({mediaTypes:['images'],quality:.7,exif:false}):await ImagePicker.launchImageLibraryAsync({mediaTypes:['images'],quality:.7,allowsMultipleSelection:false,exif:false});
const result=camera?await ImagePicker.launchCameraAsync({mediaTypes:['images'],quality:.7,exif:false}):await ImagePicker.launchImageLibraryAsync({mediaTypes:['images'],quality:.7,preferredAssetRepresentationMode:ImagePicker.UIImagePickerPreferredAssetRepresentationMode?.Compatible,allowsMultipleSelection:true,selectionLimit:9-photos.length,exif:false});
if(result.canceled||!alive.current)return;
const asset=result.assets[0],type=asset.mimeType||'image/jpeg';
if(!['image/jpeg','image/png','image/webp'].includes(type)){setError('请选择 JPG、PNG 或 WebP 照片。');return;}
if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>20*1024*1024)){setError('每张照片不能超过20MB,请降低照片大小或重新拍摄。');return;}
if(result.assets.length>9-current.current.length){setError('照片总数最多9张,请重新选择。');return;}
for(const asset of result.assets){
const type=asset.mimeType||'image/jpeg';
if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>20*1024*1024)){setError('每张照片不能超过20MB,请降低照片大小或重新拍摄。');continue;}
const extension=type==='image/png'?'png':type==='image/webp'?'webp':'jpg';
photo={clientKey:Crypto.randomUUID(),name:`arrival-${Date.now()}.${extension}`,contentType:type,uri:asset.uri};update([...current.current,photo]);
const photo={clientKey:Crypto.randomUUID(),name:`arrival-${Date.now()}.${extension}`,contentType:type,uri:asset.uri};selectedPhotos.push(photo);update([...current.current,photo]);
}
}catch(e){if(alive.current)setError((e as Error).message||'无法获取照片,请重试。');}
finally{locked.current=false;if(alive.current)setWorking(false);}
if(photo&&alive.current)await upload(photo);
for(const photo of selectedPhotos){if(!alive.current)break;await upload(photo);}
}
async function remove(photo:Row){
if(disabled||locked.current||supplemental&&photo.id)return;locked.current=true;setWorking(true);setError('');

View File

@ -22,12 +22,12 @@ export function Assistant({api}:{api:ApiClient}){
useEffect(()=>{alive.current=true;void refresh();return()=>{alive.current=false;};},[refresh]);
useEffect(()=>{if(!busy){setSeconds(0);return;}const started=Date.now(),timer=setInterval(()=>setSeconds(Math.floor((Date.now()-started)/1000)),1000);return()=>clearInterval(timer);},[busy]);
async function attach(){if(lock.current||files.length>=3)return;lock.current=true;setBusy(true);setAttachmentPhase('selecting');setError('');try{
const selected=await DocumentPicker.getDocumentAsync({multiple:false,copyToCacheDirectory:true,type:['image/png','image/jpeg','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel','application/pdf']});
if(selected.canceled||!alive.current)return;const file=selected.assets[0];if(file.size!=null&&(file.size<=0||file.size>10*1024*1024)){setError('请选择非空附件,单个不超过 10 MB。');return;}
const selected=await DocumentPicker.getDocumentAsync({multiple:true,copyToCacheDirectory:true,type:['image/png','image/jpeg','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel','application/pdf']});
if(selected.canceled||!alive.current)return;if(selected.assets.length>3-files.length){setError('识别附件最多3个,请重新选择。');return;}const failures:string[]=[];for(const file of selected.assets){if(!alive.current)break;try{if(file.size!=null&&(file.size<=0||file.size>10*1024*1024)){throw new Error('请选择非空附件,单个不超过 10 MB。');}
setAttachmentPhase('uploading');const body=new FormData();
if(Platform.OS==='web'){const response=await fetch(file.uri);body.append('file',await response.blob(),file.name);}
else body.append('file',{uri:file.uri,name:file.name,type:file.mimeType||'application/octet-stream'} as unknown as Blob);
const data=await api.request<Row>(`${root}/attachments`,{method:'POST',body,timeout:120000});if(alive.current){const f=data.data;setFiles(old=>[...old,{...f,selectedSheetIndexes:f.sheets?.length===1?[f.sheets[0].index]:[]}]);}}
const data=await api.request<Row>(`${root}/attachments`,{method:'POST',body,timeout:120000});if(alive.current){const f=data.data;setFiles(old=>[...old,{...f,selectedSheetIndexes:f.sheets?.length===1?[f.sheets[0].index]:[]}]);}}catch(e){failures.push(file.name+':'+(e as Error).message);}}if(failures.length&&alive.current)setError(failures.join(';'));}
catch(e){if(alive.current)setError((e as Error).message);}finally{lock.current=false;if(alive.current){setBusy(false);setAttachmentPhase(null);}}}
async function send(){if(lock.current||!session||uncertain||(!text.trim()&&!files.length))return;
const selected=files.filter(f=>f.type==='excel'),selectionError=sheetSelectionError(files);if(selectionError)return setError(selectionError);

View File

@ -8,6 +8,8 @@ import {Button,Icon,Note,s,useTheme} from '../ui';
import {ArrivalCard,ArrivalListTools,OnlyMineToggle} from './ArrivalListParts';
import {arrivalListQuery} from '../core/arrival-list';
import {ArrivalActions} from './ArrivalActions';
import {ArrivalBatchBrowser} from './ArrivalBatchBrowser';
import {modules} from '../core/modules';
import {ArrivalHistory} from './ArrivalHistory';
import {ArrivalOperation} from './ArrivalOperation';
import {StockOperation} from './StockOperation';
@ -18,9 +20,10 @@ 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;onlyMine: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');
export function BusinessList({api,module,permissions,canViewQuotes,scope,initialQuery={},onNavigate,photoLookup=false}:{api:ApiClient;module:Module;permissions:string[];canViewQuotes:boolean;scope:string;initialQuery?:Row;photoLookup?:boolean;onNavigate?:(key:string,query?:Row)=>void}){
const t=useTheme(),cacheKey=scope+'|'+module.key+'|'+module.path+'|'+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'>('arrival');
const [batchPhotos,setBatchPhotos]=useState(false);
const [onlyMine,setOnlyMine]=useState(cached.current?.onlyMine??false);
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});
@ -28,7 +31,7 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
const initialFilters=Object.fromEntries(Object.entries(initialQuery).filter(([key])=>!['arrivalQueue','borrow'].includes(key)));
const load=useCallback(async(next:number,text:string,append=false)=>{
if(append&&busyRef.current)return;lastRequest.current={next,text,append};const id=++serial.current;controller.current?.abort();controller.current=new AbortController();busyRef.current=true;setBusy(true);setError('');appliedQuery.current=text.trim();
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),...(['arrival','purchase','pending'].includes(module.key)&&onlyMine?{onlyMine:true}:{}),pageNum:next,pageSize:20,...(module.search?{[module.search]:text.trim()}:{})},signal:controller.current.signal}),module.key==='purchase'?api.request<Row>('/warehouse/amount-display',{signal:controller.current.signal}):Promise.resolve(null)]);
try{const [data,money]=await Promise.all([api.request<Row>(module.path,{query:{...module.query,...initialFilters,...(module.key==='arrival'?arrivalListQuery(arrivalQueue):{}),...(['arrival','purchase','pending'].includes(module.key)&&onlyMine?{onlyMine:true}:{}),pageNum:next,pageSize:20,...(module.search?{[module.search]:text.trim()}:{})},signal:controller.current.signal}),module.key==='purchase'&&!photoLookup?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});}
@ -47,7 +50,8 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
const done=()=>{setOperation(null);setBatch(null);setSelected([]);void refresh();};
const actions=(item:Row)=>{
const visible=['stock','use','move'].includes(module.key)?stockWrite:module.key==='count'?allows(permissions,['warehouse:check:add']):module.key==='check'?Number(item.checkStatus)===0&&allows(permissions,['warehouse:check:confirm']):module.key==='pending'?eligible(item):['purchase','arrival'].includes(module.key);
if(!visible)return null;
const pendingHistory=module.key==='pending'&&item.purchaseRequestId&&allows(permissions,['warehouse:purchase:list','warehouse:purchase:manage']);
if(!visible&&!pendingHistory)return null;
return <View style={{gap:8}}>
{['move','use'].includes(module.key)&&stockWrite&&<Button title={module.key==='move'?'移库':'物料领用'} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:module.key})}/>}
{module.key==='stock'&&stockWrite&&<View style={{flexDirection:'row',gap:8}}><Button title="领用" style={{flex:1,minWidth:0}} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'use'})}/><Button title="移库" secondary style={{flex:1,minWidth:0}} disabled={busy||Number(item.stockNum)<=0} onPress={()=>setOperation({row:item,kind:'move'})}/></View>}
@ -55,13 +59,15 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
{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});}}/>}
{!!pendingHistory&&<Button title="到货记录" secondary disabled={busy} onPress={()=>setHistoryRow({...item,id:item.purchaseRequestId,editable:undefined})}/>}
{module.key==='pending'&&eligible(item)&&<Button title="办理入库" disabled={busy} onPress={()=>setOperation({row:item,kind:'receive'})}/>}
</View>;
};
return <View style={s.fill}>
{!photoLookup&&['arrival','purchase'].includes(module.key)&&<View style={{paddingHorizontal:14,paddingTop:8}}><Button title="按批次补录照片" secondary onPress={()=>setBatchPhotos(true)}/></View>}
{module.key==='arrival'?<ArrivalListTools query={query} setQuery={setQuery} queue={arrivalQueue} setQueue={changeArrivalQueue} busy={busy} total={total} page={page} onlyMine={onlyMine} setOnlyMine={changeOnlyMine} search={()=>void load(1,query)} reset={()=>{setQuery('');void load(1,'');}}/>:<View style={{paddingHorizontal:14,paddingVertical:8,gap:8}}>
{!!module.search&&<View style={{flexDirection:'row',gap:8,alignItems:'center'}}><View style={{flex:1,flexDirection:'row',alignItems:'center',borderWidth:1,borderColor:t.line,borderRadius:9,backgroundColor:t.card,paddingLeft:10}}><Icon name="search-outline" size={18}/><TextInput accessibilityLabel="搜索物品或关键词" placeholder="搜索物品或关键词" placeholderTextColor={t.muted} value={query} onChangeText={setQuery} onSubmitEditing={()=>void load(1,query)} returnKeyType="search" style={{flex:1,minWidth:0,minHeight:42,fontSize:14,color:t.text,padding:8}}/>{!!query&&<Pressable accessibilityRole="button" accessibilityLabel="清除搜索" onPress={()=>{setQuery('');void load(1,'');}} style={{padding:10}}><Icon name="close-circle" size={17}/></Pressable>}</View><Button title="查询" busy={busy} onPress={()=>void load(1,query)}/></View>}
<View style={{flexDirection:'row',flexWrap:'wrap',gap:4,justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{['purchase','pending'].includes(module.key)&&<OnlyMineToggle label={module.key==='pending'?'只看本人发起的待入库来源':'只看我创建的采购明细'} value={onlyMine} onChange={changeOnlyMine}/>} {canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}</View>
<View style={{flexDirection:'row',flexWrap:'wrap',gap:4,justifyContent:'space-between',alignItems:'center'}}><Text style={{color:t.muted,fontSize:12}}>已加载 {rows.length} / 共 {total} 条</Text>{!photoLookup&&['purchase','pending'].includes(module.key)&&<OnlyMineToggle label={module.key==='pending'?'只看本人发起的待入库来源':'只看我创建的采购明细'} value={onlyMine} onChange={changeOnlyMine}/>} {canSelect&&<Pressable accessibilityRole="button" accessibilityLabel={picking?'取消多选':'多选办理'} disabled={busy} onPress={()=>{setPicking(v=>!v);setSelected([]);}} style={{padding:8}}><Text style={{color:t.accent,fontSize:14}}>{picking?'取消多选':'多选办理'}</Text></Pressable>}</View>
</View>}
{!!error&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Text accessibilityRole="alert" style={{fontSize:13,lineHeight:19,color:'#bd3636'}}>{error}</Text><Button title="重试" secondary onPress={()=>void load(lastRequest.current.next,lastRequest.current.text,lastRequest.current.append)}/></View>}
{picking&&<View style={{paddingHorizontal:14,paddingBottom:8}}><Button title={`选择已加载可办理项(最多 100 项)`} secondary disabled={busy} onPress={()=>setSelected(rows.filter(eligible).slice(0,100))}/></View>}
@ -70,6 +76,7 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
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')}/></>}</View></View>}
{batchPhotos&&<ArrivalBatchBrowser api={api} close={()=>setBatchPhotos(false)} renderDetails={batch=><BusinessList key={batch.id} api={api} module={{...modules.find(m=>m.key==='purchase')!,path:'/warehouse/purchase/photo-records'}} permissions={permissions} canViewQuotes={canViewQuotes} scope={scope} initialQuery={{purchaseBatchId:batch.id}} photoLookup/>}/>}
{!!historyRow&&<ArrivalHistory api={api} row={historyRow} canSupplement={allows(permissions,['warehouse:purchase:edit','warehouse:purchase:manage'])} 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 File

@ -22,11 +22,11 @@ export function Feedback({api,mode,bindLeave,open}:{api:ApiClient;mode:'create'|
catch(e){if(mounted.current)setError((e as Error).message);}finally{lock.current=false;if(mounted.current)setBusy(false);}},[api]);
useEffect(()=>{if(mode==='list')void load(1);},[load,mode]);
async function choose(){if(lock.current||uncertain||images.length>=5)return;lock.current=true;setBusy(true);setError('');try{
const result=await ImagePicker.launchImageLibraryAsync({mediaTypes:['images'],quality:.85,allowsMultipleSelection:false});if(result.canceled||!mounted.current)return;
const asset=result.assets[0];if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>5*1024*1024)){setError('请选择不超过 5 MB 的图片(PNG、JPG 或 WebP)。');return;}
const name=asset.fileName||`feedback-${Date.now()}.jpg`,mime=asset.mimeType||'image/jpeg';if(!['image/png','image/jpeg','image/webp'].includes(mime)){setError('请使用 PNG、JPG 或 WebP 图片。');return;}
const result=await ImagePicker.launchImageLibraryAsync({mediaTypes:['images'],quality:.85,allowsMultipleSelection:true,selectionLimit:5-images.length});if(result.canceled||!mounted.current)return;
if(result.assets.length>5-images.length){setError('最多5张图片,请重新选择。');return;}const failures:string[]=[];for(const asset of result.assets){if(!mounted.current)break;try{if(asset.fileSize!=null&&(asset.fileSize<=0||asset.fileSize>5*1024*1024)){throw new Error('请选择不超过 5 MB 的图片(PNG、JPG 或 WebP)。');}
const name=asset.fileName||`feedback-${Date.now()}.jpg`,mime=asset.mimeType||'image/jpeg';if(!['image/png','image/jpeg','image/webp'].includes(mime)){throw new Error('请使用 PNG、JPG 或 WebP 图片。');}
const body=new FormData();if(Platform.OS==='web'){body.append('file',await(await fetch(asset.uri)).blob(),name);}else body.append('file',{uri:asset.uri,type:mime,name} as unknown as Blob);
const data=await api.request<Row>('/system/feedback/images',{method:'POST',body});if(mounted.current)setImages(old=>[...old,{...data.data,uri:asset.uri}]);
const data=await api.request<Row>('/system/feedback/images',{method:'POST',body});if(mounted.current)setImages(old=>[...old,{...data.data,uri:asset.uri}]);}catch(e){failures.push((asset.fileName||'图片')+':'+(e as Error).message);}}if(failures.length&&mounted.current)setError(failures.join(';'));
}catch(e){if(mounted.current)setError((e as Error).message);}finally{lock.current=false;if(mounted.current)setBusy(false);}}
async function submit(){if(lock.current||uncertain)return;let body;try{body=feedbackPayload(type,title,description,images.map(i=>i.id));}catch(e){setError((e as Error).message);return;}
lock.current=true;setBusy(true);setError('');try{const data=await api.request<Row>('/system/feedback',{method:'POST',body});if(mounted.current){setSuccess(data.data);setTitle('');setDescription('');setImages([]);}}

View File

@ -6,7 +6,7 @@ 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 {pickManagedFiles} 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('');
@ -15,7 +15,7 @@ export function FileLibrary({api,permissions,scope}:{api:ApiClient;permissions:s
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);}}
async function choose(){if(uploadCtl.current||!canUpload)return;const ctl=new AbortController();uploadCtl.current=ctl;setError('');let files:Awaited<ReturnType<typeof pickManagedFiles>>=[];const failures:string[]=[];try{files=await pickManagedFiles();for(let i=0;i<files.length;i++){const file=files[i];if(!alive.current||ctl.signal.aborted)break;setUploadName(`${i+1}/${files.length} · ${file.name}`);setUpload({phase:'hashing',percent:0});try{await uploadManagedFile(api,file,ctl.signal,p=>{if(alive.current)setUpload(p);});}catch(e){failures.push(file.name+':'+(e as Error).message);}}if(alive.current){await load();if(failures.length)setError(failures.join(';'));}}catch(e){if(alive.current)setError((e as Error).message);}finally{files.forEach(file=>{try{file.close();}catch{}});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>

View File

@ -15,33 +15,23 @@ test('a ready purchase exposes registration; zero is a valid locked quote',()=>{
const [a]=actions({finalUnitPrice:price});assert.equal(a.enabled,true);assert.equal(a.title,'登记到货');
}
});
test('unconfirmed purchases retain a disabled button and an actionable explanation',()=>{
test('unquoted purchases can register arrival before the quote is confirmed',()=>{
for(const priceLocked of [false,0,'0','false',null,undefined]){
const [a]=actions({priceLocked});assert.equal(a.enabled,false);assert.equal(a.kind,'arrival');
assert.match(a.reason,/Web.*确认采购.*锁定报价/);
const [a]=actions({priceLocked});assert.equal(a.enabled,true);assert.equal(a.kind,'arrival');assert.equal(a.reason,'');
}
});
test('a locked flag alone cannot permit missing or invalid quotes',()=>{
for(const finalUnitPrice of [null,undefined,'',NaN,-1])assert.equal(actions({finalUnitPrice})[0].enabled,false);
test('arrival does not require a quoted price',()=>{
for(const finalUnitPrice of [null,undefined,'',NaN,-1])assert.equal(actions({finalUnitPrice})[0].enabled,true);
});
test('registration requires the batch and its supplier, with a clear explanation',()=>{
for(const changes of [{purchaseBatchId:null},{supplierId:null},{supplierId:''},{purchaseBatchId:0}]){
assert.equal(actions(changes)[0].enabled,false);assert.match(actions(changes)[0].reason,/采购批次和供应商/);
}
});
test('pending arrivals expose acceptance even when all ordered quantity is registered',()=>{
const a=actions({remainingQuantity:0,pendingArrivalQuantity:5});
assert.equal(a[0].enabled,false);assert.match(a[0].reason,/办理验收/);
assert.equal(a[1].kind,'accept');assert.equal(a[1].enabled,true);
assert.equal(actions({remainingQuantity:0,pendingArrivalQuantity:5},'accept')[0].enabled,true);
// Acceptance does not invent a supplier requirement absent from the acceptance service.
assert.equal(actions({supplierId:null,pendingArrivalQuantity:2},'accept')[0].enabled,true);
});
test('pending records still require locked quotes and missing quantities fail safely',()=>{
assert.equal(actions({pendingArrivalQuantity:3,priceLocked:false},'accept')[0].enabled,false);
assert.equal(actions({pendingArrivalQuantity:undefined},'accept')[0].enabled,false);
assert.match(actions({pendingArrivalQuantity:0},'accept')[0].reason,/先登记到货/);
assert.match(actions({remainingQuantity:undefined})[0].reason,/刷新/);
test('legacy pending arrivals never expose physical acceptance; receipt handoff is in history',()=>{
const a=actions({remainingQuantity:0,pendingArrivalQuantity:5});assert.equal(a.length,1);assert.equal(a[0].enabled,false);assert.match(a[0].reason,/待入库/);
for(const queue of ['arrival','accept'])assert.ok(actions({pendingArrivalQuantity:2},queue).every(a=>a.kind==='arrival'));
assert.match(actions({remainingQuantity:undefined})[0].reason,/刷新/);
});
test('historical and cancelled purchases can never enter either operation',()=>{
for(const changes of [{historical:true},{historical:1},{historical:'1'},{historical:'true'},{purchaseStatus:5},{purchaseStatus:'5'}]){
@ -74,24 +64,12 @@ function render(changes={},queue='arrival',onHistory){
function walk(node){if(!node||typeof node!=='object')return;nodes.push(node);React.Children.toArray(node.props?.children).forEach(walk);}
walk(tree);return {tree,nodes,opened,buttons:nodes.filter(n=>n.type==='Button'),notes:nodes.filter(n=>n.type==='Note')};
}
test('real rendered controls remain visible when unavailable; even direct handler calls cannot open them',()=>{
const s=render({priceLocked:false,pendingArrivalQuantity:3});assert.equal(s.buttons.length,2);
for(const b of s.buttons){assert.equal(b.props.disabled,true);b.props.onPress();}
assert.deepEqual(s.opened,[]);assert.equal(s.notes.length,1);assert.match(s.notes[0].props.children,/确认采购/);
});
test('real rendered controls open the correct form only; they never submit a request',()=>{
const s=render({pendingArrivalQuantity:2});assert.deepEqual(s.buttons.map(b=>b.props.title),['登记到货','验收到货']);
s.buttons.forEach(b=>{assert.equal(b.props.disabled,false);b.props.onPress();});
assert.deepEqual(s.opened,['arrival','accept']);assert.equal(s.notes.length,0);
const accept=render({remainingQuantity:0,pendingArrivalQuantity:2},'accept');
assert.equal(accept.buttons.length,1);assert.equal(accept.buttons[0].props.title,'验收到货');
});
test('history shares the same row as registration and acceptance with short labels and flexible widths',()=>{
let history=0;const s=render({pendingArrivalQuantity:2},'arrival',()=>history++);assert.deepEqual(s.buttons.map(b=>b.props.title),['登记到货','验收到货','到货记录']);
const row=s.nodes.find(n=>n.type==='View'&&n.props.style?.flexDirection==='row');assert.equal(row.props.style.flexWrap,undefined);assert.equal(React.Children.toArray(row.props.children).length,3);assert.equal(s.tree.props.style.width,'100%');
for(const button of s.buttons){assert.equal(button.props.style.flex,1);assert.equal(button.props.style.minWidth,0);assert.equal(button.props.style.paddingHorizontal,8);}
s.buttons[2].props.onPress();assert.equal(history,1);assert.deepEqual(s.opened,[]);
const accept=render({pendingArrivalQuantity:2,remainingQuantity:0},'accept',()=>{});assert.deepEqual(accept.buttons.map(b=>b.props.title),['验收到货','到货记录']);
test('rendered registration and history stay compact without an acceptance button',()=>{
let history=0;const view=render({priceLocked:false,finalUnitPrice:null},'arrival',()=>history++);
assert.deepEqual(view.buttons.map(b=>b.props.title),['登记到货','到货记录']);
view.buttons[0].props.onPress();view.buttons[1].props.onPress();assert.deepEqual(view.opened,['arrival']);assert.equal(history,1);
for(const button of view.buttons){assert.equal(button.props.style.flex,1);assert.equal(button.props.style.minWidth,0);}
const disabled=render({editable:false});assert.equal(disabled.buttons[0].props.disabled,true);disabled.buttons[0].props.onPress();assert.deepEqual(disabled.opened,[]);
});
test('ownership applies equally to arrival and acceptance while a hidden confirmed quote does not block an employee',()=>{

View File

@ -0,0 +1,21 @@
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';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
test('batch photo browser pages completed batches and opens the selected batch without pending filters',async()=>{
const source=await readFile(new URL('../src/screens/ArrivalBatchBrowser.tsx',import.meta.url),'utf8');
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
const values=[],refs=[],effects=[],calls=[],timers=[];let si=0,ri=0,tree,selected;
const react={...React,useState:v=>{const i=si++;if(!(i in values))values[i]=v;return[values[i],v=>{values[i]=typeof v==='function'?v(values[i]):v;}];},useRef:v=>refs[ri++]??=( {current:v}),useCallback:fn=>fn,useEffect:fn=>{effects.push(fn);}};
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',FlatList:'FlatList',Modal:'Modal',ActivityIndicator:'Spinner'},'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'../core/modules':{display:v=>String(v||'—')},'../ui':{Button:'Button',Card:'Card',Heading:'Heading',Note:'Note',s:{fill:{},row:{}},useTheme:()=>({})},'../typography':{Text:'Text',TextInput:'Input'}};
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>{if(!imports[name])throw Error(name);return imports[name];},setTimeout:fn=>{timers.push(fn);return timers.length;},clearTimeout:()=>{},AbortController});
const api={request:async(path,options)=>{calls.push({path,query:options.query});return{rows:[{id:options.query.pageNum,batchName:'已完成批次',requestCount:41,purchaseStatus:4}],total:2};}};
const render=()=>{si=0;ri=0;tree=module.exports.ArrivalBatchBrowser({api,close:()=>{},renderDetails:batch=>{selected=batch;return null;}});};
function find(type,node=tree){if(!node||typeof node!=='object')return null;if(node.type===type)return node;for(const child of React.Children.toArray(node.props?.children)){const value=find(type,child);if(value)return value;}return null;}
render();const cleanup=effects[0]();await timers.shift()();await new Promise(r=>setImmediate(r));render();
let list=find('FlatList');assert.equal(list.props.data[0].purchaseStatus,4);assert.deepEqual(JSON.parse(JSON.stringify(calls[0])),{path:'/warehouse/purchase/batch/photo-records',query:{keyword:'',pageNum:1,pageSize:20}});
await list.props.ListFooterComponent.props.onPress();await new Promise(r=>setImmediate(r));render();list=find('FlatList');assert.equal(list.props.data.length,2);
const card=list.props.renderItem({item:list.props.data[1]});find('Button',card).props.onPress();render();assert.equal(selected.id,2);assert.equal(selected.requestCount,41);cleanup();
});

View File

@ -6,9 +6,9 @@ import vm from 'node:vm';
import {arrivalListQuery} from '../src/core/arrival-list.ts';
import {arrivalLayout} from '../src/core/arrival-layout.ts';
import {purchaseRecordStatus} from '../src/core/record-presentation.ts';
test('registration queue asks the server for confirmed eligible purchases, not all not-yet-accepted purchases',()=>{
assert.deepEqual(arrivalListQuery('arrival'),{pendingRegistration:true,arrivalReady:true,priceLocked:true});
assert.deepEqual(arrivalListQuery('accept'),{pendingAcceptance:true,priceLocked:true});
test('registration queue includes unquoted eligible purchases and excludes already-registered quantity',()=>{
assert.deepEqual(arrivalListQuery('arrival'),{pendingRegistration:true,arrivalReady:true});
assert.deepEqual(arrivalListQuery('accept'),{pendingAcceptance:true});
});
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
const source=readFileSync(new URL('../src/screens/ArrivalListParts.tsx',import.meta.url),'utf8');
@ -18,17 +18,16 @@ vm.runInNewContext(compiled,{exports,require:name=>({react:React,'react/jsx-runt
'react-native':{ActivityIndicator:'Loading',Pressable:'Pressable',Text:'Text',TextInput:'TextInput',View:'View',useWindowDimensions:()=>({width:393,fontScale:1})},
'../typography':{Text:'Text',TextInput:'TextInput'},'./ItemIdentity':{ItemIdentity:'ItemIdentity',RecordMeta:'RecordMeta'},'../core/record-presentation':{purchaseRecordStatus},'../core/arrival-layout':{arrivalLayout},'../ui':{Card:'Card',Icon:'Icon',useTheme:()=>({})},'../core/modules':{display:v=>v==null?'—':String(v)}}[name]||require(name))});
function nodes(tree){const all=[];function walk(n){if(!n||typeof n!=='object')return;all.push(n);React.Children.toArray(n.props?.children).forEach(walk);}walk(tree);return all;}
test('compact queue tabs have equal width, correct state, accessible search and explicit clear',()=>{
test('arrival search is accessible and the removed physical acceptance tab stays absent',()=>{
const calls=[];const tree=exports.ArrivalListTools({query:'水冷',setQuery:v=>calls.push(v),queue:'accept',setQueue:v=>calls.push(v),busy:false,search:()=>calls.push('search'),reset:()=>calls.push('reset'),total:25,page:2});
const all=nodes(tree),tabs=all.filter(n=>n.props.accessibilityRole==='tab');
assert.equal(tabs.length,2);assert.deepEqual(tabs.map(n=>n.props.style.flex),[1,1]);
assert.deepEqual(tabs.map(n=>n.props.accessibilityState.selected),[false,true]);tabs[0].props.onPress();
assert.equal(tabs.length,0);
all.find(n=>n.type==='TextInput').props.onSubmitEditing();all.find(n=>n.props.accessibilityLabel==='清除搜索').props.onPress();
assert.deepEqual(calls,['arrival','search','reset']);
assert.deepEqual(calls,['search','reset']);
});
test('acceptance card forwards the pending quantity and complete identity to the compact shared item header',()=>{
const all=nodes(exports.ArrivalCard({item:{materialName:'很长的物品名称',materialParams:'规格',remainingQuantity:0,pendingArrivalQuantity:18,unit:'很长的测试单位'},queue:'accept',children:null}));
const summary=all.find(n=>n.type==='ItemIdentity');assert.ok(summary);assert.equal(summary.props.quantity,18);assert.equal(summary.props.item.unit,'很长的测试单位');assert.equal(summary.props.item.materialParams,'规格');assert.equal(summary.props.quantityLabel,'待验收数量');assert.equal(summary.props.purchase,true);
const summary=all.find(n=>n.type==='ItemIdentity');assert.ok(summary);assert.equal(summary.props.quantity,18);assert.equal(summary.props.item.unit,'很长的测试单位');assert.equal(summary.props.item.materialParams,'规格');assert.equal(summary.props.quantityLabel,'历史到货待衔接');assert.equal(summary.props.purchase,true);
assert.ok(all.filter(n=>n.type==='View').every(n=>n.props.style.width!==94));
});
test('query state survives queue changes and pagination uses applied search rather than unsent text',()=>{

View File

@ -4,20 +4,20 @@ import {readFile} from 'node:fs/promises';
import {createRequire} from 'node:module';
import vm from 'node:vm';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
async function screen({permission=true,cancel=false,failOnce=false,fileSize=1000}={}){
async function screen({permission=true,cancel=false,failOnce=false,fileSize=1000,assetCount=1,supplemental=false}={}){
const source=await readFile(new URL('../src/screens/ArrivalPhotos.tsx',import.meta.url),'utf8'),compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
const values=[],refs=[],calls=[],camera=[],cleanup=[];let state=0,ref=0,photos=[],fail=failOnce;
const values=[],refs=[],calls=[],camera=[],cleanup=[];let state=0,ref=0,photos=[],fail=failOnce,uuid=0;
const react={...React,useState:v=>{const i=state++;if(!(i in values))values[i]=v;return[values[i],v=>{values[i]=typeof v==='function'?v(values[i]):v;}];},useRef:v=>{const i=ref++;return refs[i]??={current:v};},useEffect:fn=>{const value=fn();if(value)cleanup.push(value);}};
const picker={async requestCameraPermissionsAsync(){return {granted:permission};},async launchCameraAsync(options){camera.push(options);return {canceled:cancel,assets:[{uri:'file:///camera.jpg',mimeType:'image/jpeg',fileSize}]};},async launchImageLibraryAsync(){return {canceled:cancel,assets:[{uri:'file:///album.jpg',mimeType:'image/jpeg',fileSize}]};}};
const picker={async requestCameraPermissionsAsync(){return {granted:permission};},async launchCameraAsync(options){camera.push(options);return {canceled:cancel,assets:[{uri:'file:///camera.jpg',mimeType:'image/jpeg',fileSize}]};},async launchImageLibraryAsync(){return {canceled:cancel,assets:Array.from({length:assetCount},(_,i)=>({uri:'file:///album-'+i+'.jpg',mimeType:'image/jpeg',fileSize}))};}};
class Form {values=new Map();append(k,v){this.values.set(k,v);}get(k){return this.values.get(k);}}
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Image:'Image',Platform:{OS:'android'}},'expo-image-picker':picker,'expo-crypto':{randomUUID:()=> '11111111-1111-4111-8111-111111111111'},'../ui':{Button:'Button',Note:'Note',s:{}},'../files':{ProtectedImage:'ProtectedImage'}};
const imports={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{View:'View',Image:'Image',Platform:{OS:'android'}},'expo-image-picker':picker,'expo-crypto':{randomUUID:()=> ++uuid===1?'11111111-1111-4111-8111-111111111111':`11111111-1111-4111-8111-${String(uuid).padStart(12,'0')}`},'../ui':{Button:'Button',Note:'Note',s:{}},'../files':{ProtectedImage:'ProtectedImage'}};
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:n=>imports[n]||require(n),FormData:Form,AbortController});
const api={async request(path,options){calls.push({path,options});if(fail){fail=false;throw Error('模拟上传失败');}return {data:{id:options.body?.get('uploadId'),name:'到货.jpg'}};}};
let tree;const render=()=>{state=0;ref=0;tree=module.exports.ArrivalPhotos({api,requestId:10,photos,onChange:v=>{photos=v;}});};render();
let tree;const render=()=>{state=0;ref=0;tree=module.exports.ArrivalPhotos({api,requestId:10,arrivalId:supplemental?100:undefined,readonly:supplemental,supplemental,photos,onChange:v=>{photos=v;}});};render();
function find(title,node=tree){if(!node||typeof node!=='object')return null;if(node.type==='Button'&&node.props.title===title)return node;for(const child of React.Children.toArray(node.props?.children)){const value=find(title,child);if(value)return value;}return null;}
return {calls,camera,render,button:find,get photos(){return photos;},cleanup:()=>cleanup.forEach(fn=>fn())};
}
test('camera permission denial and camera cancellation do not upload or block a photo-free arrival',async()=>{
test('camera permission denial and camera cancellation do not upload an empty photo',async()=>{
for(const options of [{permission:false},{cancel:true}]){const page=await screen(options);await page.button('拍照').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,0);assert.equal(page.photos.length,0);page.cleanup();}
});
test('taking a photo sends an image-only camera request and private multipart upload',async()=>{
@ -29,3 +29,11 @@ test('album uploads can retry the same photo identifier after failure',async()=>
test('camera photos above 5MB are accepted, while the new 20MB limit is enforced',async()=>{
for(const [size,allowed]of [[7*1024*1024,true],[20*1024*1024,true],[20*1024*1024+1,false]]){const page=await screen({fileSize:size});await page.button('拍照').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,allowed?1:0);page.cleanup();}
});
test('album multi-selection uploads all photos and retains a failed item for individual retry',async()=>{
const page=await screen({assetCount:2,failOnce:true});await page.button('从相册选择').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,2);assert.equal(page.photos.length,2);assert.ok(page.photos[0].error);assert.ok(page.photos[1].id);page.render();await page.button('重试上传').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls.length,3);assert.equal(page.calls[0].options.body.get('uploadId'),page.calls[2].options.body.get('uploadId'));page.cleanup();
});
test('historical receipt supplementation uses the saved arrival endpoint and retains retry identity',async()=>{
const page=await screen({supplemental:true,failOnce:true});await page.button('从相册选择').props.onPress();await new Promise(r=>setImmediate(r));page.render();await page.button('重试上传').props.onPress();await new Promise(r=>setImmediate(r));assert.equal(page.calls[0].path,'/warehouse/purchase/arrival/photos/record/100');assert.equal(page.calls[1].path,page.calls[0].path);assert.equal(page.calls[0].options.body.get('uploadId'),page.calls[1].options.body.get('uploadId'));assert.ok(page.photos[0].id);page.cleanup();
});

View File

@ -16,7 +16,7 @@ test('large broadcasts cannot execute against a partial recipient preview',()=>{
});
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});
const tasks=workspaceTasks(modules);assert.equal(tasks.length,3);assert.equal(tasks.find(t=>t.id==='accept'),undefined);
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',()=>{

View File

@ -9,22 +9,22 @@ import * as dateDisplay from '../src/core/date-display.ts';
import {purchaseRecordStatus} from '../src/core/record-presentation.ts';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
async function screen({mode='arrival',failure=false}={}){
async function screen({mode='arrival',failure=false,lookup=undefined}={}){
const source=await readFile(new URL('../src/screens/ArrivalOperation.tsx',import.meta.url),'utf8');
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
const values=[],refs=[],calls=[];let cursor=0,refCursor=0,done=0;
const values=[],refs=[],calls=[];let cursor=0,refCursor=0,done=0,restore;
const record={id:101,arrivalNo:'DH-101',arrivalQuantity:3,acceptanceStatus:0,label:'DH-101 · 3 个'};
const react={...React,useState:initial=>{const i=cursor++;if(!(i in values))values[i]=initial;return[values[i],v=>values[i]=typeof v==='function'?v(values[i]):v];},useRef:initial=>{const i=refCursor++;return refs[i]??= {current:initial};},useEffect:()=>{}};
const native={Modal:'Modal',ScrollView:'ScrollView',View:'View',KeyboardAvoidingView:'KeyboardAvoidingView',Platform:{OS:'android'}};
const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',DateField:'DateField',Field:'Field',Heading:'Heading',Note:'Note'};
const imports={'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}},'../hooks/useOperationDraft':{useOperationDraft:()=>({ready:true,restored:false,error:'',saveNow:async()=>{},clear:async()=>{}})}};
const imports={'./ArrivalHistory':{ArrivalHistory:'ArrivalHistory'},'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}},'../hooks/useOperationDraft':{useOperationDraft:options=>{restore=options.onRestore;return {ready:true,restored:false,error:'',saveNow:async()=>{},clear:async()=>{}}}}};
imports['./ItemIdentity']={ItemIdentity:'ItemIdentity'};imports['../core/record-presentation']={purchaseRecordStatus};
const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>imports[name]||require(name),AbortController});
const api={async request(path,options){calls.push({path,...options});if(failure)throw Error('timeout');return {data:{}};}};
const render=()=>{cursor=0;refCursor=0;return module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});};
const api={async request(path,options){calls.push({path,...options});if(path.endsWith('/submission')&&lookup!==undefined)return {data:lookup};if(failure)throw Error('timeout');return {data:{}};}};
const render=()=>{cursor=0;refCursor=0;const root=module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});return typeof root.type==='function'?root.type(root.props):root;};
let tree=render();if(mode==='accept'){values[3]=[record];values[4]=record;values[5]=false;tree=render();}
function find(type,prop,value,node=tree){if(!node||typeof node!=='object')return null;if(node.type===type&&node.props[prop]===value)return node;for(const child of React.Children.toArray(node.props?.children)){const match=find(type,prop,value,child);if(match)return match;}return null;}
return {calls,get done(){return done;},render(){tree=render();},button:title=>find('Button','title',title),field:label=>find('Field','label',label),photos:()=>find('ArrivalPhotos','requestId',10)};
return {calls,get tree(){return tree;},restore(value){restore(value);tree=render();},get done(){return done;},render(){tree=render();},button:title=>find('Button','title',title),field:label=>find('Field','label',label),photos:()=>find('ArrivalPhotos','requestId',10)};
}
const settle=()=>new Promise(resolve=>setImmediate(resolve));
test('five field operations are distinct entries; read-only accounts do not gain write entries',()=>{
@ -48,9 +48,21 @@ test('arrival without a completed photo cannot preview or submit; a failed uploa
test('arrival retry preserves the original idempotency key and body after a lost response',async()=>{
const s=await screen({failure:true});s.photos().props.onChange([{id:'11111111-1111-4111-8111-111111111111'}]);s.render();s.button('本次全部到齐').props.onPress();s.render();s.button('核对预览').props.onPress();s.render();s.button('确认提交').props.onPress();await settle();s.render();assert.equal(s.button('返回修改').props.disabled,true);s.button('核对后重试原请求').props.onPress();await settle();assert.equal(s.calls.length,2);assert.deepEqual(s.calls[0].body,s.calls[1].body);
});
test('acceptance sends defective quantity against the selected arrival, never registers another arrival',async()=>{
const s=await screen({mode:'accept'});s.field('不合格数量(0 表示全部合格)').props.onChange('1');s.render();s.button('核对预览').props.onPress();s.render();assert.equal(s.calls.length,0);s.button('确认提交').props.onPress();await settle();assert.equal(s.calls[0].path,'/warehouse/purchase/arrival/101/accept');assert.equal(s.calls[0].method,'PUT');assert.equal(s.calls[0].body.defectiveQuantity,1);assert.equal(s.calls[0].body.acceptanceStatus,1);
test('old acceptance navigation opens arrival history without submitting acceptance',async()=>{
const s=await screen({mode:'accept'});assert.equal(s.tree.type,'ArrivalHistory');assert.equal(s.tree.props.canSupplement,true);assert.equal(s.calls.length,0);assert.equal(s.button('确认提交'),null);
});
test('uncertain acceptance cannot be blindly resubmitted or edited',async()=>{
const s=await screen({mode:'accept',failure:true});s.button('核对预览').props.onPress();s.render();s.button('确认提交').props.onPress();await settle();s.render();assert.equal(s.button('核对后重试原请求').props.disabled,true);assert.equal(s.button('返回修改').props.disabled,true);assert.equal(s.calls.length,1);
test('a rejected old photo-free draft can be checked, repaired and retried using its original key',async()=>{
const s=await screen({failure:true,lookup:null});
s.restore({quantity:'2',date:'2026-10-19',attempted:true,photos:[],requestKey:'old-stable-key',preview:{body:{purchaseRequestId:10,arrivalQuantity:2,photoIds:[]}}});
s.button('核对提交结果').props.onPress();await settle();s.render();
assert.equal(s.calls[0].path,'/warehouse/purchase/arrival/10/submission');assert.equal(s.calls[0].query.requestKey,'old-stable-key');assert.equal(s.photos().props.readonly,false);assert.ok(s.button('核对预览'));
s.photos().props.onChange([{id:'11111111-1111-4111-8111-111111111111'}]);s.render();s.button('核对预览').props.onPress();s.render();s.button('确认提交').props.onPress();await settle();
assert.equal(s.calls.at(-1).body.requestKey,'old-stable-key');assert.equal(s.calls.at(-1).body.photoIds.length,1);
});
test('recovering an already-saved photo-free arrival offers direct supplements instead of a duplicate registration',async()=>{
const s=await screen({lookup:{id:708,arrivalNo:'DH-708',arrivalQuantity:2,photos:[]}});
s.restore({quantity:'2',date:'2026-10-19',attempted:true,requestKey:'original',preview:{body:{purchaseRequestId:10,photoIds:[]}}});
s.button('核对提交结果').props.onPress();await settle();s.render();
assert.equal(s.photos().props.arrivalId,708);assert.equal(s.photos().props.supplemental,true);assert.equal(s.button('确认提交'),null);assert.equal(s.calls.filter(call=>call.method==='POST').length,0);
});

View File

@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash} from 'node:crypto';
import {downloadLegacyPackage} from '../src/core/legacy-package-download.ts';
import {productionAppSigner,getOfficialPackage,officialAppInternalOrigin} from '../src/core/official-app-update.ts';
const bytes=Buffer.alloc(600000,7),hash=createHash('sha256').update(bytes).digest('hex');
const release={environment:'prod',packageName:'cn.cmvr.wms',versionCode:15,versionName:'1.0.3',sha256:hash,size:bytes.length,signerSha256:productionAppSigner,downloadPath:`/static/mobile/cmvr-wms-prod-v15-${hash}.apk`,notes:[]};
function files(initial){let content=initial;const calls=[];return {calls,cacheDirectory:'file:///cache/',async getInfoAsync(){return {exists:!!content,size:content?.length};},async deleteAsync(){content=undefined;},async readAsStringAsync(uri,options){return content.subarray(options.position,options.position+options.length).toString('base64');},createDownloadResumable(url,uri,options,progress){calls.push(url);return {async downloadAsync(){content=bytes;progress({totalBytesWritten:bytes.length});return {status:200,uri};},async pauseAsync(){}};}};}
test('legacy updates download inside the app using the selected company network and verify all bytes',async()=>{
const fs=files(),events=[],uri=await downloadLegacyPackage(release,officialAppInternalOrigin,fs,new AbortController().signal,(...event)=>events.push(event));
assert.equal(fs.calls[0],officialAppInternalOrigin+release.downloadPath);assert.match(uri,/^file:\/\/\/cache\/.*\.apk$/);assert.deepEqual(events.at(-1),['verifying',100]);
await downloadLegacyPackage(release,officialAppInternalOrigin,fs,new AbortController().signal,()=>{});assert.equal(fs.calls.length,1);
});
test('corrupt or cancelled compatibility downloads never return an installable file',async()=>{
await assert.rejects(downloadLegacyPackage(release,officialAppInternalOrigin,files(Buffer.alloc(bytes.length,8)),new AbortController().signal,()=>{}),/校验失败/);
const controller=new AbortController();controller.abort();const fs=files();await assert.rejects(downloadLegacyPackage(release,officialAppInternalOrigin,fs,controller.signal,()=>{}),/取消/);assert.equal(fs.calls.length,0);
await assert.rejects(downloadLegacyPackage(release,'https://other.example',files(),new AbortController().signal,()=>{}),/地址无效/);
});
test('official manifest requests can use the same internal connection without external Internet access',async()=>{
let requested;await getOfficialPackage(new AbortController().signal,undefined,async url=>{requested=url;return new Response(JSON.stringify(release));},officialAppInternalOrigin);assert.ok(requested.startsWith(officialAppInternalOrigin+'/static/mobile/'));
});

View File

@ -34,7 +34,7 @@ test('home keeps all allowed field-operation shortcuts without the oversized mar
'expo-constants':{},'expo-updates':{},'../ui':{Card:'Card',Icon:'Icon',Avatar:'Avatar',Heading:'Heading',Note:'Note',s:{row:{},page:{}},useTheme:()=>({})},
'../typography':{Text:'Text',useReadingScale:()=>1},'../core/preferences':{},'../core/workspace-tasks':{workspaceTasks,shortcutOrder},'../core/workspace-layout':{workspaceColumns},'../core/account':{imagePath:()=>''},'../files':{usePrivateImage:()=>undefined}});
const all=nodes(module.Workspace({api:{},user:{userName:'测试管理员'},modules,ai:true,open:v=>opened.push(v),go:v=>visited.push(v)}));
for(const title of ['到货验收','待入库','物料领用','移库','现场盘点']){
for(const title of ['到货登记','待入库','物料领用','移库','现场盘点']){
const node=all.find(n=>n.props.accessibilityLabel===title&&typeof n.props.style==='function');assert.ok(node);node.props.onPress();
assert.equal(node.props.style({pressed:false}).flexBasis,workspaceColumns(width,fontScale)===1?'100%':'47%');
}

View File

@ -4,12 +4,12 @@ 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(){
function setup(assets=[{uri:'file:///cache/picked.apk',name:'picked.apk'}]){
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};
vm.runInNewContext(code,{exports,require:n=>({'react-native':{Platform:{OS:'android'}},'expo-document-picker':{getDocumentAsync:async()=>({canceled:false,assets})},'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')));
@ -19,3 +19,7 @@ test('Android downloads write streamed chunks directly to disk and only preview
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);
});
test('multi-file selection preserves every source and releases unused file handles safely',async()=>{
const {api,removed}=setup([{uri:'file:///cache/a.pdf',name:'a.pdf'},{uri:'file:///cache/b.pdf',name:'b.pdf'}]);const files=await api.pickManagedFiles();assert.deepEqual(Array.from(files,f=>f.name),['a.pdf','b.pdf']);for(const source of files){assert.equal((await source.read(0,16)).length,16);source.close();}assert.ok(removed.includes('file:///cache/a.pdf'));assert.ok(removed.includes('file:///cache/b.pdf'));
});

View File

@ -16,7 +16,7 @@ function setup(shared={files:new Map(),preferences:new Map()},scope='one',versio
const preferences={readPreference:async(scope,key)=>shared.preferences.get(scope+'|'+key)||null,savePreference:async(scope,key,value)=>shared.preferences.set(scope+'|'+key,value)};
const fileSystem={File,Directory,Paths:{cache:'cache'},FileMode:{ReadOnly:'read'}};
const cacheExports={};vm.runInNewContext(ts.transpileModule(readFileSync(new URL('../src/package-cache.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,{exports:cacheExports,require:name=>({'expo-file-system':fileSystem,'./core/preferences':preferences,'./core/package-cache':cacheCore}[name])});
const api=new ApiClient('http://127.0.0.1:8080',()=>{},async()=>new Response(JSON.stringify({code:200,data:release}),{headers:{'Content-Type':'application/json'}}));api.authenticate('test');
const api=new ApiClient(features.baseUrl||'http://127.0.0.1:8080',()=>{},async()=>new Response(JSON.stringify({code:200,data:release}),{headers:{'Content-Type':'application/json'}}));api.authenticate('test');
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':{Platform:{OS:'android'},Linking:{openURL:async url=>opened.push(url)},NativeModules:{CmvrApkVerification:features.missingVerifier?undefined:bridge},DeviceEventEmitter:{addListener:(_name,fn)=>{listener=fn;return{remove(){listener=null}}}},AppState:{addEventListener:()=>({remove(){}})}},'expo-constants':{__esModule:true,default:{expoConfig:{extra:{environment:features.environment||'dev'}}}},'expo-application':{nativeBuildVersion:String(features.nativeBuild||9)},'expo-file-system':fileSystem,'expo/fetch':{},'./core/package-update':core,'./core/official-app-update':{...official,getOfficialPackage:async(_signal,expected)=>official.officialPackage({environment:'prod',packageName:'cn.cmvr.wms',versionCode:version,versionName:'1.0.2',sha256:features.wrongOfficial?'b'.repeat(64):hash,size:100,signerSha256:official.productionAppSigner,downloadPath:'/static/mobile/cmvr-wms-prod-v'+version+'-'+hash+'.apk',notes:[]},expected)},'./core/native-package-download':native,'./core/preferences':preferences,'./core/package-cache':cacheCore,'./package-cache':cacheExports,'./ui':{},'./typography':{},'./UpdateNotes':{UpdateNotes:'UpdateNotes'}};
const code=ts.transpileModule(readFileSync(new URL('../src/PackageUpdates.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText,exports={};vm.runInNewContext(code,{exports,require:name=>Object.hasOwn(mocks,name)?mocks[name]:require(name),AbortController,Date,Number,Math,setTimeout,clearTimeout});
const render=()=>{cursor=0;result=exports.usePackageUpdates(api,scope,true);while(effects.length)effects.shift()();return result};
@ -71,18 +71,18 @@ test('ignoring a downloaded version does no file work on startup and manual chec
});
test('legacy installation failure keeps the cached download and offers an explicit credential-free browser recovery',async()=>{
test('installation rejection preserves the download and never opens a browser',async()=>{
for(const features of [{environment:'prod',missingVerifier:true},{environment:'prod',verifyFailure:true}]){
const h=setup(undefined,'one',10,features),name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.render();await settle();assert.equal(h.render().phase,'ready');h.render().install();await settle();
const c=h.render();assert.ok(c.error);assert.doesNotMatch(c.error,/签名或版本不匹配/);assert.equal(h.state().installed,0);assert.equal(h.state().opened.length,0);assert.equal(c.canRecover,true);
c.recover();await settle();assert.deepEqual(h.state().opened,['https://wms.svc.cmvr-iot.icu/static/mobile/cmvr-wms-prod-v10-'+h.release.sha256+'.apk']);assert.equal(h.state().deleted,0);assert.equal(h.render().phase,'ready');
const h=setup(undefined,'one',10,features),name=h.release.sha256+'-123-abc.apk';h.shared.files.set('file:///cache/app-updates/'+name,Buffer.alloc(100,7));h.render();await settle();h.render().install();await settle();
assert.ok(h.render().error);assert.doesNotMatch(h.render().error,/浏览器/);assert.equal(h.state().installed,0);assert.equal(h.state().opened.length,0);assert.equal(h.render().recover,undefined);assert.equal(h.state().deleted,0);
}
});
test('a changed official package or a development session cannot open the production recovery installer',async()=>{
const h=setup(undefined,'one',10,{environment:'prod',wrongOfficial:true});h.render();await settle();h.render().recover();await settle();assert.equal(h.state().opened.length,0);assert.match(h.render().error,/无效|变化/);
const dev=setup();dev.render();await settle();assert.equal(dev.render().canRecover,false);dev.render().recover();await settle();assert.equal(dev.state().opened.length,0);
test('downloads follow the selected internal or external API connection',async()=>{
for(const baseUrl of ['http://192.168.28.10/prod-api','https://wms.svc.cmvr-iot.icu/prod-api']){
const h=setup(undefined,'one',10,{environment:'prod',baseUrl});h.render();await settle();h.render().download();await settle();assert.equal(h.options().url,baseUrl+h.release.downloadPath);assert.equal(h.state().opened.length,0);h.finish();await settle();
}
});
test('known old production APKs go directly to the official browser installer instead of downloading twice',async()=>{
const h=setup(undefined,'one',10,{environment:'prod',nativeBuild:3});h.render();await settle();const c=h.render();assert.equal(c.legacyInstaller,true);c.download();await settle();assert.equal(h.options(),undefined);assert.equal(h.state().installed,0);assert.equal(h.state().signatureChecks,0);assert.equal(h.state().opened.length,1);assert.equal(h.shared.files.size,0);
test('old version numbers no longer force an HTTP link into the browser',async()=>{
const h=setup(undefined,'one',10,{environment:'prod',nativeBuild:3});h.render();await settle();h.render().download();await settle();assert.ok(h.options());assert.equal(h.state().opened.length,0);h.finish();await settle();h.render().install();await settle();assert.equal(h.state().signatureChecks,1);assert.equal(h.state().installed,1);
});

View File

@ -13,7 +13,7 @@ test('only-mine control toggles and exposes its state to accessibility',()=>{
});
test('purchase filter is retained in account-scoped cache and sent for every result page',()=>{
const app=readFileSync(new URL('../src/screens/BusinessList.tsx',import.meta.url),'utf8');
assert.match(app,/scope\+'\|'\+module\.key\+'\|'\+JSON\.stringify\(initialQuery\)/);
assert.match(app,/scope\+'\|'\+module\.key\+'\|'\+module\.path\+'\|'\+JSON\.stringify\(initialQuery\)/);
assert.match(app,/useState\(cached\.current\?\.onlyMine\?\?false\)/);
assert.match(app,/queue:arrivalQueue,compact:compactAmounts,onlyMine/);
assert.match(app,/\['arrival','purchase','pending'\]\.includes\(module\.key\)&&onlyMine\?\{onlyMine:true\}/);

View File

@ -0,0 +1,15 @@
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 * as network from '../src/core/network.ts';import * as moduleCore from '../src/core/modules.ts';
const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript');
test('network switching and return-to-login are visible while restoring an unreachable internal session',async()=>{
const slots=[],saved=[],effects=[];let cursor=0;const react={...React,useState:initial=>{const i=cursor++;if(!(i in slots))slots[i]=initial;return[slots[i],value=>{slots[i]=typeof value==='function'?value(slots[i]):value;}];},useRef:initial=>{const i=cursor++;return slots[i]??={current:initial};},useMemo:fn=>fn(),useCallback:fn=>fn,useEffect:fn=>effects.push(fn)};
const ui={useTheme:()=>({bg:'#fff'}),s:{},Card:'Card',Heading:'Heading',Button:'Button',Note:'Note'},native={Platform:{OS:'android'},View:'View',ScrollView:'ScrollView',ActivityIndicator:'ActivityIndicator'};
const mocks={react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-constants':{__esModule:true,default:{expoConfig:{extra:{environment:'prod',apiUrl:network.PRODUCTION_INTERNAL_URL}}}},'expo-secure-store':{deleteItemAsync:async()=>{}},'./core/network':network,'./core/modules':moduleCore,'./ui':ui,'./typography':{Text:'Text'},'./PackageUpdates':{usePackageUpdates:()=>({})},'./core/server-address':{serverTokenKey:()=> 'fixture'},'./screens/LoginView':{LoginView:'LoginView'}};
const exports={};const code=ts.transpileModule(readFileSync(new URL('../src/App.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText;
vm.runInNewContext(code+'\nexports.testRoot=Root;exports.testConnection=ProductionConnection;',{exports,require:name=>mocks[name]||{},setTimeout,clearTimeout,AbortController});
const render=()=>{cursor=0;return exports.testRoot({server:network.PRODUCTION_INTERNAL_URL,saveServer:async value=>saved.push(value),updates:{}});};
function nodes(tree){const all=[];function walk(node){if(!node||typeof node!=='object')return;all.push(node);React.Children.toArray(node.props?.children).forEach(walk);}walk(tree);return all;}
let all=nodes(render());const connection=all.find(node=>node.type===exports.testConnection);assert.ok(connection,'Switching must not wait for authentication');
const back=all.find(node=>node.type==='Button'&&node.props.title==='返回登录');assert.ok(back);back.props.onPress();all=nodes(render());assert.ok(all.some(node=>typeof node.type==='function'&&node.type.name==='Login'));
cursor=0;const buttons=nodes(exports.testConnection(connection.props)).filter(node=>node.type==='Button');assert.deepEqual(buttons.map(node=>node.props.title),['外网','公司内网']);buttons[0].props.onPress();await new Promise(resolve=>setImmediate(resolve));assert.equal(saved.at(-1),network.PRODUCTION_PUBLIC_URL);
});

View File

@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@ -198,6 +199,27 @@ public class PurchaseRequestController extends BaseController
return result;
}
/** Evidence lookup includes completed receipts and zero-price items, independently of money display. */
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
@GetMapping("/photo-records")
public TableDataInfo photoRecords(@RequestParam Long purchaseBatchId, String materialName) {
if(purchaseBatchId==null||purchaseBatchId<=0)throw new com.ruoyi.common.exception.ServiceException("请先选择采购批次");
var query=new PurchaseRequest();query.setPurchaseBatchId(purchaseBatchId);query.setMaterialName(materialName);
startPage();
var rows=purchaseRequestService.selectPurchaseRequestList(query);
var result=getDataTable(rows);result.setRows(PurchaseQuoteAccess.rows(rows));return result;
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
@GetMapping("/batch/photo-records")
public TableDataInfo photoRecordBatches(String keyword) {
var query=new PurchaseBatch();query.setKeyword(keyword);
startPage();
var rows=purchaseBatchService.selectPurchaseBatchList(query);
var result=getDataTable(rows);result.setRows(rows.stream().map(PurchaseQuoteAccess::view).toList());
return result;
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:list,warehouse:purchase:manage')")
@GetMapping("/summary")
public AjaxResult summary()
@ -330,6 +352,12 @@ public class PurchaseRequestController extends BaseController
{
return success(purchaseArrivalService.selectPurchaseArrivalList(requestId).stream().map(PurchaseQuoteAccess::view).toList());
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
@GetMapping("/arrival/{requestId}/submission")
public AjaxResult arrivalSubmission(@PathVariable Long requestId,@RequestParam String requestKey){
var arrival=purchaseArrivalService.findSubmittedArrival(requestId,requestKey);
return success(arrival==null?null:PurchaseQuoteAccess.view(arrival));
}
public record CancelRemaining(java.math.BigDecimal expectedQuantity,String reason){}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
@PostMapping("/{id}/cancel-remaining") @Log(title="取消未到货采购",businessType=BusinessType.UPDATE)
@ -353,6 +381,13 @@ public class PurchaseRequestController extends BaseController
return toAjax(purchaseArrivalService.acceptPurchaseArrival(id, request));
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
@Log(title = "到货转待入库", businessType = BusinessType.UPDATE)
@PutMapping("/arrival/{id}/ready-for-inbound")
public AjaxResult readyForInbound(@PathVariable Long id) {
return toAjax(purchaseArrivalService.prepareArrivalForReceipt(id));
}
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:edit,warehouse:purchase:manage')")
@Log(title = "撤销采购到货验收", businessType = BusinessType.UPDATE)
@PutMapping("/arrival/{id}/revoke")

View File

@ -63,12 +63,10 @@ public final class AssistantBusinessRules {
case "batch.delete" -> List.of("按现有采购批次业务校验删除,不自动删除明细或已经发生的到货、库存业务。");
case "batch.assign" -> List.of("将明确的采购明细分配到指定已有批次,需用户确认目标批次;不是重新采购,也不自动锁价或登记到货。");
case "batch.query" -> List.of("按批次编号或名称查询;批次可包含多个项目及多种物品,不能把批次当作单个物品或单个项目。");
case "arrival.register" -> List.of("仅登记本次到货,进入待验收,不自动验收或入库;必须关联已有且可到货的采购明细,不能只凭物品名称跨批次猜单。", "采购须已锁价并有供应商,本次数量不得超过剩余可登记到货数;图中采购总数不等于本次到货数。");
case "arrival.registerAndAccept" -> List.of("仅当用户明确表示本次货物全部验收合格时,才合并登记到货与合格验收;生成待入库,不直接增加库存。", "未说明验收结论时询问或仅登记到货,不得把签收到货猜成验收合格。");
case "arrival.accept" -> List.of("对待验收到货记录验收,区分合格、部分不合格和全部不合格;不合格数不得超过本次到货数。", "合格部分生成待入库,不直接增加现有库存;验收说明与到货备注是不同字段。");
case "arrival.revoke" -> List.of("撤销到货验收须填写原因;存在后续入库等业务时先按业务链撤销,不自动把库存退回供应商。");
case "arrival.delete" -> List.of("只删除待验收到货记录,已验收记录先按业务流程处理,不能直接删除历史。");
case "arrival.query" -> List.of("按采购明细查看分次到货和验收记录,不把它当作仓库入库记录。");
case "arrival.register" -> List.of("登记本次到货后转待入库,不需要线下验收,不直接增加库存;必须关联已有且可到货的采购明细,不能只凭物品名称跨批次猜单。", "采购必须有有效批次和供应商,未报价也允许到货和入库,成本保留待补价;到货照片至少1张,本次数量不得超过剩余可登记到货数;图中采购总数不等于本次到货数。");
case "arrival.delete" -> List.of("只删除历史未衔接到货记录,已转待入库记录先按入库撤销或退货流程处理,不能直接删除历史。");
case "arrival.ready" -> List.of("将历史未衔接到货转待入库,必须先补传照片;不填造验收人或验收时间,未报价也可入库。");
case "arrival.query" -> List.of("按采购明细查看分次到货记录,不把它当作仓库入库记录。");
case "purchase.return" -> List.of("采购退货必须关联有效到货记录;退货数量、日期和原因须明确。是否同时取消对应采购数量是独立选择,不替用户默认决定。");
case "stock.query" -> List.of("库存按所属项目、物品和库区区分;同名不同规格、品牌或单位不能合并。未知成本不能当作0。");
case "stock.events", "stock.adjustments" -> List.of("查看明确项目和物品的库存流水或成本调整记录;仅查询,不调整库存或成本。");
@ -76,7 +74,7 @@ public final class AssistantBusinessRules {
case "stock.revokeMove" -> List.of("撤销明确的移库记录,需要原因;后续库存已使用时可能必须先撤销后续业务,不能直接补造反向移库代替撤销。");
case "receipt.query" -> List.of("查询入库记录,可按入库状态区分待入库根记录与实际入库分次记录;已到货不等于已入库。");
case "receipt.pending" -> List.of("专门查询待入库根记录,服务端固定待入库状态;用户说待入库、尚未入库或待收货入库时使用本查询,不混入已入库记录。");
case "receipt.receive" -> List.of("从采购验收或生产完工产生的待入库根记录分次入库;必须指定本次库区和数量。", "数量不得超过剩余待入库数;确认后才增加库存。采购归还用途的入库还会按照原采购关联处理借用归还。");
case "receipt.receive" -> List.of("从采购到货或生产完工产生的待入库根记录分次入库;必须指定本次库区和数量。", "数量不得超过剩余待入库数;确认后才增加库存。采购归还用途的入库还会按照原采购关联处理借用归还。");
case "receipt.revoke" -> List.of("撤销的是明确的一次已入库记录,不是到货验收;撤销后回到待入库,采购锁价费用不会因此自动取消。", "必须区分撤销全部与部分数量,未明确时先询问;部分撤回仅适用于具有待入库父记录的分次入库,历史/期初记录只能整条撤销。后续使用可能阻止撤销。");
case "loan.borrow" -> List.of("借用是两个不同项目之间的库存转移:减少借出项目原库区库存,增加借入项目目标库区库存,同时记录借用。", "指定物品、两项目、两库区及本次数量,不是普通领用,也不是只登记不改变库存。");
case "loan.return" -> List.of("按已有有效借用记录归还,其项目及物品由借用记录决定。来源库区属于借入项目,目标库区属于借出项目。", "本次归还数不得超过未归还数和借入项目来源库区可用库存;采购归还走归还用途的采购和入库流程。");

View File

@ -1323,7 +1323,7 @@ public class AssistantModelClient {
+ "关联字段有ref标记,名称/编号未知系统ID时,必须填名称字符串或遵循inputHint的候选对象;常见字段有keyword/spec/brand/batchNo/supplierName/projectName,BOM用versionTag限定版本。未知子字段省略。不得要求用户提供内部ID,也不要因缺ID而先询问是否查询。系统会按描述检索现有记录并显示未匹配或多候选。"
+ "单据表头明确写出的供应商、批次号、项目名称必须分别带入相关行候选对象的supplierName、batchNo、projectName,不要只放在备注中;每行品牌和规格也必须保留,以防匹配到其他供应商、批次或规格的货物。"
+ "例如用户明确登记到货,识别两行螺丝M6×20测试牌12个、支架L型3个:必须kind=draft/action=arrival.register,生成两行purchaseRequestId分别为{keyword:'螺丝',spec:'M6×20',brand:'测试牌'}和{keyword:'支架',spec:'L型'},arrivalQuantity分别12和3,保留每行_sourceRow/_sourceText;不能因为没有采购明细ID而返回clarify。"
+ "到货单不代表合格验收;用户只说到了应拟arrival.register,明确说验收合格才能拟arrival.registerAndAccept或arrival.accept。"
+ "采购线下流程只有采购申请、到货、入库,不再办理线下验收。到货拟arrival.register,登记后转待入库,未报价也可入库。线上资料进度的申请、合同、验收、付款独立保留。"
+ "意图已经明确时应生成可编辑draft表格,即使部分关联、日期或必填信息尚缺失;未知普通字段填null,由表格标注待补充。只有无法确定用户要办理哪种业务或存在互相冲突的意图,才用clarify追问一个关键问题。'确认'等聊天文字不具有执行权限,提示点击卡片确认。"
+ "历史对话最多10轮,currentDraft是当前结构化任务;过时对话不能覆盖当前草稿。"
+ "lastQuery独立保存最近查询的action、rows条件及有限结果。续查同一业务时继承lastQuery.rows中未要求修改的条件,只替换或清除本次明确的字段,保留项目、库区、状态等其他限定;'全部项目'表示清除项目条件,'全部状态'表示清除状态条件。只有切换业务或明确重新查询才不沿用旧条件。不得把currentDraft的写字段当作查询条件,不得把查询条件写回currentDraft。"

View File

@ -50,7 +50,7 @@ public class AssistantProductActions {
public void prepare(String action,Map<String,Object> row,Map<String,Object> snapshots,List<String> errors) {
try {
if(action.equals("product.versionCreate")) {
var source=products.requireProduct(id(row,"sourceProductId"));
var source=products.requireProductWrite(id(row,"sourceProductId"));
row.put("sourceVersion",source.getVersion());row.put("seriesVersion",source.getSeriesVersion());
if(row.get("copyBomId")!=null)row.put("copyBomVersion",products.sourceBomVersion(source.getId(),id(row,"copyBomId")));
// Existing family name is authoritative; legacy products need an explicit family and source edition name.
@ -60,7 +60,7 @@ public class AssistantProductActions {
}
if(action.equals("product.save")) {
if(row.get("id")!=null) {
var current=products.requireProduct(id(row,"id"));snapshots.put("productMetadata",json.convertValue(current,Map.class));
var current=products.requireProductWrite(id(row,"id"));snapshots.put("productMetadata",json.convertValue(current,Map.class));
row.put("seriesVersion",current.getSeriesVersion());
boolean naming=row.get("seriesName")!=null||row.get("editionTag")!=null;
if(naming) {
@ -72,12 +72,13 @@ public class AssistantProductActions {
(str(row,"seriesName").isBlank()||str(row,"editionTag").isBlank()))errors.add("请同时明确产品系列名称和产品版本名称;已有系列可只修改其中一项,另一项保留");
}
if(action.equals("product.attachmentUpload")) {
snapshots.put("attachmentTarget",json.convertValue(products.requireProduct(id(row,"id")),Map.class));
snapshots.put("attachmentTarget",json.convertValue(products.requireProductWrite(id(row,"id")),Map.class));
var file=uploads.businessFile(str(row,"attachmentId"));
files.validateUpload(file); // Read-only validation; no permanent product file yet.
row.put("operationNotice","确认后仅保存附件到所选产品版本,不读取文件正文、不更新BOM或采购价格。");
}
if(Set.of("product.attachmentRemove","product.attachmentDownload").contains(action)) {
if(action.equals("product.attachmentRemove"))products.requireProductWrite(id(row,"id"));
var file=files.list(id(row,"id")).stream().filter(item->Objects.equals(item.get("id"),row.get("attachmentId"))).findFirst()
.orElseThrow(()->new ServiceException("该附件不属于所选产品版本,或已移除,请重新选择"));
snapshots.put("productAttachment",file);

View File

@ -252,19 +252,9 @@ public class BusinessActionRegistry {
if("loan.revokeReturn".equals(action))payload.put("key",checked.get("originalReturnKey"));
}
Object response;
if("arrival.registerAndAccept".equals(action)) {
response=invoke(definition,payload);
Map<String,Object> data=asMap(((Map<?,?>)response).get("data"));
var accept=new LinkedHashMap<String,Object>(); accept.put("id",data.get("id"));
accept.put("acceptanceStatus",1); accept.put("defectiveQuantity",BigDecimal.ZERO);
accept.put("acceptanceRemark",payload.get("acceptanceRemark"));
permissions.require(action("arrival.accept").method(),"验收到货");
invoke(action("arrival.accept"),accept);
} else {
Action execution=executionAction(definition,checked);
if(execution!=definition)permissions.require(execution.method(),definition.label());
response=invoke(execution,payload);
}
Action execution=executionAction(definition,checked);
if(execution!=definition)permissions.require(execution.method(),definition.label());
response=invoke(execution,payload);
return mutationResult(definition, checked, response);
}
@ -963,7 +953,7 @@ public class BusinessActionRegistry {
case "projectType"->Map.of("RESEARCH","研发项目","PRODUCT","产品项目");
case "purchasePurpose"->Map.of("SELF","本项目使用","REPAY","归还借用");
case "purchaseStatus"->action.key().equals("batch.query")?Map.of("1","规划中","2","执行中","3","已结束","4","已归档","5","已取消"):Map.of("0","待采购","1","已下单","2","采购中","3","部分到货","4","已到齐","5","已取消");
case "acceptanceStatus"->Map.of("0","待验收","1","已验收","2","不合格");
case "acceptanceStatus"->Map.of("0","历史待衔接","1","已登记","2","历史拒收");
case "inStatus"->Map.of("0","待入库","1","已入库","2","已撤销");
case "checkStatus"->Map.of("0","待确认","1","已生效","2","已撤销");
case "status"->action.key().startsWith("feedback.")?Map.of("PENDING","待处理","PROCESSING","处理中","RESOLVED","已解决","DECLINED","不采纳"):
@ -1013,13 +1003,13 @@ public class BusinessActionRegistry {
labels.put("checkedIdentity","待核对姓名/账号");labels.put("matchResult","核对结果");
for(Action action:actions.values())for(Field field:action.fields())if(field.ref()==null)labels.put(field.key(),field.label());
labels.putAll(Map.of("name","名称","quantity","数量","remark","备注","brand","品牌","spec","规格型号","unit","单位","category","物品类别","kind","业务类型","date","业务日期"));
labels.putAll(Map.ofEntries(Map.entry("projectName","项目"),Map.entry("productName","物品"),Map.entry("materialName","物品"),Map.entry("requestNo","采购编号"),Map.entry("inNo","入库编号"),Map.entry("areaName","库区"),Map.entry("stockNum","库存数量"),Map.entry("supplierName","供应商"),Map.entry("purchaseBatchNo","采购批次"),Map.entry("batchNo","采购批次"),Map.entry("acceptedQuantity","已验收数量"),Map.entry("remainingQuantity","剩余数量"),Map.entry("arrivalNo","到货编号"),Map.entry("lenderProjectName","借出项目"),Map.entry("borrowerProjectName","借入项目"),Map.entry("outstandingQuantity","未还数量"),Map.entry("returnedQuantity","归还数量"),Map.entry("task_no","任务编号"),Map.entry("project_name","项目"),Map.entry("item_name","产品"),Map.entry("planned_quantity","计划数量"),Map.entry("good_quantity","合格数量"),Map.entry("status","状态"),Map.entry("averageUnitCost","平均单价"),Map.entry("stockAmount","库存金额"),Map.entry("budgetAmount","预算金额"),Map.entry("categoryName","经费科目"),Map.entry("committedAmount","已锁定费用"),Map.entry("availableAmount","剩余额度"),Map.entry("checkNo","盘点编号"),Map.entry("checkStatus","盘点状态"),Map.entry("inStatus","入库状态"),Map.entry("purchaseStatus","采购状态"),Map.entry("acceptanceStatus","验收状态")));
labels.putAll(Map.ofEntries(Map.entry("projectName","项目"),Map.entry("productName","物品"),Map.entry("materialName","物品"),Map.entry("requestNo","采购编号"),Map.entry("inNo","入库编号"),Map.entry("areaName","库区"),Map.entry("stockNum","库存数量"),Map.entry("supplierName","供应商"),Map.entry("purchaseBatchNo","采购批次"),Map.entry("batchNo","采购批次"),Map.entry("acceptedQuantity","已到货数量"),Map.entry("remainingQuantity","剩余数量"),Map.entry("arrivalNo","到货编号"),Map.entry("lenderProjectName","借出项目"),Map.entry("borrowerProjectName","借入项目"),Map.entry("outstandingQuantity","未还数量"),Map.entry("returnedQuantity","归还数量"),Map.entry("task_no","任务编号"),Map.entry("project_name","项目"),Map.entry("item_name","产品"),Map.entry("planned_quantity","计划数量"),Map.entry("good_quantity","合格数量"),Map.entry("status","状态"),Map.entry("averageUnitCost","平均单价"),Map.entry("stockAmount","库存金额"),Map.entry("budgetAmount","预算金额"),Map.entry("categoryName","经费科目"),Map.entry("committedAmount","已锁定费用"),Map.entry("availableAmount","剩余额度"),Map.entry("checkNo","盘点编号"),Map.entry("checkStatus","盘点状态"),Map.entry("inStatus","入库状态"),Map.entry("purchaseStatus","采购状态"),Map.entry("acceptanceStatus","到货状态")));
labels.putAll(Map.ofEntries(Map.entry("ledgerNo","资金流水编号"),Map.entry("bizNo","关联单号"),Map.entry("budgetDelta","预算变动"),Map.entry("committedDelta","费用变动"),Map.entry("balanceBudget","当前预算"),Map.entry("balanceCommitted","当前费用"),Map.entry("eventNo","库存流水编号"),Map.entry("eventType","库存变动"),Map.entry("originalCost","原始成本"),Map.entry("effectiveCost","当前成本"),Map.entry("active","有效"),Map.entry("event_no","库存流水编号"),Map.entry("event_type","库存变动"),Map.entry("old_amount","调整前金额"),Map.entry("new_amount","调整后金额"),Map.entry("difference","差额"),Map.entry("revision_no","调整编号"),Map.entry("create_time","时间"),Map.entry("createTime","时间"),Map.entry("create_by","操作人"),Map.entry("material_cost","材料总成本"),Map.entry("unit_cost","单位成本"),Map.entry("cost_status_text","成本状态"),Map.entry("unit_cost_status_text","单位成本状态"),Map.entry("settled_time","结算时间"),Map.entry("scrap_quantity","组装报废数量"),Map.entry("version_tag","BOM版本"),Map.entry("itemName","物品"),Map.entry("unitQuantity","单台用量"),Map.entry("unitCost","单位成本"),Map.entry("amount","金额"),Map.entry("source","取价来源"),Map.entry("complete","成本完整"),Map.entry("unknown","未知成本项数"),Map.entry("handled_quantity","已处理数量"),Map.entry("business_date","业务日期"),Map.entry("returnType","归还方式")));
labels.putAll(Map.ofEntries(Map.entry("userId","用户编号"),Map.entry("userName","登录账号"),Map.entry("nickName","用户姓名"),Map.entry("roleId","角色编号"),Map.entry("roleName","角色名称"),Map.entry("deptName","部门"),Map.entry("menuName","菜单名称"),Map.entry("perms","权限标识"),Map.entry("dictCode","字典项编号"),Map.entry("dictLabel","字典名称"),Map.entry("dictType","字典类型"),Map.entry("parentCode","大类编号"),Map.entry("noticeId","公告编号"),Map.entry("noticeTitle","公告标题"),Map.entry("operTime","操作时间"),Map.entry("loginTime","登录时间"),Map.entry("costTime","耗时(毫秒)"),Map.entry("count","记录数"),Map.entry("unpriced","未报价条数"),Map.entry("lockedAmount","锁定采购金额"),Map.entry("sourceProjectName","来源项目"),Map.entry("usageProjectName","使用项目"),Map.entry("area_name","库区"),Map.entry("categoryGroupName","物品大类"),Map.entry("reply","回复"),Map.entry("submitterName","反馈人"),Map.entry("handledTime","处理时间")));
labels.putAll(Map.of("seriesName","产品系列","editionTag","产品版本","itemCode","物品编码","defaultVersionTag","默认BOM版本"));
labels.put("id","记录编号");
labels.put("operation","操作类型"); labels.put("operator","操作人"); labels.put("version","版本");
labels.putAll(Map.ofEntries(Map.entry("taskNo","任务编号"),Map.entry("required","计划需用数量"),Map.entry("issued","已领数量"),Map.entry("returned","已退数量"),Map.entry("scrapped","报废数量"),Map.entry("available","可用库存"),Map.entry("outstanding","尚需数量"),Map.entry("requested","已申请采购"),Map.entry("purchasing","采购中数量"),Map.entry("pendingAcceptance","待验收数量"),Map.entry("pendingReceipt","待入库数量"),Map.entry("selfMade","在制覆盖数量"),Map.entry("shortage","库存缺口"),Map.entry("purchaseSuggestion","建议采购数量"),Map.entry("current_material_cost","当前材料成本"),Map.entry("openChildCount","未完成子任务数"),Map.entry("pendingReceiptCount","待入库记录数")));
labels.putAll(Map.ofEntries(Map.entry("taskNo","任务编号"),Map.entry("required","计划需用数量"),Map.entry("issued","已领数量"),Map.entry("returned","已退数量"),Map.entry("scrapped","报废数量"),Map.entry("available","可用库存"),Map.entry("outstanding","尚需数量"),Map.entry("requested","已申请采购"),Map.entry("purchasing","采购中数量"),Map.entry("pendingAcceptance","历史待衔接数量"),Map.entry("pendingReceipt","待入库数量"),Map.entry("selfMade","在制覆盖数量"),Map.entry("shortage","库存缺口"),Map.entry("purchaseSuggestion","建议采购数量"),Map.entry("current_material_cost","当前材料成本"),Map.entry("openChildCount","未完成子任务数"),Map.entry("pendingReceiptCount","待入库记录数")));
return labels;
}
private Map<String,Object> asMap(Object value) { return value==null?new LinkedHashMap<>():json.convertValue(value,MAP); }
@ -1177,11 +1167,9 @@ public class BusinessActionRegistry {
add("batch.assign","分配采购批次",PurchaseRequestController.class,"assignBatch","$body",ref("id","采购明细","purchase",true),ref("batchId","采购批次","batch",true));
query("batch.query","采购批次",PurchaseRequestController.class,"batchList","$body",text("keyword","批次编号或名称",false),ref("projectId","项目","project",false),ref("supplierId","供应商","supplier",false),text("materialName","物品关键词",false),select("progress","批次进度",false,"quote","待报价","confirm","待确认","open","采购中","completed","已结束"),date("beginDate","开始日期",false),date("endDate","结束日期",false));
Field[] arrival={ref("purchaseRequestId","采购明细","purchase",true),number("arrivalQuantity","本次到货数量",true),date("arrivalDate","到货日期",true),text("remark","到货备注",false)};
register("arrival.register","登记到货","登记后进入待验收,不自动验收或入库",PurchaseRequestController.class,"addArrival","$body",false,Map.of(),arrival);
register("arrival.registerAndAccept","登记到货并验收合格","明确确认本次货物全部合格后,登记并验收,生成待入库;不直接增加库存",PurchaseRequestController.class,"addArrival","$body",false,Map.of(),append(arrival,text("acceptanceRemark","验收说明",false)));
add("arrival.accept","验收到货",PurchaseRequestController.class,"acceptArrival","id,$body",ref("id","到货记录","arrival",true),select("acceptanceStatus","验收结果",true,"1","合格或部分合格","2","全部不合格"),number("defectiveQuantity","不合格数量",false),text("acceptanceRemark","验收说明",false));
add("arrival.revoke","撤销到货验收",PurchaseRequestController.class,"revokeArrival","id,$body",ref("id","到货记录","arrival",true),text("revokeRemark","撤销原因",true));
add("arrival.delete","删除待验收到货",PurchaseRequestController.class,"removeArrival","id",ref("id","到货记录","arrival",true));
register("arrival.register","登记到货","登记后转待入库,不需要线下验收;未报价也可入库,后补报价重算成本",PurchaseRequestController.class,"addArrival","$body",false,Map.of(),arrival);
add("arrival.delete","删除历史未衔接到货",PurchaseRequestController.class,"removeArrival","id",ref("id","到货记录","arrival",true));
add("arrival.ready","历史到货转待入库",PurchaseRequestController.class,"readyForInbound","id",ref("id","到货记录","arrival",true));
query("arrival.query","到货记录",PurchaseRequestController.class,"arrivalList","requestId",ref("requestId","采购明细","purchase",true));
add("purchase.return","采购退货",PurchaseReturnController.class,"returnGoods","$body",ref("arrivalId","到货记录","arrival",true),number("quantity","退货数量",true),flag("cancelPurchase","取消对应采购数量"),date("date","退货日期",true),text("remark","退货说明",true));
}
@ -1296,7 +1284,7 @@ public class BusinessActionRegistry {
query("expenseCategory.query","经费科目",ProjectInfoController.class,"categoryList","$body",text("categoryName","科目名称",false));
}
private Field[] purchaseQueryFields() {
return new Field[]{text("materialName","物品名称、型号或品牌关键词",false),ref("projectId","项目","project",false),ref("purchaseBatchId","采购批次","batch",false),ref("supplierId","供应商","supplier",false),ref("expenseCategoryId","经费科目","expense",false),ref("productionTaskId","生产任务","task",false),select("purchaseStatus","采购状态",false,"0","待采购","1","已下单","2","采购中","3","部分到货","4","已到齐","5","已取消"),flag("unbatched","仅未组批"),flag("priceLocked","已确认采购并锁价"),flag("notArrived","尚未全部到货验收"),flag("notReceived","尚未全部入库"),flag("pendingAcceptance","有待验收数量"),flag("arrivalReady","可登记到货"),text("purchaseBatchNo","采购批次编号",false),text("category","物品类别",false),text("applicantName","采购申请人",false)};
return new Field[]{text("materialName","物品名称、型号或品牌关键词",false),ref("projectId","项目","project",false),ref("purchaseBatchId","采购批次","batch",false),ref("supplierId","供应商","supplier",false),ref("expenseCategoryId","经费科目","expense",false),ref("productionTaskId","生产任务","task",false),select("purchaseStatus","采购状态",false,"0","待采购","1","已下单","2","采购中","3","部分到货","4","已到齐","5","已取消"),flag("unbatched","仅未组批"),flag("priceLocked","已确认采购并锁价"),flag("notArrived","尚未全部到货"),flag("notReceived","尚未全部入库"),flag("pendingAcceptance","有历史到货待衔接"),flag("arrivalReady","可登记到货"),text("purchaseBatchNo","采购批次编号",false),text("category","物品类别",false),text("applicantName","采购申请人",false)};
}
private Field[] receiptQueryFields() {
return new Field[]{ref("sourceProjectId","来源项目","project",false),text("productName","物品名称",false),text("keyword","单号、物品、型号或品牌关键词",false),ref("purchaseBatchId","采购批次","batch",false),ref("supplierId","供应商","supplier",false),ref("areaId","库区","area",false),select("sourceKind","来源类型",false,"PURCHASE","采购","PRODUCTION","生产","OTHER","其他"),text("inNo","入库编号",false)};
@ -1809,7 +1797,6 @@ public class BusinessActionRegistry {
if(action.key().startsWith("arrival.register")) {
Map<String,Object> purchase=asMap(snapshots.get("purchaseRequestId"));
if(!purchase.isEmpty()) {
if(!truth(purchase.get("priceLocked")) || purchase.get("finalUnitPrice")==null)errors.add("请先确认采购并锁定报价");
if(purchase.get("supplierId")==null)errors.add("采购批次未选择供应商");
if(truth(purchase.get("historical"))||"5".equals(Objects.toString(purchase.get("purchaseStatus"))))errors.add("该采购明细不能登记到货");
if(row.get("arrivalQuantity") instanceof BigDecimal n&&n.compareTo(decimal(purchase.get("remainingQuantity")))>0)errors.add("本次到货超过剩余可登记数量"+purchase.get("remainingQuantity"));

View File

@ -58,13 +58,13 @@ public class UploadTargets {
return com.ruoyi.project.workspace.ProjectDocumentService.MAX_BYTES;
}
case "product" -> {
plain(target, true); require("production:product:edit"); versions.requireProduct(target.targetId()); return 50*1024*1024;
plain(target, true); require("production:product:edit"); versions.requireProductWrite(target.targetId()); return 50*1024*1024;
}
case "purchase" -> {
require("warehouse:purchase:edit", "warehouse:purchase:manage");
if (target.targetId()==null || target.targetId()<=0 || !Set.of("batch","detail").contains(Objects.toString(target.type(),""))) throw new ServiceException("请先保存采购批次或明细");
if (purchases.list(target.type(),target.targetId()).stream().noneMatch(g->g.kind().equals(target.kind()))) throw new ServiceException("附件资料类型不正确");
return 10*1024*1024;
return PurchaseDocumentService.MAX_BYTES;
}
case "supplier" -> { plain(target,false); require("warehouse:purchase:edit","warehouse:purchase:manage"); return 10*1024*1024; }
case "feedback" -> { plain(target,false); return 5*1024*1024; }
@ -88,7 +88,7 @@ public class UploadTargets {
case "feedback" -> Set.of("png","jpg","jpeg","webp").contains(extension);
case "supplier" -> Set.of("png","jpg","jpeg","pdf").contains(extension);
case "product","assistantProduct" -> standard.contains(extension)||cad.contains(extension);
case "purchase" -> "OTHER".equals(target.kind()) ? standard.contains(extension) : extension.equals("pdf");
case "purchase" -> "OTHER".equals(target.kind()) ? standard.contains(extension) : "INVOICE".equals(target.kind()) ? Set.of("pdf","png","jpg","jpeg").contains(extension) : extension.equals("pdf");
default -> standard.contains(extension);
};
if (!allowed) throw new ServiceException("此附件格式不适合当前业务,请选择支持的文件类型");

View File

@ -19,7 +19,9 @@ import org.springframework.web.multipart.MultipartFile;
@Service
public class PurchaseAcceptanceGenerationService {
private final PurchaseAcceptanceReportService reports;private final PurchaseArrivalPhotoService photos;private final PurchaseDocumentService documents;private final JdbcTemplate db;private final ObjectMapper json;
public record Input(String requestId,PurchaseAcceptanceReportService.Fields fields) { }
public record Input(String requestId,PurchaseAcceptanceReportService.Fields fields,List<Long> selectedIds) {
public Input(String requestId,PurchaseAcceptanceReportService.Fields fields){this(requestId,fields,null);}
}
public PurchaseAcceptanceGenerationService(PurchaseAcceptanceReportService reports,PurchaseArrivalPhotoService photos,PurchaseDocumentService documents,JdbcTemplate db,ObjectMapper json){this.reports=reports;this.photos=photos;this.documents=documents;this.db=db;this.json=json;}
@Transactional(rollbackFor=Exception.class,isolation=Isolation.READ_COMMITTED)
public PurchaseDocumentService.Attachment generate(long id,String version,Input input)throws Exception{
@ -30,7 +32,7 @@ public class PurchaseAcceptanceGenerationService {
if(owners.isEmpty())throw new ServiceException("采购批次不存在");
if(!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以生成批次验收资料",403);
db.queryForList("select id from purchase_request where purchase_batch_id=? and del_flag='0' order by id for update",id);
var report=reports.export(id,version,input.fields());String fingerprint=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsBytes(report)));
var report=input.selectedIds()==null?reports.export(id,version,input.fields()):reports.export(id,version,input.fields(),input.selectedIds());String fingerprint=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((PurchaseAcceptancePdf.TEMPLATE_VERSION+":"+json.writeValueAsString(report)).getBytes(java.nio.charset.StandardCharsets.UTF_8)));
var previous=db.queryForList("select a.owner_id,cast(a.deleted as signed) deleted,g.target_type,g.target_id,g.document_kind from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=?",input.requestId());
if(!previous.isEmpty()){
var p=previous.get(0);
@ -42,7 +44,7 @@ public class PurchaseAcceptanceGenerationService {
var temporary=Files.createTempFile("purchase-acceptance-",".pdf");
try{
try(var output=Files.newOutputStream(temporary)){PurchaseAcceptancePdf.write(report,photoId->photos.content(photoId).bytes(),output,fingerprint);}
if(Files.size(temporary)>10L*1024*1024)throw new ServiceException("生成的验收资料超过单个附件10 MB限制,请联系管理员处理");
if(Files.size(temporary)>PurchaseDocumentService.MAX_BYTES)throw new ServiceException("生成的验收资料超过单个附件50 MB限制,请联系管理员处理");
byte[] bytes=Files.readAllBytes(temporary);String label=report.batchName().replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]","_");if(label.length()>120)label=label.substring(0,120);
return documents.uploadGenerated("batch",id,"ACCEPTANCE",input.requestId(),new GeneratedFile(label+"_验收资料_待签章.pdf",bytes));
}finally{Files.deleteIfExists(temporary);}

View File

@ -14,13 +14,13 @@ import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.util.Matrix;
/** 按原验收单重绘 A4 七列表格,照片仅取已通过验收的到货凭证,不含扫描章和签名。 */
/** 仪器设备验收报告:设备清单沿用七列表格,技术参数和签章区留空。 */
public final class PurchaseAcceptancePdf {
@FunctionalInterface public interface Photos { byte[] read(String id); }
private static final float X=62,W=464,H=841.92f,ROW=13;
private static final float[] WIDTHS={28,86,58,47,57,32,156};
private static final PDFont ENGLISH=new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD_OBLIQUE);
private final PDDocument doc;private final PDType0Font font;private PDPageContentStream pen;private float y;private int page;
private static final float X=80,W=451,H=841.92f,ROW=13;
public static final String TEMPLATE_VERSION="equipment-acceptance-compact-20261118";
private static final float[] WIDTHS={27,83,56,46,55,32,152};
private final PDDocument doc;private final PDType0Font font;private PDPageContentStream pen;private float y;private int page;private boolean listing;
private PurchaseAcceptancePdf(PDDocument doc)throws IOException{
this.doc=doc;
try(var input=PurchaseAcceptancePdf.class.getResourceAsStream("/fonts/NotoSerifSC-Regular.ttf")){
@ -32,26 +32,28 @@ public final class PurchaseAcceptancePdf {
}
public static void write(Report report,Photos photos,OutputStream output,String fingerprint)throws IOException{
try(var doc=new PDDocument(IOUtils.createTempFileOnlyStreamCache())){
var pdf=new PurchaseAcceptancePdf(doc);pdf.newPage();pdf.header(report.fields());pdf.tableHeader();
var pdf=new PurchaseAcceptancePdf(doc);pdf.newPage();pdf.header(report.fields());pdf.section("一、设备清单验收",24);pdf.listing=true;pdf.tableHeader();
int index=0;for(var row:report.lines())pdf.row(++index,row,photos);
pdf.footer(report.fields());pdf.pen.close();doc.getDocumentInformation().setTitle(report.batchName()+"材料及部件验收单");doc.getDocumentInformation().setCreator("设备仪器科综合管理系统");if(fingerprint!=null)doc.getDocumentInformation().setCustomMetadataValue("CMVR-Acceptance-Fingerprint",fingerprint);doc.save(output);
pdf.listing=false;pdf.footer(report.fields());pdf.pen.close();doc.getDocumentInformation().setTitle(report.batchName()+"仪器设备验收报告");doc.getDocumentInformation().setCreator("设备仪器科综合管理系统");if(fingerprint!=null)doc.getDocumentInformation().setCustomMetadataValue("CMVR-Acceptance-Fingerprint",fingerprint);doc.save(output);
}
}
private void newPage()throws IOException{
if(pen!=null)pen.close();var p=new PDPage(new PDRectangle(595.2f,H));doc.addPage(p);pen=new PDPageContentStream(doc,p);pen.setLineWidth(.45f);page++;y=page==1?66:74;
if(pen!=null)pen.close();var p=new PDPage(new PDRectangle(595.2f,H));doc.addPage(p);pen=new PDPageContentStream(doc,p);pen.setLineWidth(.6f);page++;y=page==1?80:58;
if(listing){section("一、设备清单验收(续)",24);tableHeader();}
}
private float bottom(){return page==1?761:777;}
private float bottom(){return 784;}
private void header(Fields f)throws IOException{
box(X,y,W,26,1);center("FINAL ACCEPTANCEREPORT",X,y+2,W,12,9.5f,ENGLISH);boldCenter("终验收报告",X,y+14,W,11,9);y+=26;
float a=114,b=162,c=188;
float r1=Math.max(15,Math.max(height("甲方:"+f.purchaser(),a,5.4f),height("乙方:"+f.supplier(),b,5.8f)));
float r2=Math.max(15,Math.max(height("合同号:"+f.contractNo(),a,6),height("项目号:"+f.projectNo(),b,6)));
float address=height("地址:\n"+f.address(),c,7);if(address>r1+r2)r1+=address-r1-r2;
cell("甲方:"+f.purchaser(),X,y,a,r1,5.4f,false);cell("乙方:"+f.supplier(),X+a,y,b,r1,5.8f,false);cell("地址:\n"+f.address(),X+a+b,y,c,r1+r2,7,false);y+=r1;
cell("合同号:"+f.contractNo(),X,y,a,r2,6,false);cell("项目号:"+f.projectNo(),X+a,y,b,r2,6,false);y+=r2;
float r3=Math.max(15,Math.max(height("项目描述:"+f.description(),a+b,7),height("配送位置:"+f.deliveryLocation(),c,6)));
cell("项目描述:"+f.description(),X,y,a+b,r3,7,false);cell("配送位置:"+f.deliveryLocation(),X+a+b,y,c,r3,6,false);y+=r3+9;
boldCenter("仪器设备验收报告",X,y,W,32,20);y=128;
headerRow("设备名称",f.description());headerRow("合同编号",f.contractNo());
headerRow("甲方(验收方)",f.purchaser());headerRow("乙方(供货方)",f.supplier());
headerRow("到货日期",f.arrivalDate()==null?"":f.arrivalDate().toString());
headerRow("验收地点",f.deliveryLocation());headerRow("验收日期",f.date()==null?"":f.date().toString());
}
private void headerRow(String label,String value)throws IOException{
float h=Math.max(28,height(value,W-94,11));
cell(label,X,y,94,h,11,true);cell(value,X+94,y,W-94,h,11,false);y+=h;
}
private void section(String label,float h)throws IOException{box(X,y,W,h,1);boldCenter(label,X,y,W,h,12);y+=h;}
private void tableHeader()throws IOException{
String[] labels={"序号","名称","规格型号/参数要求","采购数量","是否已到货","到货记录","图片"};float x=X;
for(int i=0;i<labels.length;i++){box(x,y,WIDTHS[i],16,.85f);center(labels[i],x,y,WIDTHS[i],16,i==2?5.5f:6.2f,font);x+=WIDTHS[i];}y+=16;
@ -72,41 +74,42 @@ public final class PurchaseAcceptancePdf {
float h=Math.max(ROW,take*7.2f+2);if(first)h=Math.max(h,Math.min(imageRows*13f,bottom()-y));float x=X;
for(int i=0;i<7;i++){box(x,y,WIDTHS[i],h,1);if(i<6){var all=texts.get(i);var part=all.subList(Math.min(offset,all.size()),Math.min(offset+take,all.size()));drawLines(part,x,y,WIDTHS[i],h,sizes[i],i!=1&&i!=2);}x+=WIDTHS[i];}
if(first&&!pictures.isEmpty()){
float cell=W-WIDTHS[6];for(int i=0;i<pictures.size();i++){
var image=pictures.get(i);int columns=Math.min(6,pictures.size());float slot=WIDTHS[6]/columns;float maxH=Math.min(26,(h-1)/Math.max(1,imageRows));
float scale=Math.min((slot-2)/image.getWidth(),maxH/image.getHeight());float iw=image.getWidth()*scale,ih=image.getHeight()*scale;
float px=X+cell+(i%columns)*slot+(slot-iw)/2,py=y+(i/columns)*maxH+(maxH-ih)/2;
pen.drawImage(JPEGFactory.createFromImage(doc,image,.85f),px,H-py-ih,iw,ih);
int columns=Math.min(6,pictures.size());float maxH=Math.min(26,(h-1)/Math.max(1,imageRows));
float groupTop=y+(h-imageRows*maxH)/2;
for(int start=0;start<pictures.size();start+=columns){
var strip=pictures.subList(start,Math.min(start+columns,pictures.size()));
float ratio=0;for(var image:strip)ratio+=(float)image.getWidth()/image.getHeight();
float imageHeight=Math.min(maxH,(WIDTHS[6]-2)/ratio);
float px=X+W-WIDTHS[6]+(WIDTHS[6]-ratio*imageHeight)/2;
float py=groupTop+(start/columns)*maxH+(maxH-imageHeight)/2;
for(var image:strip){float iw=(float)image.getWidth()/image.getHeight()*imageHeight;
pen.drawImage(JPEGFactory.createFromImage(doc,image,.85f),px,H-py-imageHeight,iw,imageHeight);px+=iw;
}
}
}
y+=h;offset+=take;first=false;if(offset<lines)newPage();
}while(offset<lines);
}
private void footer(Fields f)throws IOException{
if(y+13<=bottom()){box(X,y,W,13,1);y+=13;}y+=7;
if(y+26>bottom())newPage();
checkRow("内容","OK","N.OK",true);
for(int i=0;i<PurchaseAcceptanceReportService.CHECKS.size();i++){
if(y+13>bottom())newPage();String value=f.checks().get(i);checkRow(PurchaseAcceptanceReportService.CHECKS.get(i),"OK".equals(value)?"yes":"","N.OK".equals(value)?"yes":"",false);
// Fixed line-sized writing areas, without padding the report to a full page.
ensure(2*ROW);box(X,y,W,2*ROW,1);y+=2*ROW;
ensure(24+3*ROW);section("二、主要技术参数验收",24);
box(X,y,W,3*ROW,1);y+=3*ROW;
ensure(24+110);section("三、验收结论",24);
box(X,y,W,110,1);float baseline=y+22;
for(String conclusion:PurchaseAcceptanceReportService.CONCLUSIONS){
for(String line:wrap(conclusion,W-24,11)){text(line,X+12,baseline,11,font);baseline+=20;}
}y+=110;
ensure(24+28+40+28+28);section("四、签字确认",24);
float half=W/2;
cell("甲方(验收方)",X,y,half,28,12,true);cell("乙方(供货方)",X+half,y,half,28,12,true);y+=28;
for(String label:List.of("联系人签字或盖章:","联系电话:","日 期:")){
String value=label.startsWith("日")&&f.date()!=null?label+f.date():label;
float height=label.startsWith("联系人")?40:28;
cell(value,X,y,half,height,11,false);cell(value,X+half,y,half,height,11,false);y+=height;
}
float companies=Math.max(21,Math.max(height(f.purchaser(),172,8),height(f.supplier(),292,8)));float block=21+12+22+8+35+companies+36+8;
if(y+block>bottom())newPage();y+=21;
box(X,y,W,12,.9f);boldCenter("验收结论",X,y,W,12,10);y+=12;
text("1. 供货产品数量与合同一致,满足要求。",X+1,y+9,8,font);text("2. 同意验收",X+1,y+19,8,font);y+=30;
box(X,y,W,35,.65f);boldCenter("ACCEPTANCE SIGNATURE验收签字",X,y,W,35,10);y+=35;
cell(f.purchaser(),X,y,172,companies,8,true);cell(f.supplier(),X+172,y,292,companies,8,true);y+=companies;
box(X,y,172,36,1);box(X+172,y,292,36,1);y+=36;
String date=f.date()==null?"":f.date().toString();cell("Date日期:"+date,X,y,172,8,6.5f,true);cell("Date日期:"+date,X+172,y,292,8,6.5f,true);y+=8;
}
private void checkRow(String label,String ok,String no,boolean header)throws IOException{
cell(label,X,y,276,13,6.5f,header);
if(header){cell(ok,X+276,y,32,13,7,false);cell(no,X+308,y,156,13,7,false);}else{
box(X+276,y,32,13,1);box(X+308,y,156,13,1);checkbox(X+280,y+4,"yes".equals(ok));checkbox(X+312,y+4,"yes".equals(no));
}y+=13;
}
private void checkbox(float x,float top,boolean selected)throws IOException{
box(x,top,4,4,1);if(selected){pen.moveTo(x,H-top-2);pen.lineTo(x+2,H-top-4);pen.lineTo(x+6,H-top+2);pen.stroke();}
}
private void ensure(float height)throws IOException{if(y+height>bottom())newPage();}
private void box(float x,float top,float w,float h,float gray)throws IOException{
pen.setNonStrokingColor(gray);pen.addRect(x,H-top-h,w,h);pen.fill();pen.setStrokingColor(0f);pen.addRect(x,H-top-h,w,h);pen.stroke();pen.setNonStrokingColor(0f);
}

View File

@ -13,29 +13,44 @@ import org.springframework.transaction.annotation.*;
/** 验收单只读整批真实验收记录;不接受客户端提交物品、数量或验收状态。 */
@Service
public class PurchaseAcceptanceReportService {
public static final List<String> CONCLUSIONS=List.of("1. 设备外观完整,无明显破损、变形或缺件。","2. 设备名称、规格型号及数量与采购清单一致。","3. 到货资料及配套附件已核对,满足交付要求。","4. 本次设备清单验收通过,同意验收。");
public static final String COMPANY="招商局检测车辆技术研究院有限公司";
public static final String ADDRESS="重庆市九龙坡区金凤镇"+COMPANY;
public static final String DELIVERY_LOCATION="招商车研";
public static final List<String> CHECKS=List.of("供货范围是否与合同/技术协议一致","机械安装","电气安装","系统调试","运行结果","培训","资料");
private final PurchaseSheetService sheets; private final JdbcTemplate db;
public PurchaseAcceptanceReportService(PurchaseSheetService sheets,JdbcTemplate db){this.sheets=sheets;this.db=db;}
public record Fields(String purchaser,String supplier,String address,String contractNo,String projectNo,String description,String deliveryLocation,LocalDate date,List<String> checks) { }
public record Line(long id,String name,String spec,String unit,BigDecimal quantity,BigDecimal accepted,List<String> photos) { }
public record Fields(String purchaser,String supplier,String address,String contractNo,String projectNo,String description,String deliveryLocation,LocalDate date,List<String> checks,LocalDate arrivalDate) {
public Fields(String purchaser,String supplier,String address,String contractNo,String projectNo,String description,String deliveryLocation,LocalDate date,List<String> checks){this(purchaser,supplier,address,contractNo,projectNo,description,deliveryLocation,date,checks,null);}
}
public record Line(long id,String name,String spec,String unit,BigDecimal quantity,BigDecimal accepted,List<String> photos,LocalDate arrivalDate) {
public Line(long id,String name,String spec,String unit,BigDecimal quantity,BigDecimal accepted,List<String> photos){this(id,name,spec,unit,quantity,accepted,photos,null);}
}
public record Issue(int line,String name,String reason) { }
public record DocumentCheck(String label,String numberLabel,boolean numbered,int files) { public boolean complete(){return numbered&&files>0;} }
public record Report(String version,String batchName,Fields fields,List<Line> lines,List<Issue> issues) { public boolean ready(){return !lines.isEmpty()&&issues.isEmpty();} }
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Map<String,Object> preview(long id){
var report=load(id);var documents=documents(id);var out=new LinkedHashMap<String,Object>();out.put("version",report.version());out.put("ready",report.ready()&&documents.stream().allMatch(DocumentCheck::complete));out.put("count",report.lines().size());out.put("issues",report.issues());out.put("documents",documents);out.put("fields",report.fields());out.put("checkLabels",CHECKS);return out;
var report=load(id);var documents=documents(id);var out=new LinkedHashMap<String,Object>();out.put("version",report.version());out.put("ready",report.ready()&&documents.stream().allMatch(DocumentCheck::complete));out.put("count",report.lines().size());out.put("issues",report.issues());out.put("rows",java.util.stream.IntStream.range(0,report.lines().size()).mapToObj(index->{var line=report.lines().get(index);var reasons=report.issues().stream().filter(issue->issue.line()==index+1).map(Issue::reason).toList();return Map.of("id",line.id(),"name",line.name(),"spec",line.spec(),"unit",line.unit(),"quantity",line.quantity(),"ready",reasons.isEmpty(),"reason",String.join(";",reasons),"arrivalDate",line.arrivalDate()==null?"":line.arrivalDate().toString());}).toList());out.put("documents",documents);out.put("fields",report.fields());out.put("checkLabels",CHECKS);out.put("conclusions",CONCLUSIONS);return out;
}
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Report export(long id,String version,Fields fields){
return export(id,version,fields,null);
}
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Report export(long id,String version,Fields fields,List<Long> selectedIds){
var report=load(id);
if(!Objects.equals(report.version(),version))throw new ServiceException("采购清单已变化,请刷新后重新导出验收单");
if(!report.ready())throw new ServiceException("整批采购明细全部验收通过后才能导出验收单:"+(report.issues().isEmpty()?"没有可导出的明细":report.issues().get(0).reason()));
Set<Long> selected=selectedIds==null?new HashSet<>(report.lines().stream().map(Line::id).toList()):new HashSet<>(selectedIds);
if(selected.isEmpty())throw new ServiceException("请至少选择一条明细");
if(selectedIds!=null&&(selected.contains(null)||selected.size()!=selectedIds.size()))throw new ServiceException("所选明细无效或重复,请重新选择");
if(!report.lines().stream().map(Line::id).toList().containsAll(selected))throw new ServiceException("所选明细不属于当前批次或已取消,请重新选择");
var lines=report.lines().stream().filter(line->selected.contains(line.id())).toList();
var issues=report.issues().stream().filter(issue->selected.contains(report.lines().get(issue.line()-1).id())).toList();
if(!issues.isEmpty())throw new ServiceException("所选明细尚未全部到齐:"+issues.get(0).name()+";"+issues.get(0).reason());
for(var document:documents(id))if(!document.complete())throw new ServiceException("请先补全"+document.label()+":"+(!document.numbered()?"缺少"+document.numberLabel()+";":"")+(document.files()==0?"缺少PDF附件":""));
return new Report(report.version(),report.batchName(),validate(fields,report.fields().contractNo()),report.lines(),List.of());
return new Report(report.version(),report.batchName(),validate(fields,report.fields().contractNo(),report.fields().projectNo()),lines,List.of());
}
private List<DocumentCheck> documents(long id){
var rows=db.queryForList("select g.document_kind kind,g.document_no number,(select count(*) from purchase_document_attachment a where a.group_id=g.id and a.deleted=0 and a.content_type='application/pdf') files from purchase_document_group g where g.target_type='batch' and g.target_id=? and g.document_kind in ('REQUEST','QUOTE','CONTRACT')",id);
@ -45,7 +60,7 @@ public class PurchaseAcceptanceReportService {
}
private Report load(long id){
var sheet=sheets.load(id);var rows=sheet.getRows().stream().filter(r->!Integer.valueOf(5).equals(r.getPurchaseStatus())).toList();
var evidence=db.queryForList("select a.id,a.purchase_request_id request_id,cast(a.acceptance_status as signed) status,a.arrival_quantity quantity,a.defective_quantity defective,a.returned_quantity returned,a.accepted_time from purchase_arrival a join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' order by a.id",id);
var evidence=db.queryForList("select a.id,a.purchase_request_id request_id,cast(a.acceptance_status as signed) status,a.arrival_quantity quantity,a.defective_quantity defective,a.returned_quantity returned,a.accepted_time,a.arrival_date from purchase_arrival a join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' order by a.id",id);
var photoRows=db.queryForList("select p.id,p.purchase_request_id request_id from purchase_arrival_photo p join purchase_arrival a on a.id=p.arrival_id join purchase_request r on r.id=a.purchase_request_id where r.purchase_batch_id=? and r.del_flag='0' and a.acceptance_status=1 and a.arrival_quantity-a.defective_quantity-a.returned_quantity>0 order by a.id,p.sort_no,p.id",id);
var lines=new ArrayList<Line>();var issues=new ArrayList<Issue>();LocalDate latest=null;
for(var row:rows){
@ -54,27 +69,30 @@ public class PurchaseAcceptanceReportService {
boolean pending=records.stream().anyMatch(a->((Number)a.get("status")).intValue()==0);
String name=Objects.toString(row.getProductName(),"");if(name.isBlank())name=Objects.toString(row.getMaterialName(),"");
String spec=Objects.toString(row.getProductSpec(),"");if(spec.isBlank())spec=Objects.toString(row.getMaterialParams(),"");
lines.add(new Line(row.getId(),name,spec,Objects.toString(row.getUnit(),""),row.getQuantity(),accepted,photoRows.stream().filter(p->((Number)p.get("request_id")).longValue()==row.getId()).map(p->p.get("id").toString()).toList()));
LocalDate arrivalDate=records.stream().filter(a->((Number)a.get("status")).intValue()==1&&decimal(a.get("quantity")).subtract(decimal(a.get("defective"))).subtract(decimal(a.get("returned"))).signum()>0).map(a->date(a.get("arrival_date"))).filter(Objects::nonNull).max(LocalDate::compareTo).orElse(null);
lines.add(new Line(row.getId(),name,spec,Objects.toString(row.getUnit(),""),row.getQuantity(),accepted,photoRows.stream().filter(p->((Number)p.get("request_id")).longValue()==row.getId()).map(p->p.get("id").toString()).toList(),arrivalDate));
boolean quantityMatches=row.getQuantity()!=null&&row.getQuantity().signum()>0&&accepted.compareTo(row.getQuantity())==0;
if(!quantityMatches||pending)issues.add(new Issue(lines.size(),name,Boolean.TRUE.equals(row.getHistorical())&&records.isEmpty()?"历史完成明细没有真实验收通过记录":pending?"仍有待验收的到货记录":"验收通过数量与采购数量不一致"));
for(var record:records)if(((Number)record.get("status")).intValue()==1&&record.get("accepted_time") instanceof java.sql.Timestamp time){var date=time.toLocalDateTime().toLocalDate();if(latest==null||date.isAfter(latest))latest=date;}
}
var batch=sheet.getBatch();String projectNo="",supplier="";var projectIds=rows.stream().map(PurchaseRequest::getProjectId).filter(Objects::nonNull).distinct().toList();
if(projectIds.size()==1){var codes=db.queryForList("select project_code from project_info where id=?",String.class,projectIds.get(0));if(!codes.isEmpty())projectNo=Objects.toString(codes.get(0),"");}
var batch=sheet.getBatch();String projectNo="",supplier="";var requestNumbers=db.queryForList("select document_no from purchase_document_group where target_type='batch' and target_id=? and document_kind='REQUEST'",String.class,id);
if(!requestNumbers.isEmpty())projectNo=Objects.toString(requestNumbers.get(0),"").trim();
if(batch.getSupplierId()!=null){var names=db.queryForList("select name from supplier_info where id=?",String.class,batch.getSupplierId());if(!names.isEmpty())supplier=Objects.toString(names.get(0),"");}
// 合同编号可独立于附件维护;只读取现有批次合同组,不初始化或修改资料记录。
var contracts=db.queryForList("select document_no from purchase_document_group where target_type='batch' and target_id=? and document_kind='CONTRACT'",String.class,id);
String contractNo=contracts.isEmpty()?"":Objects.toString(contracts.get(0),"").trim();
var fields=new Fields(COMPANY,supplier,ADDRESS,contractNo,projectNo,Objects.toString(batch.getBatchName(),""),DELIVERY_LOCATION,latest,Collections.nCopies(CHECKS.size(),""));
var fields=new Fields(COMPANY,supplier,ADDRESS,contractNo,projectNo,Objects.toString(batch.getBatchName(),""),DELIVERY_LOCATION,latest,Collections.nCopies(CHECKS.size(),""),null);
return new Report(sheet.getVersion(),Objects.toString(batch.getBatchName(),batch.getBatchNo()),fields,List.copyOf(lines),List.copyOf(issues));
}
private static Fields validate(Fields f,String contractNo){
private static Fields validate(Fields f,String contractNo,String projectNo){
if(f==null)throw new ServiceException("请补充验收单信息");
if(!Objects.equals(text(f.contractNo(),100),contractNo))throw new ServiceException("批次资料中的合同编号已变化,请重新打开验收单核对");
if(!Objects.equals(text(f.projectNo(),100),projectNo))throw new ServiceException("采购申请随行编号已变化,请重新打开验收资料");
var checks=f.checks()==null?Collections.nCopies(CHECKS.size(),""):f.checks();
if(checks.size()!=CHECKS.size()||checks.stream().anyMatch(s->s==null||!Set.of("","OK","N.OK").contains(s)))throw new ServiceException("验收检查项无效");
return new Fields(text(f.purchaser(),100),text(f.supplier(),100),ADDRESS,contractNo,text(f.projectNo(),100),text(f.description(),200),DELIVERY_LOCATION,f.date(),List.copyOf(checks));
return new Fields(text(f.purchaser(),100),text(f.supplier(),100),ADDRESS,contractNo,projectNo,text(f.description(),200),DELIVERY_LOCATION,f.date(),List.copyOf(checks),f.arrivalDate());
}
private static LocalDate date(Object value){if(value instanceof java.sql.Date d)return d.toLocalDate();if(value instanceof java.sql.Timestamp t)return t.toLocalDateTime().toLocalDate();if(value instanceof LocalDate d)return d;return null;}
private static String text(String s,int max){s=s==null?"":s.trim();if(s.length()>max)throw new ServiceException("验收单填写内容过长");return s;}
private static BigDecimal decimal(Object value){return value==null?BigDecimal.ZERO:new BigDecimal(value.toString());}
}

View File

@ -77,14 +77,15 @@ public class PurchaseBoardService {
var rows=db.queryForList("select b.create_by createBy,b.id,b.batch_no batchNo,b.batch_name batchName,b.expense_category_id expenseCategoryId,coalesce(e.category_name,'待统一') expenseCategoryName,b.progress_remark remark,b.business_date businessDate,s.name supplierName,a.projectNames,a.purchasers,coalesce(a.itemCount,0) itemCount,a.actualTotalAmount,a.quoteAmount,coalesce(a.unpricedCount,0) unpricedCount"+FROM+aggregate+" left join expense_category e on e.id=b.expense_category_id "+f.sql()+" order by "+BOARD_ORDER+" limit ? offset ?",args.toArray());
if(!rows.isEmpty()){
var ids=rows.stream().map(r->r.get("id")).toList();String marks=String.join(",",Collections.nCopies(ids.size(),"?"));
var docs=db.queryForList("select g.target_id batchId,g.document_kind kind,g.document_no number,count(a.id) files from purchase_document_group g left join purchase_document_attachment a on a.group_id=g.id and a.deleted=0 and a.content_type='application/pdf' where g.target_type='batch' and g.target_id in ("+marks+") group by g.id,g.target_id,g.document_kind,g.document_no",ids.toArray());
var docs=db.queryForList("select g.target_id batchId,g.document_kind kind,g.document_no number,count(a.id) files from purchase_document_group g left join purchase_document_attachment a on a.group_id=g.id and a.deleted=0 and (g.document_kind='INVOICE' or a.content_type='application/pdf') where g.target_type='batch' and g.target_id in ("+marks+") group by g.id,g.target_id,g.document_kind,g.document_no",ids.toArray());
for(var row:rows){
int invoices=docs.stream().filter(d->Objects.equals(d.get("batchId"),row.get("id"))&&"INVOICE".equals(d.get("kind"))).mapToInt(d->((Number)d.get("files")).intValue()).sum();
var stages=new ArrayList<Map<String,Object>>();
for(String kind:List.of("REQUEST","CONTRACT","ACCEPTANCE","PAYMENT")){
var doc=docs.stream().filter(d->Objects.equals(d.get("batchId"),row.get("id"))&&kind.equals(d.get("kind"))).findFirst().orElse(Map.of());
String number=Objects.toString(doc.get("number"),"");int files=((Number)doc.getOrDefault("files",0)).intValue();
if("REQUEST".equals(kind))files+=docs.stream().filter(d->Objects.equals(d.get("batchId"),row.get("id"))&&"QUOTE".equals(d.get("kind"))).mapToInt(d->((Number)d.get("files")).intValue()).sum();
stages.add(Map.of("kind",kind,"number",number,"files",files,"complete",files>0&&("ACCEPTANCE".equals(kind)||!number.isBlank())));
stages.add(Map.of("kind",kind,"number",number,"files",files,"complete",files>0&&("ACCEPTANCE".equals(kind)||!number.isBlank())&&(!"PAYMENT".equals(kind)||invoices>0),"invoiceFiles",invoices));
}
row.put("editable",com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)row.get("createBy"),null));row.put("stages",stages);if(!quotes){row.remove("quoteAmount");row.remove("unpricedCount");}if(compact)row.remove("actualTotalAmount");
}

View File

@ -32,7 +32,9 @@ public class PurchaseLiveService implements MessageListener {
public PurchaseLiveService(PurchaseLiveStore store,RedisCache tokens,JdbcTemplate db,PurchaseRequestMapper requests){this.store=store;this.tokens=tokens;this.db=db;this.requests=requests;}
@PostConstruct public void start(){clock.scheduleWithFixedDelay(this::flushChanges,100,150,TimeUnit.MILLISECONDS);clock.scheduleWithFixedDelay(this::heartbeat,10,10,TimeUnit.SECONDS);}
@PreDestroy public void stop(){connections.values().forEach(this::close);clock.shutdownNow();senders.shutdownNow();}
public record State(String clientId,long sequence,Long rowId,String rowKey,String field,boolean editing,Object value,boolean typing){}
public record State(String clientId,long sequence,Long rowId,String rowKey,String field,boolean editing,Object value,boolean typing,List<Map<String,Object>> draftRows){
public State(String clientId,long sequence,Long rowId,String rowKey,String field,boolean editing,Object value,boolean typing){this(clientId,sequence,rowId,rowKey,field,editing,value,typing,null);}
}
private static final class Connection {
final long batch,userId;final String client,token;final SseEmitter emitter;volatile boolean quote;final Queue<Outbound> pending=new ArrayDeque<>();boolean draining;
Connection(long batch,String client,LoginUser user,boolean quote){this.batch=batch;this.client=client;this.userId=user.getUserId();this.token=user.getToken();this.quote=quote;this.emitter=new SseEmitter(0L);}
@ -55,7 +57,9 @@ public class PurchaseLiveService implements MessageListener {
var user=user();var old=owned(batch,input.clientId(),user);var next=new LinkedHashMap<>(old);next.put("sequence",input.sequence());next.put("editing",input.editing());next.put("lease","");
String field=input.field();Long rowId=input.rowId();String rowKey=input.rowKey();
if(field!=null&&!FIELDS.contains(field)&&!"batch".equals(field))throw new ServiceException("此字段不支持实时编辑");
if(rowKey!=null&&!rowKey.matches("[A-Za-z0-9_-]{1,100}"))throw new ServiceException("新增行标识无效");
// Older clients used Math.random() in row keys; its decimal point is a valid Redis key character.
if(rowKey!=null&&!rowKey.matches("[A-Za-z0-9_.-]{1,100}"))throw new ServiceException("新增行标识无效");
if(input.draftRows()!=null)next.put("draftRows",draftRows(input.draftRows(),user));
if(input.editing()){
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:edit")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有采购编辑权限",403);
if(field==null)throw new ServiceException("请选择编辑的单元格");
@ -107,8 +111,25 @@ public class PurchaseLiveService implements MessageListener {
}catch(Exception error){LOG.warn("Purchase live refresh will retry ({})",error.getClass().getSimpleName());}}
static Map<String,Object> publicMember(Map<String,Object> raw,boolean quote){
var out=new LinkedHashMap<String,Object>();for(String key:List.of("clientId","userId","name","rowId","rowKey","rowName","field","editing","draft","sequence"))out.put(key,raw.get(key));
var rows=new ArrayList<Map<String,Object>>();
if(raw.get("draftRows") instanceof List<?> list)for(var value:list)if(value instanceof Map<?,?> draft){var row=new LinkedHashMap<String,Object>();draft.forEach((key,item)->{if(quote||!"finalUnitPrice".equals(key))row.put(key.toString(),item);});rows.add(row);}
out.put("draftRows",rows);
if(!quote&&"finalUnitPrice".equals(out.get("field"))){out.put("rowId",null);out.put("rowKey",null);out.put("rowName",null);out.put("field",null);out.put("editing",false);out.put("draft",null);}return out;
}
private static final Set<String> DRAFT_FIELDS=Set.of("productId","productCode","materialName","materialBrand","materialParams","category","unit","quantity","actualUnitPrice","finalUnitPrice","projectId","projectCode","expenseCategoryId","expenseCategoryCode","productionTaskId","purchaseLink","remark");
private List<Map<String,Object>> draftRows(List<Map<String,Object>> input,LoginUser user){
if(input.size()>2000)throw new ServiceException("最多同步2000行新增草稿");
if(!input.isEmpty()&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:add")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有新增采购明细权限",403);
var rows=new ArrayList<Map<String,Object>>();var keys=new HashSet<String>();int characters=0;Boolean quote=null;
for(var raw:input){if(raw==null)throw new ServiceException("新增行草稿不能为空");String key=Objects.toString(raw.get("key"),"");if(!key.matches("[A-Za-z0-9_.-]{1,100}")||!keys.add(key))throw new ServiceException("新增行草稿标识无效或重复");
var row=new LinkedHashMap<String,Object>();row.put("key",key);
for(var entry:raw.entrySet()){String field=entry.getKey();Object value=entry.getValue();if("key".equals(field))continue;if(!DRAFT_FIELDS.contains(field))throw new ServiceException("新增行草稿包含不支持的字段");if(value==null||"".equals(value))continue;
if(!(value instanceof String)&&!(value instanceof Number)||value.toString().length()>1000)throw new ServiceException("新增行草稿字段无效或过长");
if("finalUnitPrice".equals(field)){if(quote==null)quote=quotes(user.getUserId());if(!quote)throw new ServiceException("报价金额仅采购管理员可维护",403);}
characters+=field.length()+value.toString().length()+8;if(characters>512*1024)throw new ServiceException("新增行草稿内容过多,请分批填写或先保存");row.put(field,value);
}rows.add(row);
}return rows;
}
private List<Map<String,Object>> visibleMembers(long batch,boolean quote){return store.members(batch).stream().map(m->publicMember(m,quote)).toList();}
private static boolean canRead(LoginUser login){return login!=null&&(PurchasePermissions.grants(login,"warehouse:purchase:list")||SecurityUtils.hasPermi(login.getPermissions(),"warehouse:purchase:list")||SecurityUtils.hasPermi(login.getPermissions(),"warehouse:purchase:manage"));}
private void publishMembers(long batch){store.publish(Map.of("batch",batch,"type","members"));}

View File

@ -65,7 +65,7 @@ public class PurchaseLiveStore {
local raw=redis.call('get',KEYS[1]);if not raw then return 0 end
local member=cjson.decode(raw)
if member.token~=ARGV[1] or member.sequence>tonumber(ARGV[2]) then return 0 end
member.draft=cjson.null;redis.call('psetex',KEYS[1],ARGV[3],cjson.encode(member));return 1
member.draft=cjson.null;member.draftRows=nil;redis.call('psetex',KEYS[1],ARGV[3],cjson.encode(member));return 1
""",Long.class);
public void clearDraft(long batch,String client,String token,long sequence){redis.execute(CLEAR,List.of(member(batch,client)),token,String.valueOf(sequence),String.valueOf(MEMBER_MS));}
public List<Map<String,Object>> members(long batch){

View File

@ -0,0 +1,108 @@
package com.ruoyi.production.service;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.production.domain.*;
import com.ruoyi.production.mapper.BomMapper;
import com.ruoyi.production.util.BomDataAccess;
import com.ruoyi.project.service.IProjectInfoService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehouse.domain.ProductInfo;
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
import com.ruoyi.web.service.files.UploadTargets;
import java.util.*;
import org.junit.jupiter.api.*;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BomOwnershipPermissionTest {
static LoginUser login(long id,String account,String key,String status,String deleted,Set<String> permissions){
var role=new SysRole();role.setRoleId(40L);role.setRoleKey(key);role.setStatus(status);role.setDelFlag(deleted);
var user=new SysUser();user.setUserId(id);user.setUserName(account);user.setStatus("0");user.setDelFlag("0");user.setRoles(List.of(role));
var login=new LoginUser(id,1L,user,permissions);SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null));return login;
}
static LoginUser employee(){return login(22,"alice","common","0","0",Set.of("production:product:edit","production:bom:edit"));}
@BeforeEach void setup(){employee();org.springframework.web.context.request.RequestContextHolder.setRequestAttributes(new org.springframework.web.context.request.ServletRequestAttributes(new org.springframework.mock.web.MockHttpServletRequest()));}
@AfterEach void cleanup(){SecurityContextHolder.clearContext();org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes();}
static class Fixture {
final BomMapper mapper=mock(BomMapper.class);final ProductInfoMapper items=mock(ProductInfoMapper.class);final IProjectInfoService projects=mock(IProjectInfoService.class);
final BomService boms=new BomService();final ProductVersionService editions=new ProductVersionService();
final Map<Long,BomVersion> versions=new LinkedHashMap<>();final Map<Long,ProductionProduct> products=new LinkedHashMap<>();long next=100;
Fixture(){
ReflectionTestUtils.setField(boms,"mapper",mapper);ReflectionTestUtils.setField(boms,"items",items);ReflectionTestUtils.setField(boms,"projects",projects);
ReflectionTestUtils.setField(editions,"mapper",mapper);ReflectionTestUtils.setField(editions,"boms",boms);
when(mapper.lockGraph()).thenReturn(1);when(mapper.selectVersion(anyLong())).thenAnswer(call->versions.get(call.getArgument(0)));
when(mapper.selectLines(anyLong())).thenAnswer(call->{var bom=versions.get(call.getArgument(0));return bom==null?List.of():bom.getLines();});
when(mapper.selectGraphVersions()).thenAnswer(call->new ArrayList<>(versions.values()));
when(mapper.selectProduct(anyLong())).thenAnswer(call->products.get(call.getArgument(0)));
when(mapper.selectProductByItem(anyLong())).thenAnswer(call->products.values().stream().filter(row->Objects.equals(row.getItemId(),call.getArgument(0))).findFirst().orElse(null));
when(mapper.selectPublicVersions(any(),any())).thenAnswer(call->new ArrayList<>(versions.values()));
when(mapper.selectProducts(any())).thenAnswer(call->new ArrayList<>(products.values()));
when(mapper.selectDefault(anyLong())).thenAnswer(call->versions.values().stream().filter(row->Objects.equals(row.getItemId(),call.getArgument(0))&&Boolean.TRUE.equals(row.getIsDefault())).findFirst().orElse(null));
when(mapper.insertVersion(any())).thenAnswer(call->{BomVersion bom=call.getArgument(0);bom.setId(next++);versions.put(bom.getId(),bom);return 1;});
when(mapper.updateVersion(any())).thenReturn(1);when(mapper.updateProduct(any())).thenReturn(1);when(mapper.deleteProduct(anyLong())).thenReturn(1);when(mapper.deleteVersion(anyLong())).thenReturn(1);
when(items.selectProductInfoById(anyLong())).thenAnswer(call->{var item=new ProductInfo();item.setId(call.getArgument(0));item.setUnit("台");item.setProductName("测试产品");return item;});
}
ProductionProduct product(long id,String owner){var row=new ProductionProduct();row.setId(id);row.setItemId(id);row.setVersion(0);row.setCreateBy(owner);products.put(id,row);return row;}
BomVersion bom(long id,long item,String owner,boolean defaultVersion){var row=new BomVersion();row.setId(id);row.setItemId(item);row.setVersion(0);row.setCreateBy(owner);row.setVersionTag("v"+id);row.setScopeType("PUBLIC");row.setScopeKey("PUBLIC");row.setIsDefault(defaultVersion);row.setLines(new ArrayList<>());versions.put(id,row);return row;}
}
@Test void activeRoleGrantsOnlyProductAndBomActionsWithoutMenuPrivileges(){
var login=login(22,"manager","bom_manager","0","0",Set.of());var expressions=new PermissionService();
for(String permission:BomPermissions.ACTIONS){assertTrue(SecurityUtils.hasPermi(permission));assertTrue(expressions.hasPermi(permission));assertTrue(expressions.hasAnyPermi("system:user:edit,"+permission));}
for(String permission:List.of("system:role:edit","warehouse:product:edit","warehouse:stock:out","project:project:manage","production:task:edit","*:*:*")){assertFalse(SecurityUtils.hasPermi(permission));assertFalse(expressions.hasPermi(permission));}
assertTrue(BomDataAccess.canEdit("someone-else"));assertTrue(BomDataAccess.canEdit(""));assertTrue(BomDataAccess.canEdit((String)null));
var menu=mock(ISysMenuService.class);when(menu.selectMenuPermsByRoleId(40L)).thenReturn(Set.of());var permissions=new SysPermissionService();ReflectionTestUtils.setField(permissions,"menuService",menu);
assertEquals(BomPermissions.ACTIONS,permissions.getMenuPermission(login.getUser()));
for(String[] invalid:List.of(new String[]{"bom_manager","1","0"},new String[]{"bom_manager","0","2"},new String[]{"common","0","0"})){login(22,"manager",invalid[0],invalid[1],invalid[2],Set.of());assertFalse(BomDataAccess.canEdit("other"));assertFalse(SecurityUtils.hasPermi("production:bom:edit"));}
}
@Test void menuWildcardCannotBypassOwnershipButSuperAdminCanMaintainLegacyRecords(){
login(22,"alice","common","0","0",Set.of("*:*:*"));assertTrue(BomDataAccess.canEdit("alice"));assertFalse(BomDataAccess.canEdit("bob"));assertFalse(BomDataAccess.canEdit(""));
var f=new Fixture();f.product(7,"bob");assertEquals(403,assertThrows(ServiceException.class,()->f.boms.deleteProduct(7L)).getCode());
login(1,"admin","admin","0","0",Set.of("*:*:*"));f.products.get(7L).setCreateBy(null);assertDoesNotThrow(()->f.boms.deleteProduct(7L));
}
@Test void actualOwnerProtectsUpdatesDeletesAndIdlessProductOverwrite(){
var f=new Fixture();var foreign=f.product(7,"bob");var own=f.product(8,"alice");var input=new ProductionProduct();input.setId(7L);input.setVersion(0);input.setCreateBy("alice");
assertEquals(403,assertThrows(ServiceException.class,()->f.boms.saveProduct(input)).getCode());assertThrows(ServiceException.class,()->f.boms.deleteProduct(7L));
input.setId(null);input.setItemId(7L);input.setRemark("forged overwrite");assertThrows(ServiceException.class,()->f.boms.saveProduct(input));
verify(f.mapper,never()).updateProduct(any());verify(f.mapper,never()).deleteProduct(anyLong());
var rows=f.boms.products("");assertFalse(foreign.getEditable());assertTrue(own.getEditable());assertEquals(2,rows.size());
input.setId(8L);assertDoesNotThrow(()->f.boms.saveProduct(input));assertDoesNotThrow(()->f.boms.deleteProduct(8L));
}
@Test void bomWritesNeverTrustForgedCreatorAndDefaultCannotClearAnothersBom(){
var f=new Fixture();f.bom(9,1,"bob",false);var request=new BomVersion();request.setId(9L);request.setVersion(0);request.setCreateBy("alice");request.setVersionTag("forged");
assertEquals(403,assertThrows(ServiceException.class,()->f.boms.save(request)).getCode());assertThrows(ServiceException.class,()->f.boms.delete(9L));assertThrows(ServiceException.class,()->f.boms.setDefault(9L,0));
var own=f.bom(10,1,"alice",false);f.bom(11,1,"bob",true);
assertThrows(ServiceException.class,()->f.boms.setDefault(10L,0));verify(f.mapper,never()).clearDefault(anyLong(),any());verify(f.mapper,never()).updateVersion(any());
request.setId(10L);request.setIsDefault(false);assertDoesNotThrow(()->f.boms.save(request));assertEquals("alice",request.getCreateBy());
login(22,"manager","bom_manager","0","0",Set.of());assertDoesNotThrow(()->f.boms.setDefault(10L,0));assertTrue(f.boms.get(9L).getEditable());
}
@Test void copyingAnotherPublicBomCreatesAnOwnedVersionWithoutEditingSource(){
var f=new Fixture();var source=f.bom(9,1,"bob",false);f.product(1,"bob");
var copy=f.boms.copy(9L,"alice-v2","自己的用料",false);assertEquals("alice",copy.getCreateBy());assertNotEquals(source.getId(),copy.getId());assertEquals("bob",source.getCreateBy());
verify(f.mapper,never()).updateVersion(any());verify(f.mapper,never()).clearDefault(anyLong(),any());
}
@Test void versionAndAttachmentEntryPointsRejectForeignProductBeforeAnyWrite(){
var f=new Fixture();f.product(7,"bob");
assertEquals(403,assertThrows(ServiceException.class,()->f.editions.requireProductWrite(7L)).getCode());
assertThrows(ServiceException.class,()->f.editions.save(f.products.get(7L)));assertThrows(ServiceException.class,()->f.editions.preview(new ProductVersionService.Create(7L,0,null,null,null,"v2",null,false,null,null,null,null,null,null,"request-key")));
var files=new ProductAttachmentService();ReflectionTestUtils.setField(files,"products",f.editions);
assertThrows(ServiceException.class,()->files.upload(7L,UUID.randomUUID().toString(),null));assertThrows(ServiceException.class,()->files.remove(7L,UUID.randomUUID().toString()));
var targets=new UploadTargets();ReflectionTestUtils.setField(targets,"versions",f.editions);var users=mock(ISysUserService.class);when(users.selectUserById(22L)).thenReturn(SecurityUtils.getLoginUser().getUser());ReflectionTestUtils.setField(targets,"users",users);
var permissions=mock(SysPermissionService.class);when(permissions.getMenuPermission(any())).thenReturn(Set.of("production:product:edit"));ReflectionTestUtils.setField(targets,"currentPermissions",permissions);
assertEquals(403,assertThrows(ServiceException.class,()->targets.authorize(new UploadTargets.Target("product",7L,null,null))).getCode());
verify(f.mapper,never()).updateProduct(any());verify(f.mapper,never()).insertProduct(any());
}
@Test void bomManagerReadsProjectBomsWithoutBecomingAProjectAdministrator(){
var f=new Fixture();var bom=f.bom(9,1,"bob",false);bom.setScopeType("PROJECT");bom.setProjectId(30L);
login(22,"manager","bom_manager","0","0",Set.of());assertTrue(f.boms.get(9L).getEditable());verifyNoInteractions(f.projects);
bom.setScopeType("TASK");assertFalse(f.boms.get(9L).getEditable());assertThrows(ServiceException.class,()->f.boms.save(bom));
}
}

View File

@ -0,0 +1,25 @@
package com.ruoyi.projectdev;
import com.ruoyi.production.mapper.BomMapper;
import java.util.UUID;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import static org.junit.jupiter.api.Assertions.*;
class BomOwnershipMapperTest {
@Test void realMapperRetainsProductAndBomCreatorsForPermissionChecks()throws Exception{
var source=new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa","");var db=new JdbcTemplate(source);
db.execute("create table product_info(id bigint primary key,product_code varchar(64),product_name varchar(100),category varchar(100),brand varchar(100),spec varchar(100),unit varchar(20))");
db.execute("create table bom_version(id bigint primary key,item_id bigint,create_by varchar(64),del_flag char(1),scope_type varchar(20),is_default int,version_tag varchar(64),create_time timestamp)");
db.execute("create table production_product(id bigint primary key,item_id bigint,create_by varchar(64),version int,del_flag char(1),create_time timestamp,update_time timestamp)");
db.execute("create table production_product_edition(product_id bigint,series_id bigint,edition_tag varchar(64),source_product_id bigint,source_bom_id bigint)");
db.execute("create table production_product_series(id bigint primary key,series_name varchar(100),version int)");
db.execute("insert into product_info values(1,'P-1','测试产品','','','','个')");db.execute("insert into production_product values(7,1,'alice',0,'0',current_timestamp,current_timestamp)");db.execute("insert into bom_version values(9,1,'bob','0','PUBLIC',1,'V1',current_timestamp)");
var config=AuthorizedDatabaseTestSupport.configuration("mapper/production/BomMapper.xml");config.setEnvironment(new Environment("isolated-bom-ownership",new JdbcTransactionFactory(),source));
try(var session=new SqlSessionFactoryBuilder().build(config).openSession(true)){var mapper=session.getMapper(BomMapper.class);assertEquals("alice",mapper.selectProduct(7L).getCreateBy());assertEquals("bob",mapper.selectVersion(9L).getCreateBy());assertEquals("bob",mapper.selectPublicVersions(1L,null).get(0).getCreateBy());}
}
}

View File

@ -61,7 +61,7 @@ class BomServiceTest {
assertEquals(new BigDecimal("0.0019"), request.getLines().get(0).getUnitQuantity()); verify(mapper).clearDefault(1L, null); verify(mapper).insertLine(any());
}
@Test void settingDefaultChangesMetadataOnlyAndDoesNotRewriteLines() {
BomVersion bom=request();bom.setId(9L);bom.setScopeType("PUBLIC");bom.setVersion(0);bom.setIsDefault(false);
BomVersion bom=request();bom.setCreateBy("tester");bom.setId(9L);bom.setScopeType("PUBLIC");bom.setVersion(0);bom.setIsDefault(false);
when(mapper.selectVersion(9L)).thenReturn(bom);when(mapper.selectLines(9L)).thenReturn(List.of(line("2")));when(mapper.updateVersion(any())).thenReturn(1);
try(var security=mockStatic(SecurityUtils.class)) {
security.when(SecurityUtils::getUsername).thenReturn("tester");

View File

@ -14,7 +14,8 @@ class PurchaseArrivalQueueMapperTest {
var query=new PurchaseRequest();query.setPendingRegistration(true);
String sql=sql(query);
assertTrue(sql.contains("pr.historical=0 and pr.purchase_status<>5"));
assertTrue(sql.contains("pr.price_locked=1 and pr.final_unit_price>=0 and pb.supplier_id is not null"));
assertTrue(sql.contains("pb.supplier_id is not null and pb.del_flag='0'"));
assertFalse(sql.contains("pr.price_locked=1"));assertFalse(sql.contains("pr.final_unit_price>=0"));
assertTrue(sql.contains("pr.quantity>coalesce(pa.accepted_quantity,0)+coalesce(pa.pending_quantity,0)"));
// Explicitly confirmed zero quotes remain valid; do not silently require a positive price.
assertFalse(sql.contains("pr.final_unit_price>0"));

View File

@ -10,15 +10,37 @@ import com.ruoyi.warehouse.service.impl.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchaseArrivalRulesTest {
@Test void ordinaryArrivalAndAcceptanceRequireConfirmedPrice(){
@Test void registrationStillRequiresPhotoAndLegacyRejectionDoesNotCreateAcceptance(){
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);
var service=new PurchaseArrivalServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class);
ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals);
var request=new PurchaseRequest();request.setId(1L);request.setPriceLocked(false);request.setFinalUnitPrice(BigDecimal.TEN);request.setPurchaseStatus(0);
when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request);
var arrival=new PurchaseArrival();arrival.setId(2L);arrival.setPurchaseRequestId(1L);arrival.setArrivalQuantity(BigDecimal.ONE);arrival.setAcceptanceStatus(0);
assertThrows(ServiceException.class,()->service.insertPurchaseArrival(arrival));verify(arrivals,never()).insertPurchaseArrival(any());
when(arrivals.selectPurchaseArrivalByIdForUpdate(2L)).thenReturn(arrival);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1);
assertThrows(ServiceException.class,()->service.acceptPurchaseArrival(2L,acceptance));
when(arrivals.selectPurchaseArrivalByIdForUpdate(2L)).thenReturn(arrival);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(2);
assertTrue(assertThrows(ServiceException.class,()->service.acceptPurchaseArrival(2L,acceptance)).getMessage().contains("取消线下验收"));
}
}
@Test void unquotedArrivalWithPhotoCanBeRegisteredWithoutInventingAPrice(){
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("owner");
var service=new PurchaseArrivalServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class);var db=mock(org.springframework.jdbc.core.JdbcTemplate.class);var numbers=mock(BusinessNumberService.class);var photos=mock(PurchaseArrivalPhotoService.class);
ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals);ReflectionTestUtils.setField(service,"database",db);ReflectionTestUtils.setField(service,"businessNumbers",numbers);ReflectionTestUtils.setField(service,"arrivalPhotos",photos);ReflectionTestUtils.setField(service,"purchaseOperationLogService",mock(com.ruoyi.warehouse.service.IPurchaseOperationLogService.class));
var request=new PurchaseRequest();request.setId(1L);request.setPurchaseBatchId(7L);request.setQuantity(BigDecimal.TEN);request.setPriceLocked(false);request.setEstimatedUnitPrice(new BigDecimal("999"));request.setPurchaseStatus(0);when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request);
when(db.queryForObject(anyString(),eq(Long.class),eq(7L))).thenReturn(1L);when(arrivals.selectActiveQuantityByRequestId(1L)).thenReturn(BigDecimal.ZERO);when(arrivals.insertPurchaseArrival(any())).thenAnswer(c->{((PurchaseArrival)c.getArgument(0)).setId(8L);return 1;});when(arrivals.updatePurchaseArrivalAcceptance(any())).thenReturn(1);when(arrivals.selectAcceptedQuantityByRequestId(1L)).thenReturn(BigDecimal.ONE);ReflectionTestUtils.setField(service,"inRecordMapper",mock(InRecordMapper.class));when(numbers.next("PA")).thenReturn("DH-TEST");
var arrival=new PurchaseArrival();arrival.setPurchaseRequestId(1L);arrival.setArrivalQuantity(BigDecimal.ONE);arrival.setArrivalDate(new java.util.Date());arrival.setPhotoIds(java.util.List.of("11111111-1111-4111-8111-111111111111"));
assertEquals(1,service.insertPurchaseArrival(arrival));assertNull(arrival.getActualUnitPrice());assertNull(arrival.getActualAmount());assertEquals(1,arrival.getAcceptanceStatus());assertNull(arrival.getAcceptedBy());assertNull(arrival.getAcceptedTime());verify(photos).bind(arrival);
verify(requests).updatePurchaseStatus(eq(1L),eq(3),any(),eq("owner"));
}
}
@Test void submissionRecoveryFindsTheReservedNumberWithoutAllocatingAnotherArrival(){
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);
var service=new PurchaseArrivalServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class);var numbers=mock(BusinessNumberService.class);var photos=mock(PurchaseArrivalPhotoService.class);
ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals);ReflectionTestUtils.setField(service,"businessNumbers",numbers);ReflectionTestUtils.setField(service,"arrivalPhotos",photos);
var request=new PurchaseRequest();request.setId(1L);when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request);when(requests.selectPurchaseRequestById(1L,null)).thenReturn(request);when(numbers.lookup("PA","stable-key")).thenReturn("DH-RECOVERED");
var saved=new PurchaseArrival();saved.setId(17L);saved.setArrivalNo("DH-RECOVERED");saved.setPurchaseRequestId(1L);when(arrivals.selectPurchaseArrivalList(1L)).thenReturn(java.util.List.of(saved));
assertSame(saved,service.findSubmittedArrival(1L,"stable-key"));when(numbers.lookup("PA","absent-key")).thenReturn(null);assertNull(service.findSubmittedArrival(1L,"absent-key"));verify(numbers,never()).reserve(any(),any(),any());verify(arrivals,never()).insertPurchaseArrival(any());
}
}
@Test void newRegistrationRequiresAtLeastOnePhotoBeforeCreatingAnyArrival(){
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);

View File

@ -0,0 +1,30 @@
package com.ruoyi.projectdev;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.domain.*;
import com.ruoyi.project.mapper.*;
import com.ruoyi.project.service.IProjectInfoService;
import com.ruoyi.warehouse.domain.*;
import com.ruoyi.warehouse.mapper.*;
import com.ruoyi.warehouse.service.*;
import com.ruoyi.warehouse.service.impl.*;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchaseFirstQuoteTest {
@Test void aFirstQuoteAfterArrivalUpdatesPendingAmountsButLaterChangesRequireCorrection(){
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("owner");
var service=new PurchaseRequestServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class);var products=mock(ProductInfoMapper.class);var projects=mock(ProjectInfoMapper.class);var budgets=mock(ProjectBudgetMapper.class);var db=mock(JdbcTemplate.class);
ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals);ReflectionTestUtils.setField(service,"productInfoMapper",products);ReflectionTestUtils.setField(service,"projectInfoMapper",projects);ReflectionTestUtils.setField(service,"projectBudgetMapper",budgets);ReflectionTestUtils.setField(service,"projectInfoService",mock(IProjectInfoService.class));ReflectionTestUtils.setField(service,"taskDatabase",db);ReflectionTestUtils.setField(service,"itemCategories",mock(ItemCategoryService.class));ReflectionTestUtils.setField(service,"priceService",mock(PurchasePriceService.class));ReflectionTestUtils.setField(service,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));
var existing=row();when(requests.selectPurchaseRequestByIdForUpdate(10L)).thenReturn(existing);when(arrivals.selectActiveQuantityByRequestId(10L)).thenReturn(BigDecimal.ONE);when(arrivals.selectAcceptedQuantityByRequestId(10L)).thenReturn(BigDecimal.ONE);when(requests.updatePurchaseRequest(any(),isNull())).thenReturn(1);
var project=new ProjectInfo();project.setId(2L);project.setProjectCode("P2");when(projects.selectProjectInfoById(2L,null)).thenReturn(project);var category=new ExpenseCategory();category.setId(3L);when(budgets.selectExpenseCategoryById(3L)).thenReturn(category);
var product=new ProductInfo();product.setId(5L);product.setProductName("电机");product.setCategory("配件");product.setUnit("个");when(products.selectProductInfoById(5L)).thenReturn(product);
var input=row();input.setFinalUnitPrice(new BigDecimal("12"));assertEquals(1,service.updatePurchaseRequest(input));
verify(db).update(startsWith("update purchase_arrival set actual_unit_price="),eq(new BigDecimal("12")),eq(new BigDecimal("12")),eq("owner"),eq(10L));
existing.setFinalUnitPrice(BigDecimal.TEN);assertTrue(assertThrows(com.ruoyi.common.exception.ServiceException.class,()->service.updatePurchaseRequest(input)).getMessage().contains("更正价格"));
}
}
private PurchaseRequest row(){var row=new PurchaseRequest();row.setId(10L);row.setProjectId(2L);row.setExpenseCategoryId(3L);row.setProductId(5L);row.setMaterialName("电机");row.setCategory("配件");row.setUnit("个");row.setQuantity(new BigDecimal("5"));row.setPriceLocked(false);row.setPurchaseStatus(0);row.setPurchasePurpose("SELF");return row;}
}

View File

@ -0,0 +1,32 @@
package com.ruoyi.projectdev;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.warehouse.domain.*;
import com.ruoyi.warehouse.service.*;
import com.ruoyi.web.controller.warehouse.PurchaseRequestController;
import com.github.pagehelper.Page;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchasePhotoLookupTest {
@Test void completedAndZeroPriceRowsRemainDiscoverableAndQuotesStayPrivate(){
var controller=new PurchaseRequestController();var requests=mock(IPurchaseRequestService.class);var batches=mock(IPurchaseBatchService.class);
ReflectionTestUtils.setField(controller,"purchaseRequestService",requests);ReflectionTestUtils.setField(controller,"purchaseBatchService",batches);
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
try(var security=mockStatic(SecurityUtils.class)){
var row=new PurchaseRequest();row.setId(3L);row.setPurchaseStatus(4);row.setFinalUnitPrice(BigDecimal.ZERO);
var page=new Page<PurchaseRequest>(1,20);page.add(row);page.setTotal(41);
when(requests.selectPurchaseRequestList(any())).thenAnswer(call->{PurchaseRequest q=call.getArgument(0);assertEquals(7L,q.getPurchaseBatchId());assertEquals("水泵",q.getMaterialName());assertNull(q.getPendingRegistration());assertNull(q.getPendingAcceptance());assertNull(q.getArrivalReady());assertNull(q.getPurchaseStatus());assertFalse(q.getParams().containsKey("amountDisplay"));return page;});
var result=controller.photoRecords(7L,"水泵");assertEquals(41,result.getTotal());var visible=(PurchaseRequest)result.getRows().get(0);assertEquals(4,visible.getPurchaseStatus());assertNull(visible.getFinalUnitPrice());
var batch=new PurchaseBatch();batch.setId(7L);batch.setTotalAmount(BigDecimal.TEN);var batchPage=new Page<PurchaseBatch>(1,20);batchPage.add(batch);batchPage.setTotal(22);
when(batches.selectPurchaseBatchList(any())).thenAnswer(call->{PurchaseBatch q=call.getArgument(0);assertEquals("批次",q.getKeyword());assertNull(q.getPurchaseStatus());assertFalse(q.getParams().containsKey("amountDisplay"));return batchPage;});
var all=controller.photoRecordBatches("批次");assertEquals(22,all.getTotal());assertNull(((PurchaseBatch)all.getRows().get(0)).getTotalAmount());
assertThrows(com.ruoyi.common.exception.ServiceException.class,()->controller.photoRecords(0L,null));
}finally{com.github.pagehelper.PageHelper.clearPage();RequestContextHolder.resetRequestAttributes();}
}
}

View File

@ -0,0 +1,52 @@
package com.ruoyi.projectdev;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.project.service.IProjectInfoService;
import com.ruoyi.warehouse.domain.*;
import com.ruoyi.warehouse.mapper.*;
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
import com.ruoyi.warehouse.service.impl.*;
import com.ruoyi.warehouse.util.MovingAverageCost;
import java.math.BigDecimal;
import java.util.*;
import org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchasePhysicalReceiptTest {
@Test void unquotedReceiptIncreasesStockWithUnknownCostThenLaterQuoteResolvesConsumedAndRemainingCost(){
try(var security=mockStatic(SecurityUtils.class)){
security.when(SecurityUtils::getUsername).thenReturn("owner");security.when(SecurityUtils::isAdmin).thenReturn(true);
var service=new InRecordServiceImpl();var records=mock(InRecordMapper.class);var requests=mock(PurchaseRequestMapper.class);var journal=mock(InventoryCostJournal.class);
ReflectionTestUtils.setField(service,"inRecordMapper",records);ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"journal",journal);ReflectionTestUtils.setField(service,"projectInfoService",mock(IProjectInfoService.class));ReflectionTestUtils.setField(service,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));
var request=new PurchaseRequest();request.setId(1L);request.setProjectId(2L);request.setProductId(3L);request.setPurchaseStatus(4);request.setPriceLocked(false);request.setFinalUnitPrice(null);
when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request);
var receipt=new InRecord();receipt.setId(4L);receipt.setPurchaseRequestId(1L);receipt.setProductId(3L);receipt.setInNum(BigDecimal.TEN);receipt.setAreaId(5L);receipt.setInStatus(0);receipt.setInOperator("owner");receipt.setReceiptRoot(false);
when(records.selectInRecordById(4L)).thenReturn(receipt);when(records.selectInRecordByIdForUpdate(4L)).thenReturn(receipt);when(records.confirmInRecord(any())).thenReturn(1);
when(journal.append(any())).thenAnswer(call->{InventoryCostEvent event=call.getArgument(0);assertNull(event.getReceiptAmount());assertEquals(BigDecimal.TEN,event.getQuantity());event.setId(6L);return event;});
assertEquals(1,service.confirmInRecord(4L,"owner"));assertNull(receipt.getReceiptUnitCost());
var events=List.of(new MovingAverageCost.Event(6L,MovingAverageCost.Type.RECEIPT,BigDecimal.TEN,null,null,true),new MovingAverageCost.Event(7L,MovingAverageCost.Type.ISSUE,new BigDecimal("4"),null,null,true));
var unknown=MovingAverageCost.replay(events);assertNull(unknown.events().get(1).amount());assertFalse(unknown.balance().complete());
var priced=MovingAverageCost.replay(events,Map.of(6L,new BigDecimal("120")));
assertEquals(new BigDecimal("48.000000"),priced.events().get(1).amount());assertEquals(new BigDecimal("72.000000"),priced.balance().amount());assertEquals(unknown.balance().quantity(),priced.balance().quantity());
}
}
@Test void historicalPendingArrivalNeedsPhotosThenCreatesOneRootWithoutHumanSignoff(){
try(var security=mockStatic(SecurityUtils.class)){
security.when(SecurityUtils::getUsername).thenReturn("owner");security.when(SecurityUtils::isAdmin).thenReturn(true);
var service=new PurchaseArrivalServiceImpl();var requests=mock(PurchaseRequestMapper.class);var arrivals=mock(PurchaseArrivalMapper.class);var records=mock(InRecordMapper.class);var numbers=mock(BusinessNumberService.class);var photos=mock(PurchaseArrivalPhotoService.class);
ReflectionTestUtils.setField(service,"journal",mock(InventoryCostJournal.class));ReflectionTestUtils.setField(service,"purchaseRequestMapper",requests);ReflectionTestUtils.setField(service,"purchaseArrivalMapper",arrivals);ReflectionTestUtils.setField(service,"inRecordMapper",records);ReflectionTestUtils.setField(service,"arrivalPhotos",photos);ReflectionTestUtils.setField(service,"businessNumbers",numbers);ReflectionTestUtils.setField(service,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));
var request=new PurchaseRequest();request.setId(1L);request.setQuantity(BigDecimal.ONE);request.setProjectId(2L);request.setProductId(3L);request.setPurchaseStatus(0);when(requests.selectPurchaseRequestByIdForUpdate(1L)).thenReturn(request);
var arrival=new PurchaseArrival();arrival.setId(4L);arrival.setPurchaseRequestId(1L);arrival.setArrivalNo("DH-4");arrival.setArrivalDate(new Date());arrival.setArrivalQuantity(BigDecimal.ONE);arrival.setAcceptanceStatus(0);when(arrivals.selectPurchaseArrivalByIdForUpdate(4L)).thenReturn(arrival);
assertTrue(assertThrows(ServiceException.class,()->service.prepareArrivalForReceipt(4L)).getMessage().contains("照片"));verifyNoInteractions(records);
// A saved photo is attached by the real photo service; this isolated test supplies that evidence.
doAnswer(c->{arrival.setPhotos(List.of(new PurchaseArrivalPhoto("id","name","image/png",1,"owner",null)));return null;}).when(photos).attach(anyList());
when(arrivals.updatePurchaseArrivalAcceptance(arrival)).thenReturn(1);when(arrivals.selectAcceptedQuantityByRequestId(1L)).thenReturn(BigDecimal.ONE);
assertEquals(1,service.prepareArrivalForReceipt(4L));assertNull(arrival.getAcceptedBy());assertNull(arrival.getAcceptedTime());assertEquals(1,service.prepareArrivalForReceipt(4L));
verify(records,times(1)).insertInRecord(argThat(r->Boolean.TRUE.equals(r.getReceiptRoot())&&r.getInStatus()==0&&r.getProductId()==3L&&r.getSourceProjectId()==2L&&r.getArrivalId()==4L));
verify(requests,times(1)).updatePurchaseStatus(eq(1L),eq(4),any(),eq("owner"));
}
}
}

View File

@ -29,6 +29,28 @@ class PurchaseArrivalPhotosTest {
assertTrue(bytes.length>5*1024*1024);assertTrue(bytes.length<20*1024*1024);
service.upload(10L,A,new MockMultipartFile("file","camera.png","image/png",bytes));assertArrayEquals(bytes,service.content(A).bytes());
}
@Test void qqImagesUseRealFormatInsteadOfNameOrMimeAndKeepOriginalJpegEvidence()throws Exception{
var out=new ByteArrayOutputStream();ImageIO.write(new BufferedImage(2,2,BufferedImage.TYPE_INT_RGB),"jpeg",out);byte[] jpeg=out.toByteArray();
var file=new MockMultipartFile("file","球头铣刀R2.png","image/png",jpeg);
var saved=service.upload(10L,A,file);assertEquals("image/jpeg",saved.contentType());assertEquals("球头铣刀R2.jpg",saved.name());assertArrayEquals(jpeg,service.content(A).bytes());
assertEquals(A,service.upload(10L,A,file).id());verify(storage,times(1)).save(anyString(),any(byte[].class),anyString(),any(Path.class));
var png=image();var other=service.upload(10L,B,new MockMultipartFile("file","QQ图片.jpg","application/octet-stream",png.getBytes()));
assertEquals("image/png",other.contentType());assertEquals("QQ图片.png",other.name());assertArrayEquals(png.getBytes(),service.content(B).bytes());
}
@Test void gifBmpAndTiffBecomeViewablePngAndCanBeRetried()throws Exception{
for(String format:List.of("gif","bmp","tiff")){
var out=new ByteArrayOutputStream();assertTrue(ImageIO.write(new BufferedImage(3,2,BufferedImage.TYPE_INT_RGB),format,out));
String id=UUID.randomUUID().toString();var file=new MockMultipartFile("file","照片."+format,"application/octet-stream",out.toByteArray());
var saved=service.upload(10L,id,file);assertEquals("image/png",saved.contentType());assertEquals("照片.png",saved.name());
var decoded=ImageIO.read(new java.io.ByteArrayInputStream(service.content(id).bytes()));assertEquals(3,decoded.getWidth());assertEquals(2,decoded.getHeight());decoded.flush();
assertEquals(id,service.upload(10L,id,file).id());
}
}
@Test void renamedNonImagesAndDamagedJpegsAreRejectedBeforeStorage()throws Exception{
for(byte[] bytes:List.of("<svg xmlns='http://www.w3.org/2000/svg'/>".getBytes(),new byte[]{(byte)0xff,(byte)0xd8,(byte)0xff,0,0}))
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","照片.jpg","image/jpeg",bytes)));
verifyNoInteractions(storage);
}
static final String A="11111111-1111-4111-8111-111111111111",B="22222222-2222-4222-8222-222222222222";
@TempDir Path temp;
JdbcTemplate db;PurchaseArrivalPhotoService service;TransactionTemplate tx;MockedStatic<SecurityUtils> security;BusinessFileStorage storage;Map<String,byte[]> files;
@ -69,12 +91,12 @@ class PurchaseArrivalPhotosTest {
service.upload(10L,A,image());assertThrows(ServiceException.class,()->tx.executeWithoutResult(s->{db.update("insert into purchase_arrival(id) values(100)");service.bind(arrival(100,10,A,B));}));
assertEquals(0,db.queryForObject("select count(*) from purchase_arrival",Integer.class));assertNull(db.queryForObject("select arrival_id from purchase_arrival_photo where id=?",Long.class,A));assertTrue(service.content(A).bytes().length>0);
}
@Test void rejectsBadFilesLimitsAndUnconfirmedPurchasesBeforeStoring()throws Exception{
assertThrows(ServiceException.class,()->service.upload(30L,A,image()));
@Test void unquotedPurchasesCanUploadEvidenceWhileBadFilesAndLimitsAreRejected()throws Exception{
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","fake.png","image/png","not an image".getBytes())));
assertThrows(ServiceException.class,()->service.upload(10L,A,new MockMultipartFile("file","large.png","image/png",new byte[20*1024*1024+1])));
assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(List.of(A,A)));assertThrows(ServiceException.class,()->PurchaseArrivalPhotoService.ids(Collections.nCopies(10,A)));
assertThrows(ServiceException.class,()->service.content("../private"));verifyNoInteractions(storage);
assertEquals(A,service.upload(30L,A,image()).id());
}
@Test void removingDraftAndExpiryNeverDeleteSavedArrivalPhotos()throws Exception{
service.upload(10L,A,image());service.upload(10L,B,image());db.update("insert into purchase_arrival(id) values(100)");service.bind(arrival(100,10,A));

View File

@ -42,8 +42,8 @@ class PurchaseDocumentsTest {
try(var security=mockStatic(SecurityUtils.class)) {
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:manage")).thenReturn(true);
security.when(SecurityUtils::isAdmin).thenReturn(true);
var groups=service.list("batch",1L);assertEquals(5,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty()));
assertEquals(List.of("REQUEST","CONTRACT","ACCEPTANCE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList());
var groups=service.list("batch",1L);assertEquals(6,groups.size());assertTrue(groups.stream().allMatch(g->g.number().isEmpty()&&g.files().isEmpty()));
assertEquals(List.of("REQUEST","CONTRACT","ACCEPTANCE","INVOICE","PAYMENT","OTHER"),groups.stream().map(PurchaseDocumentService.Group::kind).toList());
assertEquals("OTHER",service.list("detail",1L).get(0).kind());
}
verify(db,never()).update(anyString(),any(Object[].class));
@ -59,7 +59,7 @@ class PurchaseDocumentsTest {
});
try(var security=mockStatic(SecurityUtils.class)) {
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:list")).thenReturn(true);
assertEquals(5,service.list("batch",1L).size());
assertEquals(6,service.list("batch",1L).size());
assertTrue(service.list("batch",1L).stream().noneMatch(group->group.kind().equals("QUOTE")));
assertThrows(ServiceException.class,()->service.content("batch",1L,ID));
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:edit")).thenReturn(true);
@ -165,6 +165,26 @@ class PurchaseDocumentsTest {
verifyNoInteractions(db);
}
@Test void fiftyMbPdfCanBeUploadedAndReadBack() throws Exception {
byte[] bytes=new byte[50*1024*1024];Arrays.fill(bytes,(byte)' ');
System.arraycopy(PDF,0,bytes,0,8);System.arraycopy(PDF,8,bytes,bytes.length-PDF.length+8,PDF.length-8);
String sha=HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db);
when(db.queryForList(anyString(),any(Object[].class))).thenAnswer(call->{
String sql=call.getArgument(0,String.class);
if(sql.startsWith("select id,create_by"))return List.of(Map.of("id",1L));
if(sql.startsWith("select a.original_name"))return List.of(Map.of("original_name","大附件.pdf","content_type","application/pdf","byte_size",bytes.length,"sha256",sha));
return List.of();
});
when(db.queryForObject(startsWith("select id from purchase_document_group"),eq(Long.class),eq("batch"),eq(1L),eq("REQUEST"))).thenReturn(5L);
when(db.queryForObject(startsWith("select count(*)"),eq(Integer.class),eq("batch"),eq(1L))).thenReturn(0);
try(var security=mockStatic(SecurityUtils.class)){
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("editor");security.when(SecurityUtils::getUserId).thenReturn(1L);
assertEquals(bytes.length,service.upload("batch",1L,"REQUEST",ID,new MockMultipartFile("file","大附件.pdf","application/pdf",bytes)).size());
assertArrayEquals(bytes,service.content("batch",1L,ID).bytes());
}
}
@Test void missingAndWrongTargetFilesNeverReachDiskOrLeakContent() {
JdbcTemplate db=mock(JdbcTemplate.class);var service=service(db);
when(db.queryForList(startsWith("select id,create_by"),eq(1L))).thenReturn(List.of(Map.of("id",1L)));

View File

@ -0,0 +1,51 @@
package com.ruoyi.warehouse.service.impl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import java.nio.file.Path;
import java.util.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class PurchaseInvoiceGateTest {
@TempDir Path temp;JdbcTemplate db;PurchaseDocumentService service;org.mockito.MockedStatic<SecurityUtils> security;
final String invoice="11111111-1111-4111-8111-111111111111",payment="22222222-2222-4222-8222-222222222222";
MockMultipartFile pdf(){return new MockMultipartFile("file","发票.pdf","application/pdf","%PDF-1.7\n1 0 obj<</Type/Catalog>>endobj\nstartxref\n0\n%%EOF\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII));}
@BeforeEach void setup(){
db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""));
db.execute("create table purchase_batch(id bigint primary key,create_by varchar(64),del_flag char(1) default '0')");db.update("insert into purchase_batch(id,create_by) values(7,'owner')");
db.execute("create table purchase_document_group(id bigint auto_increment primary key,target_type varchar(10),target_id bigint,document_kind varchar(16),document_no varchar(100) default '',version int default 0,update_by varchar(64),update_time timestamp default current_timestamp,unique(target_type,target_id,document_kind))");
db.execute("create table purchase_document_attachment(id varchar(36) primary key,group_id bigint,original_name varchar(180),content_type varchar(100),byte_size int,sha256 varchar(64),owner_id bigint,create_by varchar(64),create_time timestamp default current_timestamp,deleted int default 0,server_generated boolean default false)");
service=new PurchaseDocumentService();ReflectionTestUtils.setField(service,"db",db);ReflectionTestUtils.setField(service,"configuredPath",temp.resolve("private").toString());new RuoYiConfig().setProfile(temp.resolve("public").toString());
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("owner");security.when(SecurityUtils::getUserId).thenReturn(1L);
}
@AfterEach void cleanup(){security.close();}
@Test void pdfInAcceptanceCannotSubstituteForInvoiceAndBothPaymentWritesAreBlocked(){
service.upload("batch",7L,"ACCEPTANCE",invoice,pdf());
assertTrue(assertThrows(ServiceException.class,()->service.saveNumber("batch",7L,"PAYMENT","FK-1",0)).getMessage().contains("验收发票"));
assertTrue(assertThrows(ServiceException.class,()->service.upload("batch",7L,"PAYMENT",payment,pdf())).getMessage().contains("验收发票"));
assertEquals(0,db.queryForObject("select count(*) from purchase_document_group where document_kind='PAYMENT'",Integer.class));
}
@Test void separateInvoiceEnablesPaymentAndCannotBeRemovedAsTheLastInvoice(){
service.upload("batch",7L,"INVOICE",invoice,pdf());service.saveNumber("batch",7L,"PAYMENT","FK-1",0);service.upload("batch",7L,"PAYMENT",payment,pdf());
assertEquals(1,db.queryForObject("select count(*) from purchase_document_group where document_kind='INVOICE'",Integer.class));
assertThrows(ServiceException.class,()->service.remove("batch",7L,invoice));
assertEquals(0,db.queryForObject("select deleted from purchase_document_attachment where id=?",Integer.class,invoice));
}
@Test void deletedInvoicesAndNumberOnlyInvoiceGroupsDoNotSatisfyPayment(){
service.upload("batch",7L,"INVOICE",invoice,pdf());db.update("update purchase_document_attachment set deleted=1 where id=?",invoice);
assertThrows(ServiceException.class,()->service.saveNumber("batch",7L,"PAYMENT","FK-1",0));
assertThrows(ServiceException.class,()->service.saveNumber("batch",7L,"INVOICE","INV-1",0));
assertThrows(ServiceException.class,()->service.upload("detail",7L,"INVOICE",payment,pdf()));
}
@Test void invoicePhotosUseTheActualImageFormatAndRejectOfficeDocuments()throws Exception{
var output=new java.io.ByteArrayOutputStream();javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(2,2,java.awt.image.BufferedImage.TYPE_INT_RGB),"jpeg",output);
var image=service.upload("batch",7L,"INVOICE",invoice,new MockMultipartFile("file","发票.png","image/png",output.toByteArray()));assertEquals("image/jpeg",image.contentType());assertEquals("发票.jpg",image.name());assertArrayEquals(output.toByteArray(),service.content("batch",7L,invoice).bytes());
assertThrows(ServiceException.class,()->service.upload("batch",7L,"INVOICE",payment,new MockMultipartFile("file","发票.docx","application/octet-stream",output.toByteArray())));
}
}

View File

@ -0,0 +1,19 @@
package com.ruoyi.warehouse.service.impl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.warehouse.domain.PurchaseRequest;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PurchaseSheetReceiptKeysTest {
private PurchaseRequest row(String key,Long id){var row=new PurchaseRequest();row.setClientRowKey(key);row.setId(id);return row;}
@Test void returnsBothLegacyDecimalKeysAndCurrentKeys(){
var result=PurchaseSheetService.clientRowIds(List.of(row("new-1721000-0.12345",8L),row("new-1721000-abc",9L)));
assertEquals(8L,result.get("new-1721000-0.12345"));assertEquals(9L,result.get("new-1721000-abc"));
}
@Test void refusesAmbiguousOrInvalidReceipts(){
assertThrows(ServiceException.class,()->PurchaseSheetService.clientRowIds(List.of(row("same",8L),row("same",9L))));
assertThrows(ServiceException.class,()->PurchaseSheetService.clientRowIds(List.of(row("bad/key",8L))));
}
}

View File

@ -30,7 +30,7 @@ class AssistantProductActionsTest {
ProductionProduct source(){var source=new ProductionProduct();source.setId(7L);source.setVersion(4);source.setSeriesId(2L);source.setSeriesVersion(3);source.setSeriesName("测试系列");source.setEditionTag("试制版");source.setItemId(11L);return source;}
Map<String,Object> row(){return new LinkedHashMap<>(Map.of("sourceProductId",7L,"editionTag","2026改进款","cloneItem",true,"itemName","测试整机","itemSpec","新规格"));}
@Test void previewCreatesNothingAndBindsSourceAndBomConcurrency(){
when(products.requireProduct(7L)).thenReturn(source());when(products.sourceBomVersion(7L,9L)).thenReturn(6);
when(products.requireProductWrite(7L)).thenReturn(source());when(products.sourceBomVersion(7L,9L)).thenReturn(6);
when(products.preview(any())).thenAnswer(call->Map.of("source",source(),"notice","独立库存和成本","sourceBom",Map.of("version",6)));
var row=row();row.put("copyBomId",9L);row.put("bomTag","量产BOM");row.put("sourceVersion",999);row.put("seriesVersion",999);row.put("copyBomVersion",999);
var snapshots=new LinkedHashMap<String,Object>();var errors=new ArrayList<String>();actions.prepare("product.versionCreate",row,snapshots,errors);
@ -42,19 +42,19 @@ class AssistantProductActionsTest {
verify(products,times(1)).sourceBomVersion(7L,9L);
}
@Test void businessValidationAndSupplementalPermissionFailuresStayInDraft(){
when(products.requireProduct(7L)).thenReturn(source());when(products.preview(any())).thenThrow(new ServiceException("复制BOM可请同事协助",403));
when(products.requireProductWrite(7L)).thenReturn(source());when(products.preview(any())).thenThrow(new ServiceException("复制BOM可请同事协助",403));
var errors=new ArrayList<String>();actions.prepare("product.versionCreate",row(),new LinkedHashMap<>(),errors);assertEquals(List.of("复制BOM可请同事协助"),errors);verify(products,never()).create(any());
}
@Test void metadataRenamePreservesOtherNameAndExplainsSeriesWideEffect(){
when(products.requireProduct(7L)).thenReturn(source());var row=new LinkedHashMap<String,Object>(Map.of("id",7L,"editionTag","量产版"));var errors=new ArrayList<String>();
when(products.requireProductWrite(7L)).thenReturn(source());var row=new LinkedHashMap<String,Object>(Map.of("id",7L,"editionTag","量产版"));var errors=new ArrayList<String>();
actions.prepare("product.save",row,new LinkedHashMap<>(),errors);assertTrue(errors.isEmpty());assertEquals("测试系列",row.get("seriesName"));assertEquals(3,row.get("seriesVersion"));assertTrue(row.get("operationNotice").toString().contains("同系列"));verify(products,never()).save(any());
}
@Test void legacyMetadataNeedsBothExplicitNames(){
var old=source();old.setSeriesId(null);old.setSeriesName(null);old.setEditionTag(null);when(products.requireProduct(7L)).thenReturn(old);
var old=source();old.setSeriesId(null);old.setSeriesName(null);old.setEditionTag(null);when(products.requireProductWrite(7L)).thenReturn(old);
var row=new LinkedHashMap<String,Object>(Map.of("id",7L,"editionTag","量产版"));var errors=new ArrayList<String>();actions.prepare("product.save",row,new LinkedHashMap<>(),errors);assertFalse(errors.isEmpty());
}
@Test void filePreviewValidatesButDoesNotUploadAndConfirmationUsesStableUuid(){
var file=new MockMultipartFile("file","图纸.step","application/octet-stream",new byte[]{1,2});when(uploads.businessFile("owned-file")).thenReturn(file);when(products.requireProduct(7L)).thenReturn(source());
var file=new MockMultipartFile("file","图纸.step","application/octet-stream",new byte[]{1,2});when(uploads.businessFile("owned-file")).thenReturn(file);when(products.requireProductWrite(7L)).thenReturn(source());
var row=new LinkedHashMap<String,Object>(Map.of("id",7L,"attachmentId","owned-file"));var errors=new ArrayList<String>();actions.prepare("product.attachmentUpload",row,new LinkedHashMap<>(),errors);
assertTrue(errors.isEmpty());verify(files).validateUpload(file);verify(files,never()).upload(any(),any(),any());
assertThrows(ServiceException.class,()->actions.upload(row));row.put("_executionKey","confirmed-file-1");actions.upload(row);actions.upload(row);

View File

@ -13,6 +13,20 @@ import java.util.Set;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class UploadTargetsTest {
@Test void purchaseResumableUploadsAllowFiftyMbWithoutChangingSupplierLimits(){
var target=new UploadTargets();var users=mock(ISysUserService.class);var perms=mock(SysPermissionService.class);var purchases=mock(com.ruoyi.warehouse.service.impl.PurchaseDocumentService.class);
ReflectionTestUtils.setField(target,"users",users);ReflectionTestUtils.setField(target,"currentPermissions",perms);ReflectionTestUtils.setField(target,"purchases",purchases);
var user=new SysUser();user.setUserId(27L);user.setStatus("0");user.setDelFlag("0");var login=new LoginUser(27L,1L,user,Set.of());
when(users.selectUserById(27L)).thenReturn(user);when(perms.getMenuPermission(user)).thenReturn(Set.of("warehouse:purchase:edit"));
when(purchases.list("batch",7L)).thenReturn(java.util.List.of(new com.ruoyi.warehouse.service.impl.PurchaseDocumentService.Group("REQUEST","采购申请","",0,java.util.List.of())));
when(purchases.list("detail",8L)).thenReturn(java.util.List.of(new com.ruoyi.warehouse.service.impl.PurchaseDocumentService.Group("OTHER","附件","",0,java.util.List.of())));
try(var security=mockStatic(SecurityUtils.class)){
security.when(SecurityUtils::getLoginUser).thenReturn(login);security.when(SecurityUtils::isAdmin).thenReturn(true);
assertEquals(50*1024*1024,target.authorize(new UploadTargets.Target("purchase",7L,"batch","REQUEST")));
assertEquals(50*1024*1024,target.authorize(new UploadTargets.Target("purchase",8L,"detail","OTHER")));
assertEquals(10*1024*1024,target.authorize(new UploadTargets.Target("supplier",null,null,null)));
}
}
@Test void archiveOneGbLimitStillRequiresLiveArchiveTargetAuthority(){
var target=new UploadTargets();var users=mock(ISysUserService.class);var perms=mock(SysPermissionService.class);var docs=mock(com.ruoyi.web.service.archive.ArchiveDocuments.class);
ReflectionTestUtils.setField(target,"users",users);ReflectionTestUtils.setField(target,"currentPermissions",perms);ReflectionTestUtils.setField(target,"archiveDocuments",docs);

View File

@ -11,13 +11,19 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PurchaseAcceptancePdfTest {
@Test void reproducesSixPageFormWithPhotosAndBlankSignatureArea()throws Exception{
@Test void equipmentReportHasSelectedListPhotosAndBlankSignatureArea()throws Exception{
var rows=new ArrayList<Line>();for(int i=1;i<=254;i++)rows.add(new Line(i,"内六角螺钉","M2*20","个",BigDecimal.valueOf(200),BigDecimal.valueOf(200),i<10?List.of("photo"):List.of()));
var fields=new Fields(PurchaseAcceptanceReportService.COMPANY,"上海则龙信息科技有限公司",PurchaseAcceptanceReportService.ADDRESS,"","","第二代座舱机器人材料及部件(版式示例)",PurchaseAcceptanceReportService.DELIVERY_LOCATION,null,Collections.nCopies(7,"OK"));
var picture=new java.awt.image.BufferedImage(64,64,java.awt.image.BufferedImage.TYPE_INT_RGB);var paint=picture.createGraphics();paint.setColor(java.awt.Color.LIGHT_GRAY);paint.fillRect(0,0,64,64);paint.setColor(java.awt.Color.DARK_GRAY);paint.fillOval(12,12,40,40);paint.dispose();var image=new ByteArrayOutputStream();ImageIO.write(picture,"png",image);
var output=new ByteArrayOutputStream();PurchaseAcceptancePdf.write(new Report("v1","第二代座舱机器人",fields,rows,List.of()),id->image.toByteArray(),output);
var path=Path.of("../.codex-tmp/acceptance-pdf-20261104/验收单版式示例.pdf");Files.createDirectories(path.getParent());Files.write(path,output.toByteArray());
try(var pdf=Loader.loadPDF(output.toByteArray())){assertEquals(6,pdf.getNumberOfPages());String text=new PDFTextStripper().getText(pdf).replaceAll("\\s","");for(String label:List.of("FINALACCEPTANCEREPORT","终验收报告","合同号","项目号","采购数量","到货记录","培训","资料","验收结论","同意验收","验收签字","254"))assertTrue(text.contains(label),label);assertFalse(text.contains("单价"));assertFalse(text.contains("金额"));assertTrue(pdf.getPage(0).getResources().getXObjectNames().iterator().hasNext());}
var path=Path.of("../.codex-tmp/acceptance-template-20261118/多页验收报告示例.pdf");Files.createDirectories(path.getParent());Files.write(path,output.toByteArray());
try(var pdf=Loader.loadPDF(output.toByteArray())){assertTrue(pdf.getNumberOfPages()>=6);String text=new PDFTextStripper().getText(pdf).replaceAll("\\s","");for(String label:List.of("仪器设备验收报告","设备名称","合同编号","采购数量","到货记录","主要技术参数验收","验收结论","同意验收","签字确认","联系人签字或盖章","联系电话","254"))assertTrue(text.contains(label),label);assertFalse(text.contains("单价"));assertFalse(text.contains("金额"));assertTrue(pdf.getPage(0).getResources().getXObjectNames().iterator().hasNext());}
}
@Test void smallBatchIsCompactAndLeavesTechnicalParametersAndUnknownContactsBlank()throws Exception{
var fields=new Fields("验收公司","供货公司","旧地址","HT-001","SX-001","测试设备","招商车研",java.time.LocalDate.of(2026,11,18),Collections.nCopies(7,"OK"),java.time.LocalDate.of(2026,11,10));
var out=new ByteArrayOutputStream();PurchaseAcceptancePdf.write(new Report("v","测试设备",fields,List.of(new Line(1,"试验仪器","型号A","台",BigDecimal.ONE,BigDecimal.ONE,List.of())),List.of()),id->null,out);
var file=Path.of("../.codex-tmp/acceptance-template-20261118/仪器设备验收报告示例.pdf");Files.createDirectories(file.getParent());Files.write(file,out.toByteArray());
try(var pdf=Loader.loadPDF(out.toByteArray())){assertEquals(1,pdf.getNumberOfPages());var text=new PDFTextStripper().getText(pdf).replaceAll("\\s","");assertTrue(text.contains("2026-11-10"));assertTrue(text.contains("2026-11-18"));assertFalse(text.contains("SX-001"));assertFalse(text.contains("若有"));assertFalse(text.contains("机械安装"));assertFalse(text.contains("旧地址"));for(String line:PurchaseAcceptanceReportService.CONCLUSIONS)assertTrue(text.contains(line.replaceAll("\\s","")));}
}
@Test void veryLongSpecificationsAndSupplementalInformationAreNotClipped()throws Exception{
String tail="规格末尾完整保留";var spec="超长规格用于验证自动换行及跨页内容".repeat(180)+tail;

View File

@ -0,0 +1,19 @@
package com.ruoyi.web.service.warehouse;
import com.ruoyi.web.service.warehouse.PurchaseAcceptanceReportService.*;
import java.io.*;import java.math.BigDecimal;import java.nio.file.*;import java.util.*;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;
import org.apache.pdfbox.Loader;import org.apache.pdfbox.rendering.PDFRenderer;import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;import org.apache.pdfbox.pdmodel.*;import org.apache.pdfbox.pdmodel.graphics.image.PDImage;import org.apache.pdfbox.cos.COSName;import java.awt.geom.Point2D;
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;
class PurchaseAcceptancePhotoLayoutTest {
@Test void photosTouchAndEachStripIsCentered()throws Exception{
var fields=new Fields(PurchaseAcceptanceReportService.COMPANY,"供应商",PurchaseAcceptanceReportService.ADDRESS,"HT-TEST","SX-20261113","自由勾选明细版式验证",PurchaseAcceptanceReportService.DELIVERY_LOCATION,null,Collections.nCopies(7,""));
var photos=new HashMap<String,byte[]>();for(int i=0;i<2;i++){var image=new BufferedImage(60*(i+1),60,BufferedImage.TYPE_INT_RGB);var g=image.createGraphics();g.setColor(i==0?java.awt.Color.BLUE:java.awt.Color.ORANGE);g.fillRect(0,0,image.getWidth(),image.getHeight());g.dispose();var out=new ByteArrayOutputStream();ImageIO.write(image,"png",out);photos.put("p"+i,out.toByteArray());}
var lines=List.of(new Line(11,"仅选中的明细","两张照片紧贴居中","个",BigDecimal.ONE,BigDecimal.ONE,List.of("p0","p1")),new Line(12,"第二个勾选项","单张照片居中","个",BigDecimal.ONE,BigDecimal.ONE,List.of("p0")));
var out=new ByteArrayOutputStream();PurchaseAcceptancePdf.write(new Report("v","版式测试",fields,lines,List.of()),photos::get,out);
var dir=Path.of("../.codex-tmp/acceptance-selection-20261113");Files.createDirectories(dir);Files.write(dir.resolve("selection-layout.pdf"),out.toByteArray());
try(var pdf=Loader.loadPDF(out.toByteArray())){var capture=new Capture(pdf.getPage(0));capture.processPage(pdf.getPage(0));assertEquals(3,capture.boxes.size());assertTrue(capture.rectangles.stream().anyMatch(r->Math.abs(r[0]-451)<.01&&Math.abs(r[1]-26)<.01));assertTrue(capture.rectangles.stream().anyMatch(r->Math.abs(r[0]-451)<.01&&Math.abs(r[1]-39)<.01));var a=capture.boxes.get(0);var b=capture.boxes.get(1);var c=capture.boxes.get(2);assertEquals(a[0]+a[2],b[0],.001);assertEquals(455,(a[0]+b[0]+b[2])/2,.001);assertEquals(a[1],b[1],.001);assertEquals(455,c[0]+c[2]/2,.001);ImageIO.write(new PDFRenderer(pdf).renderImageWithDPI(0,150),"png",dir.resolve("selection-layout.png").toFile());}
}
static class Capture extends PDFGraphicsStreamEngine {
List<float[]> boxes=new ArrayList<>(),rectangles=new ArrayList<>();Capture(PDPage page){super(page);}public void drawImage(PDImage image){var m=getGraphicsState().getCurrentTransformationMatrix();boxes.add(new float[]{m.getTranslateX(),m.getTranslateY(),m.getScalingFactorX(),m.getScalingFactorY()});}
public void appendRectangle(Point2D a,Point2D b,Point2D c,Point2D d){rectangles.add(new float[]{(float)a.distance(b),(float)b.distance(c)});}public void clip(int rule){}public void moveTo(float x,float y){}public void lineTo(float x,float y){}public void curveTo(float a,float b,float c,float d,float e,float f){}public Point2D getCurrentPoint(){return new Point2D.Float();}public void closePath(){}public void endPath(){}public void strokePath(){}public void fillPath(int rule){}public void fillAndStrokePath(int rule){}public void shadingFill(COSName name){}
}
}

View File

@ -13,17 +13,18 @@ import static org.mockito.ArgumentMatchers.*;
class PurchaseAcceptanceReportTest {
private PurchaseSheet sheet;private PurchaseAcceptanceReportService service;private JdbcTemplate db;
private final Fields fields=new Fields("甲方","乙方","地址","HT-2026-001","","材料及部件","",null,Collections.nCopies(7,""));
private final Fields fields=new Fields("甲方","乙方","地址","HT-2026-001","SX-1","材料及部件","",null,Collections.nCopies(7,""));
@BeforeEach void setup(){
sheet=new PurchaseSheet();var batch=new PurchaseBatch();batch.setId(1L);batch.setBatchName("验收测试");sheet.setBatch(batch);sheet.setVersion("v1");sheet.setRows(new ArrayList<>(List.of(row(11,1))));
var sheets=mock(PurchaseSheetService.class);when(sheets.load(1L)).thenReturn(sheet);db=mock(JdbcTemplate.class);service=new PurchaseAcceptanceReportService(sheets,db);
when(db.queryForList(contains("select document_no from purchase_document_group"),eq(String.class),eq(1L))).thenReturn(List.of("HT-2026-001"));
when(db.queryForList(contains("document_kind='REQUEST'"),eq(String.class),eq(1L))).thenReturn(List.of("SX-1"));
prerequisites(true,1,true,1);
}
private PurchaseRequest row(long id,int quantity){var row=new PurchaseRequest();row.setId(id);row.setMaterialName("试验物品");row.setMaterialParams("M2*20");row.setQuantity(BigDecimal.valueOf(quantity));row.setPurchaseStatus(4);row.setUnit("个");row.setAcceptedQuantity(BigDecimal.valueOf(quantity));return row;}
private void evidence(int status,int quantity,int defective,int returned){when(db.queryForList(contains("from purchase_arrival a"),eq(1L))).thenReturn(List.of(Map.of("id",1L,"request_id",11L,"status",status,"quantity",quantity,"defective",defective,"returned",returned)));}
private void prerequisites(boolean request,int requestFiles,boolean contract,int contractFiles){when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","REQUEST","number",request?"SX-1":"","files",requestFiles),Map.of("kind","CONTRACT","number",contract?"HT-2026-001":"","files",contractFiles)));}
@Test void acceptsOnlyRealPassedEvidenceAndKeepsOptionalFieldsBlank(){evidence(1,1,0,0);assertTrue(service.export(1,"v1",fields).ready());assertEquals("",service.export(1,"v1",fields).fields().projectNo());assertEquals(1,service.export(1,"v1",fields).lines().size());}
@Test void acceptsOnlyRealPassedEvidenceAndKeepsOptionalFieldsBlank(){evidence(1,1,0,0);assertTrue(service.export(1,"v1",fields).ready());assertEquals("SX-1",service.export(1,"v1",fields).fields().projectNo());assertEquals(1,service.export(1,"v1",fields).lines().size());}
@Test void completedFlagAndSyntheticHistoricalQuantityDoNotSubstituteForAcceptance(){sheet.getRows().get(0).setHistorical(true);assertFalse((Boolean)service.preview(1).get("ready"));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@Test void pendingOrFailedArrivalCannotExport(){evidence(0,1,0,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));evidence(2,1,0,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@Test void returnAndDefectQuantitiesAreNotAcceptedGoods(){evidence(1,2,1,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@ -36,7 +37,7 @@ class PurchaseAcceptanceReportTest {
var loaded=(Fields)service.preview(1).get("fields");assertEquals("HT-2026-001",loaded.contractNo());assertEquals("HT-2026-001",service.export(1,"v1",loaded).fields().contractNo());
}
@Test void fixedAddressesCannotBeOverriddenByRequest(){
evidence(1,1,0,0);var result=service.export(1,"v1",new Fields("甲方","乙方","伪造地址","HT-2026-001","","材料","伪造配送位置",null,Collections.nCopies(7,""))).fields();
evidence(1,1,0,0);var result=service.export(1,"v1",new Fields("甲方","乙方","伪造地址","HT-2026-001","SX-1","材料","伪造配送位置",null,Collections.nCopies(7,""))).fields();
assertEquals(PurchaseAcceptanceReportService.ADDRESS,result.address());assertEquals(PurchaseAcceptanceReportService.DELIVERY_LOCATION,result.deliveryLocation());
}
@Test void changedOrForgedContractNumberMustBeReloaded(){
@ -47,4 +48,17 @@ class PurchaseAcceptanceReportTest {
@Test void completeAcceptanceStillRequiresRequestNumberAndPdf(){evidence(1,1,0,0);prerequisites(false,1,true,1);assertFalse((Boolean)service.preview(1).get("ready"));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));prerequisites(true,0,true,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@Test void contractNumberAloneDoesNotReplaceContractPdf(){evidence(1,1,0,0);prerequisites(true,1,true,0);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));prerequisites(true,1,false,1);assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@Test void mergedLegacyQuoteFilesUseRequestNumberAndNeverQuoteNumber(){evidence(1,1,0,0);when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","REQUEST","number","SX-1","files",0),Map.of("kind","QUOTE","number","Q-OLD","files",1),Map.of("kind","CONTRACT","number","HT-2026-001","files",1)));assertTrue(service.export(1,"v1",fields).ready());when(db.queryForList(contains("select g.document_kind kind"),eq(1L))).thenReturn(List.of(Map.of("kind","QUOTE","number","Q-OLD","files",1),Map.of("kind","CONTRACT","number","HT-2026-001","files",1)));assertThrows(ServiceException.class,()->service.export(1,"v1",fields));}
@Test void onlySelectedRowsAndTheirPhotosAreIncluded(){evidence(1,1,0,0);sheet.getRows().add(row(12,2));var result=service.export(1,"v1",fields,List.of(11L));assertEquals(List.of(11L),result.lines().stream().map(Line::id).toList());assertThrows(ServiceException.class,()->service.export(1,"v1",fields,List.of(12L)));}
@Test void emptyDuplicateForeignAndCancelledSelectionsAreRejected(){evidence(1,1,0,0);for(var ids:List.of(List.<Long>of(),List.of(11L,11L),List.of(999L)))assertThrows(ServiceException.class,()->service.export(1,"v1",fields,ids));var cancelled=row(12,1);cancelled.setPurchaseStatus(5);sheet.getRows().add(cancelled);assertThrows(ServiceException.class,()->service.export(1,"v1",fields,List.of(12L)));}
@Test void projectNumberIsTheRequestNumberAndCannotBeOverridden(){evidence(1,1,0,0);var loaded=(Fields)service.preview(1).get("fields");assertEquals("SX-1",loaded.projectNo());assertThrows(ServiceException.class,()->service.export(1,"v1",new Fields("甲方","乙方","","HT-2026-001","PROJECT-CODE","","",null,Collections.nCopies(7,""))));}
@Test void arrivalDateDefaultsBlankAndUsesTheManuallyChosenDate(){
sheet.setRows(List.of(row(11,1),row(12,1)));
when(db.queryForList(contains("from purchase_arrival a"),eq(1L))).thenReturn(List.of(
Map.of("id",1L,"request_id",11L,"status",1,"quantity",1,"defective",0,"returned",0,"arrival_date",java.sql.Date.valueOf("2026-11-10")),
Map.of("id",2L,"request_id",12L,"status",1,"quantity",1,"defective",0,"returned",0,"arrival_date",java.sql.Date.valueOf("2026-11-17"))));
assertNull(((Fields)service.preview(1).get("fields")).arrivalDate());
var chosen=new Fields(fields.purchaser(),fields.supplier(),fields.address(),fields.contractNo(),fields.projectNo(),fields.description(),fields.deliveryLocation(),fields.date(),fields.checks(),java.time.LocalDate.of(2026,11,18));
assertEquals(java.time.LocalDate.of(2026,11,18),service.export(1,"v1",chosen,List.of(11L)).fields().arrivalDate());
assertNull(service.export(1,"v1",fields,List.of(11L)).fields().arrivalDate());
}
}

View File

@ -78,4 +78,14 @@ class PurchaseBoardDisplayTest {
assertThrows(ServiceException.class,()->f.service.saveOrder(List.of(1L,2L),List.of(2L,1L)));
}
}
@Test @SuppressWarnings("unchecked") void paymentStageRequiresAnActiveInvoiceIncludingImageInvoices(){
var f=new Fixture();f.line(1,1,4,"1","1","1");
f.db.update("insert into purchase_document_group values(1,'batch',1,'PAYMENT','FK-1'),(2,'batch',1,'INVOICE','')");
f.db.update("insert into purchase_document_attachment values(1,1,0,'application/pdf')");
try(var security=mockStatic(SecurityUtils.class)){
security.when(SecurityUtils::isAdmin).thenReturn(true);var q=new PurchaseBatch();q.setKeyword("测试批次1");
java.util.function.Supplier<Boolean> complete=()->{var row=((List<Map<String,Object>>)f.service.batches(q,1,20).get("rows")).get(0);return(Boolean)((List<Map<String,Object>>)row.get("stages")).stream().filter(v->v.get("kind").equals("PAYMENT")).findFirst().orElseThrow().get("complete");};
assertFalse(complete.get());f.db.update("insert into purchase_document_attachment values(2,2,0,'image/jpeg')");assertTrue(complete.get());f.db.update("update purchase_document_attachment set deleted=1 where id=2");assertFalse(complete.get());
}
}
}

View File

@ -25,6 +25,21 @@ import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
class PurchaseLiveServiceTest {
@Test void legacyDecimalRowKeysAndUnfinishedDraftsAreSharedWithoutCreatingPurchaseRows(){
service.open(10,A);
var row=new LinkedHashMap<String,Object>();row.put("key","new-1790000000000-0.12345");row.put("materialName","未完成的新增行");row.put("quantity",1);row.put("finalUnitPrice",20);
assertDoesNotThrow(()->service.state(10,new PurchaseLiveService.State(A,1,null,row.get("key").toString(),"materialName",true,"未完成的新增行",true,List.of(row))));
var visible=PurchaseLiveService.publicMember(members.get(A),false);var drafts=(List<Map<String,Object>>)visible.get("draftRows");assertEquals(1,drafts.size());assertEquals("未完成的新增行",drafts.get(0).get("materialName"));assertFalse(drafts.get(0).containsKey("finalUnitPrice"));
verify(requests,never()).insertPurchaseRequest(any());
assertDoesNotThrow(()->service.state(10,new PurchaseLiveService.State(A,2,null,null,null,false,null,false,List.of())));
assertTrue(((List<?>)members.get(A).get("draftRows")).isEmpty());
}
@Test void sharedDraftsCannotForgePersistentIdsOrContainUnsupportedObjects(){
service.open(10,A);
assertThrows(ServiceException.class,()->service.state(10,new PurchaseLiveService.State(A,1,null,null,null,false,null,false,List.of(Map.of("key","row-1","id",123)))));
assertThrows(ServiceException.class,()->service.state(10,new PurchaseLiveService.State(A,1,null,null,null,false,null,false,List.of(Map.of("key","row-1","materialName",Map.of("nested","value"))))));
assertThrows(ServiceException.class,()->service.state(10,new PurchaseLiveService.State(A,1,null,null,null,false,null,false,List.of(Map.of("key","row-1"),Map.of("key","row-1")))));
}
static final String A="client-aaaaaaaaaaaaaaa",B="client-bbbbbbbbbbbbbbb";
PurchaseLiveStore store;PurchaseLiveService service;JdbcTemplate db;RedisCache tokens;PurchaseRequestMapper requests;MockedStatic<SecurityUtils> security;LoginUser current;
Map<String,Map<String,Object>> members;Map<String,String> leases;ObjectMapper json=new ObjectMapper();

View File

@ -0,0 +1,15 @@
package com.ruoyi.common.utils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import java.util.Set;
/** An active BOM administrator manages products and BOMs without receiving unrelated system privileges. */
public final class BomPermissions {
public static final String ROLE_KEY="bom_manager";
public static final Set<String> ACTIONS=Set.of("production:product:list","production:product:edit","production:bom:list","production:bom:edit");
private BomPermissions(){}
public static boolean isManager(SysUser user){return user!=null&&user.getRoles()!=null&&user.getRoles().stream().anyMatch(role->role!=null&&ROLE_KEY.equals(role.getRoleKey())&&"0".equals(role.getStatus())&&"0".equals(role.getDelFlag()));}
public static boolean isManager(LoginUser login){return login!=null&&isManager(login.getUser());}
public static boolean grants(LoginUser login,String permission){return permission!=null&&ACTIONS.contains(permission.trim())&&isManager(login);}
}

View File

@ -144,7 +144,7 @@ public class SecurityUtils
public static boolean hasPermi(String permission)
{
LoginUser login = getLoginUser();
return PurchasePermissions.grants(login, permission) || hasPermi(login.getPermissions(), permission);
return PurchasePermissions.grants(login, permission) || BomPermissions.grants(login, permission) || hasPermi(login.getPermissions(), permission);
}
/**

View File

@ -8,6 +8,7 @@ import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.PurchasePermissions;
import com.ruoyi.common.utils.BomPermissions;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.PermissionContextHolder;
@ -37,7 +38,7 @@ public class PermissionService
return false;
}
PermissionContextHolder.setContext(permission);
return PurchasePermissions.grants(loginUser, permission) || hasPermissions(loginUser.getPermissions(), permission);
return PurchasePermissions.grants(loginUser, permission) || BomPermissions.grants(loginUser, permission) || hasPermissions(loginUser.getPermissions(), permission);
}
/**
@ -72,7 +73,7 @@ public class PermissionService
Set<String> authorities = loginUser.getPermissions();
for (String permission : permissions.split(Constants.PERMISSION_DELIMITER))
{
if (permission != null && (PurchasePermissions.grants(loginUser, permission) || hasPermissions(authorities, permission)))
if (permission != null && (PurchasePermissions.grants(loginUser, permission) || BomPermissions.grants(loginUser, permission) || hasPermissions(authorities, permission)))
{
return true;
}

View File

@ -12,6 +12,7 @@ import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.PurchasePermissions;
import com.ruoyi.common.utils.BomPermissions;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
@ -80,6 +81,11 @@ public class SysPermissionService
rolePerms = new HashSet<>(rolePerms);
rolePerms.addAll(PurchasePermissions.ACTIONS);
}
if (BomPermissions.ROLE_KEY.equals(role.getRoleKey()) && "0".equals(role.getDelFlag()))
{
rolePerms = new HashSet<>(rolePerms);
rolePerms.addAll(BomPermissions.ACTIONS);
}
role.setPermissions(rolePerms);
perms.addAll(rolePerms);
}

View File

@ -5,6 +5,9 @@ import com.ruoyi.common.core.domain.BaseEntity;
public class BomVersion extends BaseEntity {
private static final long serialVersionUID = 1L;
private Long id;
private Boolean editable;
public Boolean getEditable(){return editable;}
public void setEditable(Boolean value){editable=value;}
private Long itemId;
private String itemCode;
private String itemName;

View File

@ -5,6 +5,9 @@ import com.ruoyi.common.core.domain.BaseEntity;
public class ProductionProduct extends BaseEntity {
private static final long serialVersionUID = 1L;
private Long id;
private Boolean editable;
public Boolean getEditable(){return editable;}
public void setEditable(Boolean value){editable=value;}
private Long itemId;
private String itemCode;
private String itemName;

View File

@ -12,6 +12,7 @@ import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.production.domain.*;
import com.ruoyi.production.mapper.BomMapper;
import com.ruoyi.production.util.BomGraphRules;
import com.ruoyi.production.util.BomDataAccess;
import com.ruoyi.project.service.IProjectInfoService;
import com.ruoyi.warehouse.domain.ProductInfo;
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
@ -22,10 +23,11 @@ public class BomService {
@Autowired private ProductInfoMapper items;
@Autowired private IProjectInfoService projects;
public List<BomVersion> list(Long itemId, String keyword) { return mapper.selectPublicVersions(itemId, keyword); }
public List<BomVersion> list(Long itemId, String keyword) { var rows=mapper.selectPublicVersions(itemId, keyword);rows.forEach(row->row.setEditable(BomDataAccess.canEdit(row)));return rows; }
public BomVersion get(Long id) {
BomVersion bom = requireVersion(id);
if (bom.getProjectId() != null) projects.requireProjectAccess(bom.getProjectId());
if (bom.getProjectId() != null && !BomDataAccess.managesAll()) projects.requireProjectAccess(bom.getProjectId());
bom.setEditable(!"TASK".equals(bom.getScopeType())&&BomDataAccess.canEdit(bom));
bom.setLines(mapper.selectLines(id)); return bom;
}
public List<Map<String, Object>> logs(Long id) { get(id); return mapper.selectLogs(id); }
@ -38,12 +40,14 @@ public class BomService {
request.setScopeType("PUBLIC"); request.setScopeKey("PUBLIC"); request.setProjectId(null);
request.setSourceVersionId(null); request.setVersion(0);
} else {
BomDataAccess.require(existing);
if (!"PUBLIC".equals(existing.getScopeType()) && !"PROJECT".equals(existing.getScopeType()))
throw new ServiceException("任务用料快照不能通过公共BOM入口修改");
if (!Objects.equals(existing.getVersion(), request.getVersion())) throw stale();
request.setItemId(existing.getItemId()); request.setScopeType(existing.getScopeType());
request.setScopeKey(existing.getScopeKey()); request.setProjectId(existing.getProjectId());
request.setSourceVersionId(existing.getSourceVersionId());
request.setCreateBy(existing.getCreateBy());
}
requireItem(request.getItemId()); normalize(request);
if (!"PUBLIC".equals(request.getScopeType())) request.setIsDefault(false);
@ -69,7 +73,7 @@ public class BomService {
BomGraphRules.validate(request, graph);
// A child edit must also keep every existing parent acyclic.
for (BomVersion parent : graph.values()) BomGraphRules.validate(parent, graph);
if (Boolean.TRUE.equals(request.getIsDefault())) mapper.clearDefault(request.getItemId(), request.getId());
if (Boolean.TRUE.equals(request.getIsDefault())) {requireDefaultChange(request.getItemId(),request.getId());mapper.clearDefault(request.getItemId(), request.getId());}
String actor = SecurityUtils.getUsername();
if (existing == null) {
ensureProduct(request.getItemId()); request.setCreateBy(actor); mapper.insertVersion(request);
@ -81,9 +85,11 @@ public class BomService {
}
@Transactional public BomVersion setDefault(Long id, Integer expectedVersion) {
lockGraph(); BomVersion bom = get(id);
BomDataAccess.require(bom);
if (!"PUBLIC".equals(bom.getScopeType())) throw new ServiceException("只能将公共BOM设为默认版本");
if (expectedVersion == null || !Objects.equals(expectedVersion, bom.getVersion())) throw stale();
if (Boolean.TRUE.equals(bom.getIsDefault())) return bom;
requireDefaultChange(bom.getItemId(),bom.getId());
mapper.clearDefault(bom.getItemId(), bom.getId());
bom.setIsDefault(true); bom.setUpdateBy(SecurityUtils.getUsername());
if (mapper.updateVersion(bom) != 1) throw stale();
@ -103,17 +109,19 @@ public class BomService {
}
@Transactional public void delete(Long id) {
lockGraph(); BomVersion bom = get(id);
BomDataAccess.require(bom);
if (!"PUBLIC".equals(bom.getScopeType())) throw new ServiceException("项目副本从项目产品入口维护,不删除任务快照");
if (mapper.countVersionReferences(id) > 0) throw new ServiceException("该BOM已被下级关联、项目或快照引用,不能删除");
audit(bom, "DELETE"); if (mapper.deleteVersion(id) != 1) throw stale();
}
public List<ProductionProduct> products(String keyword) { return mapper.selectProducts(keyword); }
public List<ProductionProduct> products(String keyword) { var rows=mapper.selectProducts(keyword);rows.forEach(row->row.setEditable(BomDataAccess.canEdit(row)));return rows; }
@Transactional public ProductionProduct saveProduct(ProductionProduct request) {
lockGraph(); if (request == null) throw new ServiceException("请选择物品");
checkText(request.getRemark(), 500, "产品说明");
if (request.getId() == null) {
requireItem(request.getItemId());
ProductionProduct product = ensureProduct(request.getItemId());
BomDataAccess.require(product);
if (StringUtils.isNotBlank(request.getRemark())) {
product.setRemark(request.getRemark()); product.setUpdateBy(SecurityUtils.getUsername());
if (mapper.updateProduct(product) != 1) throw stale();
@ -122,6 +130,7 @@ public class BomService {
}
ProductionProduct existing = mapper.selectProduct(request.getId());
if (existing == null) throw new ServiceException("产品不存在");
BomDataAccess.require(existing);
request.setItemId(existing.getItemId()); checkText(request.getRemark(), 500, "产品说明");
request.setUpdateBy(SecurityUtils.getUsername()); if (mapper.updateProduct(request) != 1) throw stale();
return mapper.selectProduct(request.getId());
@ -129,6 +138,7 @@ public class BomService {
@Transactional public void deleteProduct(Long id) {
lockGraph(); ProductionProduct product = mapper.selectProduct(id);
if (product == null) throw new ServiceException("产品不存在");
BomDataAccess.require(product);
if (mapper.countProductReferences(product.getItemId()) > 0) throw new ServiceException("产品已被BOM或项目引用,不能删除");
mapper.deleteProduct(id);
}
@ -227,7 +237,7 @@ public class BomService {
private ProductionProduct ensureProduct(Long itemId) {
ProductionProduct existing = mapper.selectProductByItem(itemId);
if (existing != null) {
if (mapper.selectProduct(existing.getId()) == null) { mapper.restoreProduct(existing.getId()); return mapper.selectProduct(existing.getId()); }
if (mapper.selectProduct(existing.getId()) == null) { BomDataAccess.require(existing);mapper.restoreProduct(existing.getId()); return mapper.selectProduct(existing.getId()); }
return existing;
}
ProductionProduct product = new ProductionProduct(); product.setItemId(itemId); product.setCreateBy(SecurityUtils.getUsername());
@ -239,6 +249,7 @@ public class BomService {
checkText(bom.getVersionTag(), 64, "版本号"); checkText(bom.getDescription(), 500, "版本说明");
bom.setIsDefault(Boolean.TRUE.equals(bom.getIsDefault()));
}
private void requireDefaultChange(Long itemId,Long exceptId){var current=mapper.selectDefault(itemId);if(current!=null&&!Objects.equals(current.getId(),exceptId))BomDataAccess.require(current);}
private void checkText(String value, int length, String label) { if (value != null && value.length() > length) throw new ServiceException(label + "长度超过" + length + "字"); }
private BomVersion requireVersion(Long id) { BomVersion bom = id == null ? null : mapper.selectVersion(id); if (bom == null) throw new ServiceException("BOM不存在或已删除"); return bom; }
private void lockGraph() { if (mapper.lockGraph() == null) throw new ServiceException("BOM数据结构未初始化"); }

View File

@ -68,7 +68,7 @@ public class ProductAttachmentService {
try{byte[] bytes=storage.read("product/"+id+".bin",null,MAX_BYTES);if(bytes.length!=((Number)meta.get("byte_size")).intValue()||!hash(bytes).equals(meta.get("sha256")))throw new ServiceException("附件完整性校验失败,请联系产品负责人核对");String type=meta.get("content_type").toString();return new Content(bytes,meta.get("original_name").toString(),type,Set.of("application/pdf","image/png","image/jpeg").contains(type));}
catch(ServiceException error){throw error;}catch(Exception error){throw new ServiceException("附件读取失败,请稍候重试");}}
private Map<String,Object> describe(Long product,String id){return db.queryForMap("select id,original_name name,content_type contentType,byte_size size,create_by uploadedBy,create_time uploadedAt from production_product_attachment where product_id=? and id=? and deleted=0",product,id);}
private void authorize(Long product,boolean write){ProductVersionService.requirePermission(write);products.requireProduct(product);}
private void authorize(Long product,boolean write){ProductVersionService.requirePermission(write);if(write)products.requireProductWrite(product);else products.requireProduct(product);}
private void requireStorage(){if(!storage.isEnabled())throw new ServiceException("产品附件需要启用本环境的MinIO存储,请联系管理员配置");}
static void requireId(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 new ServiceException("附件编号无效");}
static String safeName(String original){String name=Objects.toString(original,"").replace('\\','/');name=name.substring(name.lastIndexOf('/')+1).replaceAll("[\\p{Cntrl}]","").trim();if(name.isEmpty()||name.length()>180||name.lastIndexOf('.')<=0||name.endsWith("."))throw new ServiceException("附件名称无效或超过180个字符");return name;}

View File

@ -8,6 +8,7 @@ import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.production.domain.*;
import com.ruoyi.production.mapper.BomMapper;
import com.ruoyi.production.util.BomDataAccess;
import com.ruoyi.warehouse.domain.ProductInfo;
import com.ruoyi.warehouse.mapper.ProductInfoMapper;
import com.ruoyi.warehouse.service.IProductInfoService;
@ -32,22 +33,23 @@ public class ProductVersionService {
Long copyBomId,Integer copyBomVersion,String bomTag,String remark,String submissionKey){}
public static void requirePermission(boolean write){
if(SecurityUtils.isAdmin()||SecurityUtils.hasPermi("production:product:edit")||!write&&SecurityUtils.hasPermi("production:product:list"))return;
if(BomDataAccess.managesAll()||SecurityUtils.hasPermi("production:product:edit")||!write&&SecurityUtils.hasPermi("production:product:list"))return;
throw new ServiceException(write?"产品版本和资料可请产品负责人协助维护,或联系管理员开通相应功能":"产品资料暂未向当前账号开放,可联系产品负责人协助查看",403);
}
public ProductionProduct requireProduct(Long id){var product=id==null?null:mapper.selectProduct(id);if(product==null)throw new ServiceException("产品不存在或已移除,请刷新后重试");return product;}
public Integer sourceBomVersion(Long productId,Long bomId){requirePermission(true);var product=requireProduct(productId);var bom=boms.get(bomId);if(!Objects.equals(product.getItemId(),bom.getItemId())||!"PUBLIC".equals(bom.getScopeType()))throw new ServiceException("请选择来源产品的公共BOM");return bom.getVersion();}
public ProductionProduct requireProduct(Long id){var product=id==null?null:mapper.selectProduct(id);if(product==null)throw new ServiceException("产品不存在或已移除,请刷新后重试");product.setEditable(BomDataAccess.canEdit(product));return product;}
public ProductionProduct requireProductWrite(Long id){requirePermission(true);var product=requireProduct(id);BomDataAccess.require(product);return product;}
public Integer sourceBomVersion(Long productId,Long bomId){var product=requireProductWrite(productId);var bom=boms.get(bomId);if(!Objects.equals(product.getItemId(),bom.getItemId())||!"PUBLIC".equals(bom.getScopeType()))throw new ServiceException("请选择来源产品的公共BOM");return bom.getVersion();}
public List<ProductionProduct> versions(Long id){requirePermission(false);var product=requireProduct(id);if(product.getSeriesId()==null)return List.of(product);
return db.queryForList("select product_id from production_product_edition e join production_product p on p.id=e.product_id where e.series_id=? and p.del_flag='0' order by p.id desc",product.getSeriesId()).stream().map(row->requireProduct(((Number)row.get("product_id")).longValue())).toList();}
/** Read-only plan used by the assistant confirmation card. No metadata, catalog or BOM is created. */
@Transactional(readOnly=true) public Map<String,Object> preview(Create request){
requirePermission(true);if(request==null)throw new ServiceException("请填写产品版本");var source=requireProduct(request.sourceProductId());
requirePermission(true);if(request==null)throw new ServiceException("请填写产品版本");var source=requireProductWrite(request.sourceProductId());
String tag=text(request.editionTag(),64,"新产品版本");String seriesName=source.getSeriesId()==null?text(request.seriesName(),160,"产品系列"):source.getSeriesName();
if(source.getSeriesId()==null){String original=text(request.originalEditionTag(),64,"原产品版本");if(original.equalsIgnoreCase(tag))throw new ServiceException("新旧版本名称不能相同");}else uniqueTag(source.getSeriesId(),tag,null);
var plan=new LinkedHashMap<String,Object>();plan.put("source",source);plan.put("seriesName",seriesName);plan.put("editionTag",tag);plan.put("cloneItem",Boolean.TRUE.equals(request.cloneItem()));
if(Boolean.TRUE.equals(request.cloneItem())){
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:product:add"))throw new ServiceException("新建物品档案可请物品负责人协助,或选择已建好的独立物品",403);
if(!BomDataAccess.managesAll()&&!SecurityUtils.hasPermi("warehouse:product:add"))throw new ServiceException("新建物品档案可请物品负责人协助,或选择已建好的独立物品",403);
var original=items.selectProductInfoById(source.getItemId());if(original==null)throw new ServiceException("来源物品不存在");var target=new ProductInfo();target.setProductName(text(request.itemName(),100,"新物品名称"));target.setSpec(text(request.itemSpec(),500,"新物品规格"));target.setBrand(original.getBrand());target.setCategory(original.getCategory());target.setUnit(original.getUnit());if(items.checkProductInfoUnique(target)!=null)throw new ServiceException("已存在同名、品牌、类别及规格的物品,请选择现有独立物品,或调整新版本规格");plan.put("targetItem",target);
}else {var target=request.itemId()==null?null:items.selectProductInfoById(request.itemId());if(target==null)throw new ServiceException("请选择新版本对应的独立物品");if(Objects.equals(source.getItemId(),target.getId())||mapper.selectProductByItem(target.getId())!=null)throw new ServiceException("新版本不能复用已有产品版本的物品档案");plan.put("targetItem",target);}
if(request.copyBomId()!=null){if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("production:bom:edit"))throw new ServiceException("复制BOM可请有BOM维护权限的同事协助",403);var bom=boms.get(request.copyBomId());if(!"PUBLIC".equals(bom.getScopeType())||!Objects.equals(bom.getItemId(),source.getItemId()))throw new ServiceException("请选择来源产品的公共BOM");text(request.bomTag(),64,"新BOM版本");plan.put("sourceBom",bom);}
@ -58,6 +60,7 @@ public class ProductVersionService {
@Transactional public ProductionProduct save(ProductionProduct request){
requirePermission(true);lock();if(request==null)throw new ServiceException("请选择产品物品");
ProductionProduct existing=request.getId()==null?null:requireProduct(request.getId());
if(existing!=null)BomDataAccess.require(existing);
boolean metadata=request.getSeriesName()!=null||request.getEditionTag()!=null;
if(metadata&&existing==null&&mapper.selectProductByItem(request.getItemId())!=null)throw new ServiceException("此物品已经是产品,请修改原产品,或为新版本选择独立物品档案");
var saved=boms.saveProduct(request);
@ -65,6 +68,7 @@ public class ProductVersionService {
if(existing==null||existing.getSeriesId()==null){long series=newSeries(seriesName);insertEdition(saved.getId(),series,tag,null,null);}
else {
if(!Objects.equals(request.getSeriesVersion(),existing.getSeriesVersion()))throw stale();
if(!seriesName.equals(existing.getSeriesName()))BomDataAccess.require(db.queryForObject("select create_by from production_product_series where id=?",String.class,existing.getSeriesId()));
if(!seriesName.equals(existing.getSeriesName())&&db.update("update production_product_series set series_name=?,version=version+1,update_by=?,update_time=current_timestamp where id=? and version=?",seriesName,SecurityUtils.getUsername(),existing.getSeriesId(),request.getSeriesVersion())!=1)throw stale();
uniqueTag(existing.getSeriesId(),tag,existing.getId());db.update("update production_product_edition set edition_tag=?,update_by=?,update_time=current_timestamp where product_id=?",tag,SecurityUtils.getUsername(),saved.getId());
}
@ -74,7 +78,8 @@ public class ProductVersionService {
@Transactional public ProductionProduct create(Create request){
requirePermission(true);if(request==null)throw new ServiceException("请填写产品版本");
if(Boolean.TRUE.equals(request.cloneItem())&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:product:add"))throw new ServiceException("新建物品档案可请物品负责人协助;也可选择已经建好的独立物品",403);
requireProductWrite(request.sourceProductId());
if(Boolean.TRUE.equals(request.cloneItem())&&!BomDataAccess.managesAll()&&!SecurityUtils.hasPermi("warehouse:product:add"))throw new ServiceException("新建物品档案可请物品负责人协助;也可选择已经建好的独立物品",403);
if(request.copyBomId()!=null&&!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("production:bom:edit"))throw new ServiceException("复制BOM可请有BOM维护权限的同事协助,或先创建不带BOM的产品版本",403);
if(request.submissionKey()==null||!request.submissionKey().matches("[A-Za-z0-9_-]{8,75}"))throw new ServiceException("版本提交标识无效,请重新打开新增窗口");
String tag=text(request.editionTag(),64,"新产品版本");String hash=hash(encode(request));

View File

@ -0,0 +1,16 @@
package com.ruoyi.production.util;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BomPermissions;
import com.ruoyi.common.utils.SecurityUtils;
/** Record ownership is enforced independently of menu permissions, including assistant and attachment writes. */
public final class BomDataAccess {
private BomDataAccess(){}
public static boolean managesAll(){try{return SecurityUtils.isAdmin()||BomPermissions.isManager(SecurityUtils.getLoginUser());}catch(ServiceException unauthenticated){return false;}}
public static boolean canEdit(String creator){try{return managesAll()||creator!=null&&!creator.isBlank()&&creator.equals(SecurityUtils.getUsername());}catch(ServiceException unauthenticated){return false;}}
public static boolean canEdit(BaseEntity record){return record!=null&&canEdit(record.getCreateBy());}
public static void require(BaseEntity record){require(record==null?null:record.getCreateBy());}
public static void require(String creator){if(!canEdit(creator))throw new ServiceException("仅创建人、BOM管理员或超级管理员可以维护此数据",403);}
}

View File

@ -23,6 +23,7 @@ import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.PurchasePermissions;
import com.ruoyi.common.utils.BomPermissions;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.MetaVo;
import com.ruoyi.system.domain.vo.RouterVo;
@ -150,14 +151,17 @@ public class SysMenuServiceImpl implements ISysMenuService
menus = new java.util.ArrayList<>(menuMapper.selectMenuTreeByUserId(userId));
var user = new SysUser();
user.setRoles(roleMapper.selectRolePermissionByUserId(userId));
if (PurchasePermissions.isManager(user))
Set<String> managedPermissions=new java.util.HashSet<>();
if(PurchasePermissions.isManager(user))managedPermissions.addAll(PurchasePermissions.ACTIONS);
if(BomPermissions.isManager(user))managedPermissions.addAll(BomPermissions.ACTIONS);
if (!managedPermissions.isEmpty())
{
// Include procurement pages and their directories, without granting sibling modules.
// Include only managed module pages and their directories, never unrelated siblings.
var all = menuMapper.selectMenuTreeAll();
Set<Long> selected = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toSet());
for (var menu : all)
if (Arrays.stream(StringUtils.defaultString(menu.getPerms()).split(","))
.anyMatch(perm -> PurchasePermissions.ACTIONS.contains(perm.trim())))
.anyMatch(perm -> managedPermissions.contains(perm.trim())))
selected.add(menu.getMenuId());
boolean changed;
do {

View File

@ -8,7 +8,9 @@ import com.ruoyi.warehouse.domain.PurchaseArrivalRevokeRequest;
public interface IPurchaseArrivalService
{
List<PurchaseArrival> selectPurchaseArrivalList(Long purchaseRequestId);
PurchaseArrival findSubmittedArrival(Long requestId,String requestKey);
int insertPurchaseArrival(PurchaseArrival arrival);
int prepareArrivalForReceipt(Long id);
int importAcceptedArrival(PurchaseArrival arrival);
int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest request);
int revokePurchaseArrivalAcceptance(Long id, PurchaseArrivalRevokeRequest request);

View File

@ -0,0 +1,54 @@
package com.ruoyi.warehouse.service.impl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.service.impl.FeedbackImageStorage;
import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
/** Arrival evidence is identified by its decoded contents, never the supplied extension or MIME. */
final class ArrivalPhotoImages {
record Prepared(byte[] bytes,String type,String extension) { }
static Prepared prepare(byte[] bytes) {return prepare(bytes,PurchaseArrivalPhotoService.MAX_BYTES);}
static Prepared prepare(byte[] bytes,int maximum) {
if(bytes.length==0||bytes.length>maximum)throw new ServiceException("每张照片不能超过"+(maximum/1024/1024)+"MB");
// The existing bounded WebP validator also supports containers unavailable to the JDK decoder.
if(bytes.length>=12&&ascii(bytes,0,4).equals("RIFF")&&ascii(bytes,8,4).equals("WEBP"))
return new Prepared(bytes,FeedbackImageStorage.validateContent(bytes,"webp"),"webp");
BufferedImage decoded=null;
try(var input=new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))){
var readers=ImageIO.getImageReaders(input);
if(!readers.hasNext())throw new ServiceException("无法识别这张图片,请重新选择;苹果HEIC原图可在网页上传时自动转换");
var reader=readers.next();
try{
String format=reader.getFormatName().toLowerCase(Locale.ROOT);
if(!Set.of("jpeg","png","gif","bmp","tiff","tif").contains(format))throw new ServiceException("暂不支持此图片格式");
reader.setInput(input,true,true);long width=reader.getWidth(0),height=reader.getHeight(0);
if(width<=0||height<=0||width*height>40_000_000)throw new ServiceException("图片最大支持4000万像素");
if(format.equals("jpeg")||format.equals("png")){
// Retain the original evidence bytes, including orientation metadata.
String extension=format.equals("jpeg")?"jpg":"png";
return new Prepared(bytes,FeedbackImageStorage.validateContent(bytes,extension),extension);
}
boolean[] warning={false};reader.addIIOReadWarningListener((source,message)->warning[0]=true);
decoded=reader.read(0);
if(decoded==null||warning[0]||decoded.getWidth()!=width||decoded.getHeight()!=height)throw new ServiceException("图片无法解码或已损坏,请重新选择");
// First frame/page of GIF, BMP and TIFF becomes a portable still photograph.
var output=new ByteArrayOutputStream();
if(!ImageIO.write(decoded,"png",output)||output.size()>maximum)throw new ServiceException("图片转换后超过"+(maximum/1024/1024)+"MB,请缩小后上传");
return new Prepared(output.toByteArray(),"image/png","png");
}finally{reader.dispose();}
}catch(ServiceException e){throw e;}catch(Exception e){throw new ServiceException("图片无法解码或已损坏,请重新选择");}
finally{if(decoded!=null)decoded.flush();}
}
static String name(String original,String extension){
String input=original==null||original.isBlank()?"到货照片.image":original;
String safe=PurchaseDocumentService.safeName(input.contains(".")?input:input+".image");
if(safe.toLowerCase(Locale.ROOT).endsWith("."+extension)||extension.equals("jpg")&&safe.toLowerCase(Locale.ROOT).endsWith(".jpeg"))return safe;
String base=safe.substring(0,safe.lastIndexOf('.'));
return base.substring(0,Math.min(base.length(),179-extension.length()))+"."+extension;
}
private static String ascii(byte[] bytes,int offset,int length){return new String(bytes,offset,length,java.nio.charset.StandardCharsets.US_ASCII);}
}

View File

@ -38,6 +38,12 @@ public class BusinessNumberService {
public String next(String kind,LocalDate date){return allocate(Kind.find(kind),date,null);}
@Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public String reserve(String kind,LocalDate date,String requestKey){return allocate(Kind.find(kind),date,requestKey);}
/** Read-only lookup: checking a submission must never allocate another business number. */
public String lookup(String kind,String requestKey){
if(requestKey==null||requestKey.isBlank()||requestKey.length()>500)throw new ServiceException("编号防重复标识无效");
try{return reserved(Kind.find(kind).prefix,HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(requestKey.getBytes(StandardCharsets.UTF_8))));}
catch(java.security.NoSuchAlgorithmException error){throw new IllegalStateException(error);}
}
private String allocate(Kind kind,LocalDate date,String requestKey){
date=date==null?LocalDate.now():date;
if(date.getYear()<1||date.getYear()>9999)throw new ServiceException("业务日期年份须为四位");

View File

@ -32,8 +32,8 @@ import com.ruoyi.common.exception.ServiceException;
List<Object> args=Arrays.asList(projectId,projectId);
String groupBase=base.replace("(? is null or pr.project_id=?)","(? is null or pr.project_id=? and pr.purchase_batch_id is null or exists(select 1 from purchase_request member where member.purchase_batch_id=pr.purchase_batch_id and member.project_id=? and member.del_flag=\'0\'))");
List<Object> groupArgs=Arrays.asList(projectId,projectId,projectId);
String grouped="select coalesce(cast(pr.purchase_batch_id as char),concat('unbatched-',min(pr.project_id),'-',coalesce(min(b.supplier_id),0))) id,'purchase' source,pr.purchase_batch_id purchaseBatchId,max(pr.purchase_batch_no) purchaseBatchNo,case when count(distinct pr.project_id)=1 then min(pr.project_id) else null end projectId,group_concat(distinct p.project_name separator '、') project,coalesce(max(b.batch_name),max(pr.purchase_batch_no),'未分批采购') item,coalesce(max(pr.purchase_batch_no),'未分批采购') record,coalesce(max(s.name),'—') supplier,concat(count(*),' 项明细') quantityText,substring_index(group_concat(distinct pr.material_name separator '、'),'、',2) detail,min(pr.create_time) date,sum(case when pr.price_locked=0 and pr.final_unit_price is null then 1 else 0 end) unpriced,sum(case when pr.price_locked=0 then 1 else 0 end) unlocked,sum(case when pr.price_locked=1 and b.supplier_id is not null and coalesce(a.pending,0)>0 then 1 else 0 end) pending,sum(case when pr.price_locked=1 and b.supplier_id is not null and pr.quantity>coalesce(a.arrived,0) then 1 else 0 end) remaining"+groupBase+" group by pr.purchase_batch_id,case when pr.purchase_batch_id is null then pr.project_id end,case when pr.purchase_batch_id is null then b.supplier_id end";
if(home("todo"))for(var def:List.of(new String[]{"quote","待补报价","录入报价","unpriced>0"},new String[]{"confirm","待确认采购","确认采购","unpriced=0 and unlocked>0"},new String[]{"acceptance","待验收","去验收","pending>0"},new String[]{"arrival","未到齐","查看到货","remaining>0"})){var q=queue(def[0],def[1],def[2],grouped+" having "+def[3]+" order by date",groupArgs);for(var r:(List<Map<String,Object>>)q.get("rows"))r.put("progress",r.get("unpriced")+" 项待报价 · "+r.get("pending")+" 项待验收 · "+r.get("remaining")+" 项未到齐");queues.add(q);}
String grouped="select coalesce(cast(pr.purchase_batch_id as char),concat('unbatched-',min(pr.project_id),'-',coalesce(min(b.supplier_id),0))) id,'purchase' source,pr.purchase_batch_id purchaseBatchId,max(pr.purchase_batch_no) purchaseBatchNo,case when count(distinct pr.project_id)=1 then min(pr.project_id) else null end projectId,group_concat(distinct p.project_name separator '、') project,coalesce(max(b.batch_name),max(pr.purchase_batch_no),'未分批采购') item,coalesce(max(pr.purchase_batch_no),'未分批采购') record,coalesce(max(s.name),'—') supplier,concat(count(*),' 项明细') quantityText,substring_index(group_concat(distinct pr.material_name separator '、'),'、',2) detail,min(pr.create_time) date,sum(case when pr.price_locked=0 and pr.final_unit_price is null then 1 else 0 end) unpriced,sum(case when pr.price_locked=0 then 1 else 0 end) unlocked,sum(case when b.supplier_id is not null and coalesce(a.pending,0)>0 then 1 else 0 end) pending,sum(case when b.supplier_id is not null and pr.quantity>coalesce(a.arrived,0) then 1 else 0 end) remaining"+groupBase+" group by pr.purchase_batch_id,case when pr.purchase_batch_id is null then pr.project_id end,case when pr.purchase_batch_id is null then b.supplier_id end";
if(home("todo"))for(var def:List.of(new String[]{"quote","待补报价","录入报价","unpriced>0"},new String[]{"confirm","待确认采购","确认采购","unpriced=0 and unlocked>0"},new String[]{"acceptance","历史待衔接","查看到货","pending>0"},new String[]{"arrival","未到齐","查看到货","remaining>0"})){var q=queue(def[0],def[1],def[2],grouped+" having "+def[3]+" order by date",groupArgs);for(var r:(List<Map<String,Object>>)q.get("rows"))r.put("progress",r.get("unpriced")+" 项待报价 · "+r.get("pending")+" 项历史待衔接 · "+r.get("remaining")+" 项未到齐");queues.add(q);}
if(home("project"))overview.putAll(db.queryForMap("select count(*) purchaseCount,count(distinct pr.purchase_batch_id) batchCount,coalesce(sum(case when pr.purchase_batch_id is null then 1 else 0 end),0) unbatchedCount"+base+" and (pr.price_locked=0 or coalesce(a.pending,0)>0 or pr.quantity>coalesce(a.arrived,0))",args.toArray()));
}
if((home("warehouse")||home("todo"))&&can("warehouse:in:list")){

View File

@ -131,7 +131,7 @@ public class InRecordServiceImpl implements IInRecordService
}
if (dbRecord != null && (dbRecord.getArrivalId() != null || dbRecord.getParentInId()!=null || dbRecord.getCostEventId()!=null || dbRecord.getProductionTaskId()!=null))
{
throw new ServiceException("采购验收生成的待入库记录不能删除");
throw new ServiceException("采购到货生成的待入库记录不能删除");
}
}
return inRecordMapper.deleteInRecordByIds(ids);
@ -158,9 +158,8 @@ public class InRecordServiceImpl implements IInRecordService
{
com.ruoyi.warehouse.domain.PurchaseRequest purchase = purchaseRequestMapper
.selectPurchaseRequestByIdForUpdate(inRecord.getPurchaseRequestId());
if (purchase == null || !Boolean.TRUE.equals(purchase.getPriceLocked())
|| purchase.getFinalUnitPrice() == null || Integer.valueOf(5).equals(purchase.getPurchaseStatus()))
throw new ServiceException("请先填写最终价格并锁价,再确认采购入库");
if (purchase == null || Integer.valueOf(5).equals(purchase.getPurchaseStatus()))
throw new ServiceException("采购明细不存在或已取消,不能入库");
if (purchase.getProductId()!=null && !java.util.Objects.equals(purchase.getProductId(),inRecord.getProductId()))
throw new ServiceException("入库物品与采购明细不一致,请刷新后重试");
inRecord.setSourceProjectId("REPAY".equals(purchase.getPurchasePurpose())
@ -214,7 +213,7 @@ public class InRecordServiceImpl implements IInRecordService
String no="RIN-"+java.util.UUID.nameUUIDFromBytes(key.getBytes(java.nio.charset.StandardCharsets.UTF_8));
InRecord root=lockRecordAfterPurchase(id),duplicate=inRecordMapper.checkInNoUnique(no);
if(duplicate==null){no=businessNumbers.reserve("IN",date,"receipt:"+key);duplicate=inRecordMapper.checkInNoUnique(no);}
if (!Boolean.TRUE.equals(root.getReceiptRoot())) throw new ServiceException("分次入库请选择采购或完工验收生成的待入库记录");
if (!Boolean.TRUE.equals(root.getReceiptRoot())) throw new ServiceException("分次入库请选择采购到货或生产完工生成的待入库记录");
if (duplicate!=null) {
String expectedRemark=remark==null?root.getRemark():remark;
if (!java.util.Objects.equals(duplicate.getParentInId(),id) || !java.util.Objects.equals(duplicate.getAreaId(),areaId) || quantity==null || duplicate.getInNum().compareTo(quantity)!=0 || !Integer.valueOf(1).equals(duplicate.getInStatus())

View File

@ -4,10 +4,8 @@ import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.storage.BusinessFileStorage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.impl.FeedbackImageStorage;
import com.ruoyi.warehouse.domain.PurchaseArrival;
import com.ruoyi.warehouse.domain.PurchaseArrivalPhoto;
import com.ruoyi.warehouse.util.WarehouseFileUtils;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
@ -58,11 +56,13 @@ public class PurchaseArrivalPhotoService {
return photo(db.queryForMap("select * from purchase_arrival_photo where id=?",id));
}
private PurchaseArrivalPhoto stage(Long requestId,String id,MultipartFile file){
String extension=WarehouseFileUtils.validateUpload(file,MAX_BYTES,Set.of("jpg","jpeg","png","webp"));
if(file==null||file.isEmpty())throw new ServiceException("请选择要上传的照片");
if(file.getSize()>MAX_BYTES)throw new ServiceException("每张照片不能超过20MB");
byte[] bytes;
try(var input=file.getInputStream()){bytes=input.readNBytes(MAX_BYTES+1);}catch(IOException e){throw new ServiceException("照片读取失败,请重新选择");}
if(bytes.length==0||bytes.length>MAX_BYTES)throw new ServiceException("每张照片不能超过20MB");
String type=FeedbackImageStorage.validateContent(bytes,extension),name=PurchaseDocumentService.safeName(file.getOriginalFilename()),sha=digest(bytes);
var prepared=ArrivalPhotoImages.prepare(bytes);bytes=prepared.bytes();
String type=prepared.type(),name=ArrivalPhotoImages.name(file.getOriginalFilename(),prepared.extension()),sha=digest(bytes);
var existing=db.queryForList("select * from purchase_arrival_photo where id=?",id);
if(!existing.isEmpty()){
var old=existing.get(0);
@ -143,7 +143,7 @@ public class PurchaseArrivalPhotoService {
if(rows.isEmpty())throw new ServiceException("采购明细不存在",404);
var r=rows.get(0);
if(lock&&!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)r.get("create_by"),(String)r.get("batch_create_by")))throw new ServiceException("仅明细创建人、批次创建人、采购管理员或超级管理员可以维护到货照片",403);
if(!supplemental&&(!truth(r.get("price_locked"))||truth(r.get("historical"))||number(r,"purchase_status")==5))throw new ServiceException("请先确认采购,历史或已取消采购不能登记到货照片");
if(!supplemental&&(truth(r.get("historical"))||number(r,"purchase_status")==5))throw new ServiceException("历史或已取消采购不能登记到货照片");
}
private static boolean truth(Object value){return Boolean.TRUE.equals(value)||value instanceof Number n&&n.intValue()!=0;}
private static void validId(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 new ServiceException("照片标识无效");}

View File

@ -59,6 +59,19 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
return rows;
}
@Override
@Transactional
public PurchaseArrival findSubmittedArrival(Long requestId,String requestKey) {
if(requestKey==null||requestKey.isBlank()||requestKey.length()>120)throw new ServiceException("到货业务标识无效");
// Serialize with registration. A negative result must not race an already-running save.
journal.lockInventory();
var request=purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(requestId);
com.ruoyi.warehouse.util.PurchaseDataAccess.require(request);
String legacy="ARR-"+java.util.UUID.nameUUIDFromBytes(requestKey.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String reserved=businessNumbers.lookup("PA",requestKey);
return selectPurchaseArrivalList(requestId).stream().filter(row->legacy.equals(row.getArrivalNo())||row.getArrivalNo().equals(reserved)).findFirst().orElse(null);
}
@Override
@Transactional
public int insertPurchaseArrival(PurchaseArrival arrival) { return insertArrival(arrival,false); }
@ -108,7 +121,6 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
throw new ServiceException("已取消的采购申请不能登记到货");
}
if(!historicalImport&&PurchaseArrivalPhotoService.ids(arrival.getPhotoIds()).isEmpty())throw new ServiceException("登记到货至少需要1张照片,请先上传到货照片");
if ((!historicalImport&&!Boolean.TRUE.equals(request.getPriceLocked())) || request.getFinalUnitPrice()==null) throw new ServiceException("请先确认采购并锁定报价,再登记到货");
if(request.getPurchaseBatchId()==null || database.queryForObject("select count(*) from purchase_batch where id=? and del_flag='0' and supplier_id is not null",Long.class,request.getPurchaseBatchId())==0) throw new ServiceException("请先选择有效供应商并确认未删除的采购批次");
if (arrival.getArrivalQuantity() == null || arrival.getArrivalQuantity().signum() <= 0 || arrival.getArrivalQuantity().stripTrailingZeros().scale()>4)
{
@ -118,8 +130,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
{
throw new ServiceException("到货日期不能为空");
}
BigDecimal unitPrice = request.getFinalUnitPrice() != null
? request.getFinalUnitPrice() : request.getEstimatedUnitPrice();
BigDecimal unitPrice = request.getFinalUnitPrice();
arrival.setActualUnitPrice(unitPrice);
arrival.setActualAmount(unitPrice == null ? null
: arrival.getArrivalQuantity().multiply(unitPrice).setScale(6, RoundingMode.HALF_UP));
@ -137,13 +148,47 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
purchaseOperationLogService.record(request.getId(), request.getRequestNo(), "ARRIVAL_REGISTER",
"登记到货", "到货单:" + arrival.getArrivalNo()
+ ";数量:" + decimalText(arrival.getArrivalQuantity()) + unitText(request.getUnit())
+ ";实际金额:¥" + (arrival.getActualAmount() == null ? "未锁价" : arrival.getActualAmount().toPlainString()));
+ ";实际金额:¥" + (arrival.getActualAmount() == null ? "待补价" : arrival.getActualAmount().toPlainString()));
if(!historicalImport)readyForReceipt(arrival,request);
return rows;
}
/** Physical receipt readiness is separate from the batch's online acceptance documents. */
@Override @Transactional
public int prepareArrivalForReceipt(Long id) {
journal.lockInventory();
var arrival=purchaseArrivalMapper.selectPurchaseArrivalByIdForUpdate(id);
if(arrival==null)throw new ServiceException("到货记录不存在");
var request=purchaseRequestMapper.selectPurchaseRequestByIdForUpdate(arrival.getPurchaseRequestId());
com.ruoyi.warehouse.util.PurchaseDataAccess.require(request);
if(Integer.valueOf(1).equals(arrival.getAcceptanceStatus()))return 1;
if(!Integer.valueOf(0).equals(arrival.getAcceptanceStatus())||Integer.valueOf(5).equals(request.getPurchaseStatus()))throw new ServiceException("该到货记录当前不能转待入库");
if(arrivalPhotos!=null)arrivalPhotos.attach(java.util.List.of(arrival));
if(arrival.getPhotos()==null||arrival.getPhotos().isEmpty())throw new ServiceException("请先补传至少1张到货照片");
readyForReceipt(arrival,request);return 1;
}
private void readyForReceipt(PurchaseArrival arrival,PurchaseRequest request) {
// Reuse the legacy availability state without inventing a human acceptance/sign-off.
arrival.setAcceptanceStatus(1);arrival.setDefectiveQuantity(BigDecimal.ZERO);
arrival.setAcceptedBy(null);arrival.setAcceptedTime(null);arrival.setPreAcceptPurchaseStatus(request.getPurchaseStatus());
arrival.setAcceptanceRemark("登记到货转待入库(无需线下验收)");arrival.setUpdateBy(SecurityUtils.getUsername());
if(purchaseArrivalMapper.updatePurchaseArrivalAcceptance(arrival)!=1)throw new ServiceException("到货状态已变化,请刷新核对");
arrival.setProductId(request.getProductId());arrival.setProjectId(request.getProjectId());arrival.setExpenseCategoryId(request.getExpenseCategoryId());arrival.setRequestNo(request.getRequestNo());
createPendingInRecord(arrival,SecurityUtils.getUsername());
var arrived=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(request.getId());
purchaseRequestMapper.updatePurchaseStatus(request.getId(),arrived.compareTo(request.getQuantity())>=0?4:3,request.getProgressRemark(),SecurityUtils.getUsername());
purchaseOperationLogService.record(request.getId(),request.getRequestNo(),"ARRIVAL_READY","到货转待入库","到货单:"+arrival.getArrivalNo()+";数量:"+decimalText(arrival.getArrivalQuantity())+";未报价也可办理入库,线上验收资料另行维护");
}
@Override
@Transactional
public int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest acceptance) { return acceptArrival(id,acceptance,false); }
public int acceptPurchaseArrival(Long id, PurchaseArrivalAcceptanceRequest acceptance) {
// Older clients may submit this after registration. No new physical acceptance is created.
if(acceptance==null||!Integer.valueOf(1).equals(acceptance.getAcceptanceStatus())
||acceptance.getDefectiveQuantity()!=null&&acceptance.getDefectiveQuantity().signum()!=0)
throw new ServiceException("已取消线下验收;异常到货请使用退货流程");
return prepareArrivalForReceipt(id);
}
private int acceptArrival(Long id,PurchaseArrivalAcceptanceRequest acceptance,boolean historicalImport)
{
journal.lockInventory();
@ -216,6 +261,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
{
throw new ServiceException("到货记录不存在");
}
if (arrival.getAcceptedBy()==null)throw new ServiceException("该记录无需线下验收;请使用入库撤销或退货流程");
if (Integer.valueOf(0).equals(arrival.getAcceptanceStatus()))
{
throw new ServiceException("该到货记录尚未验收,无需撤销");
@ -336,7 +382,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
inRecord.setInStatus(0);
inRecord.setOperator(username);
inRecord.setInOperator(null);
inRecord.setRemark("采购到货验收:" + arrival.getRequestNo());
inRecord.setRemark("采购到货:" + arrival.getRequestNo());
inRecordMapper.insertInRecord(inRecord);
}

View File

@ -23,12 +23,13 @@ import java.util.zip.ZipInputStream;
/** Optional, private purchasing records. Never changes purchase/arrival/payment status. */
@Service
public class PurchaseDocumentService {
static final int MAX_BYTES = 10 * 1024 * 1024, MAX_FILES = 10;
public static final int MAX_BYTES = 50 * 1024 * 1024;
static final int MAX_FILES = 10;
static final Map<String, String> BATCH_KINDS = new LinkedHashMap<>();
static {
BATCH_KINDS.put("REQUEST", "采购申请");
BATCH_KINDS.put("CONTRACT", "合同"); BATCH_KINDS.put("ACCEPTANCE", "验收资料");
BATCH_KINDS.put("PAYMENT", "付款资料"); BATCH_KINDS.put("OTHER", "其他附件");
BATCH_KINDS.put("INVOICE", "验收发票"); BATCH_KINDS.put("PAYMENT", "付款资料"); BATCH_KINDS.put("OTHER", "其他附件");
}
static final Set<String> EXTENSIONS = Set.of("pdf", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx", "txt", "zip");
@Autowired private JdbcTemplate db;
@ -70,8 +71,9 @@ public class PurchaseDocumentService {
if (version == null || version < 0) throw new ServiceException("请刷新资料后重试");
String normalized = Objects.toString(number, "").trim();
if (normalized.length() > 100 || normalized.matches("(?s).*[\\p{Cntrl}].*")) throw new ServiceException("资料编号最多100个字符,不能含换行或控制字符");
if ("OTHER".equals(kind)) throw new ServiceException("其他附件不需要流程编号");
if (Set.of("OTHER","INVOICE").contains(kind)) throw new ServiceException("此类附件不需要流程编号");
requireTarget(type, targetId, true);
if("PAYMENT".equals(kind)&&!normalized.isBlank())requireInvoice(targetId);
long group = ensureGroup(type, targetId, kind);
if (db.update("update purchase_document_group set document_no=?,version=version+1,update_by=?,update_time=current_timestamp where id=? and version=?", normalized, SecurityUtils.getUsername(), group, version) != 1)
throw new ServiceException("资料编号已被其他人修改,请刷新后核对再保存");
@ -82,19 +84,25 @@ public class PurchaseDocumentService {
@Transactional public Attachment uploadGenerated(String type,Long targetId,String kind,String uploadId,MultipartFile file){return upload(type,targetId,kind,uploadId,file,true);}
private Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file,boolean generated) {
requirePermission(true); requireKind(type, kind); requireId(uploadId);
if (file == null || file.isEmpty() || file.getSize() > MAX_BYTES) throw new ServiceException("请上传不超过10 MB的附件");
if (file == null || file.isEmpty() || file.getSize() > MAX_BYTES) throw new ServiceException("请上传不超过50 MB的附件");
String name = safeName(file.getOriginalFilename());
String extension = name.substring(name.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);
if (!EXTENSIONS.contains(extension)) throw new ServiceException("支持 PDF、图片、Word、Excel、TXT、ZIP 文件");
if (!"OTHER".equals(kind) && !"pdf".equals(extension)) throw new ServiceException("此类流程资料请上传PDF文件,其他格式可放入其他附件");
if (!Set.of("OTHER","INVOICE").contains(kind) && !"pdf".equals(extension)) throw new ServiceException("此类流程资料请上传PDF文件,其他格式可放入其他附件");
if("INVOICE".equals(kind)&&!Set.of("pdf","png","jpg","jpeg").contains(extension))throw new ServiceException("发票支持PDF、JPG、PNG图片");
Path stored = null;
try {
byte[] input;
try (var stream = file.getInputStream()) { input = stream.readNBytes(MAX_BYTES + 1); }
if (input.length == 0 || input.length > MAX_BYTES) throw new ServiceException("附件为空或超过10 MB");
Validated valid = validate(input, extension);
if (input.length == 0 || input.length > MAX_BYTES) throw new ServiceException("附件为空或超过50 MB");
Validated valid;
if("INVOICE".equals(kind)){
if(input.length>=5&&new String(input,0,5,StandardCharsets.US_ASCII).equals("%PDF-")){valid=validate(input,"pdf");name=ArrivalPhotoImages.name(name,"pdf");}
else{var image=ArrivalPhotoImages.prepare(input,MAX_BYTES);valid=new Validated(image.bytes(),image.type());name=ArrivalPhotoImages.name(name,image.extension());}
}else valid=validate(input, extension);
String sha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(valid.bytes()));
requireTarget(type, targetId, true);
if("PAYMENT".equals(kind))requireInvoice(targetId);
long group = ensureGroup(type, targetId, kind);
var prior = db.queryForList("select group_id,owner_id,sha256,original_name,content_type,byte_size,deleted,server_generated from purchase_document_attachment where id=?", uploadId);
if (!prior.isEmpty()) {
@ -126,6 +134,8 @@ public class PurchaseDocumentService {
public void remove(String type, Long targetId, String id) {
requirePermission(true); requireId(id); requireTarget(type, targetId, true);
requireFileAccess(type,targetId,id);
if("batch".equals(type)&&!db.queryForList("select a.id from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=? and a.deleted=0 and g.target_type='batch' and g.target_id=? and g.document_kind='INVOICE'",id,targetId).isEmpty()
&&invoiceCount(targetId)<=1&&paymentExists(targetId))throw new ServiceException("已有付款资料,不能移除最后一份验收发票;请先补传发票或清理付款资料");
if(!db.queryForList("select id from purchase_acceptance_confirmation where attachment_id=? limit 1",id).isEmpty())
throw new ServiceException("该签章附件已用于验收确认,请保留原件;需要补充时请上传新版本");
if (db.update("update purchase_document_attachment a join purchase_document_group g on g.id=a.group_id set a.deleted=1,a.deleted_by=?,a.deleted_time=current_timestamp where a.id=? and a.deleted=0 and g.target_type=? and g.target_id=?", SecurityUtils.getUsername(), id, type, targetId) != 1)
@ -156,6 +166,10 @@ public class PurchaseDocumentService {
} catch (Exception e) { throw new ServiceException("附件不存在或已损坏,请重新上传"); }
}
private int invoiceCount(Long id){Integer count=db.queryForObject("select count(*) from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where g.target_type='batch' and g.target_id=? and g.document_kind='INVOICE' and a.deleted=0",Integer.class,id);return count==null?0:count;}
private void requireInvoice(Long id){if(invoiceCount(id)==0)throw new ServiceException("请先在验收资料中上传验收发票,再维护付款资料");}
private boolean paymentExists(Long id){Integer count=db.queryForObject("select count(*) from purchase_document_group g where g.target_type='batch' and g.target_id=? and g.document_kind='PAYMENT' and (g.document_no<>'' or exists(select 1 from purchase_document_attachment a where a.group_id=g.id and a.deleted=0))",Integer.class,id);return count!=null&&count>0;}
private long ensureGroup(String type, Long targetId, String kind) {
db.update("insert into purchase_document_group(target_type,target_id,document_kind,update_by) values(?,?,?,?) on duplicate key update id=id", type, targetId, kind, SecurityUtils.getUsername());
return db.queryForObject("select id from purchase_document_group where target_type=? and target_id=? and document_kind=?", Long.class, type, targetId, kind);

View File

@ -87,6 +87,8 @@ public class PurchasePriceCorrectionService {
for(var lot:snapshot.lots())db.update("update stock_lot set unit_cost=?,update_by=?,update_time=sysdate() where id=?",
input.finalUnitPrice(),SecurityUtils.getUsername(),number(lot,"id"));
db.update("update in_record set receipt_unit_cost=?,update_time=sysdate() where purchase_request_id=? and in_status in (0,1)",input.finalUnitPrice(),id);
db.update("update purchase_arrival set actual_unit_price=?,actual_amount=round(arrival_quantity*?,6),update_by=?,update_time=sysdate() where purchase_request_id=? and acceptance_status in (0,1)",
input.finalUnitPrice(),input.finalUnitPrice(),SecurityUtils.getUsername(),id);
if(db.update("update purchase_request set final_unit_price=?,estimated_unit_price=?,estimated_amount=?,update_by=?,update_time=sysdate() where id=? and del_flag='0'",
input.finalUnitPrice(),input.finalUnitPrice(),amount(old.getQuantity(),input.finalUnitPrice()),SecurityUtils.getUsername(),id)!=1)
throw new ServiceException("采购明细已变化,更正未完成");

View File

@ -149,7 +149,9 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
throw new ServiceException("已有到货记录,不能更换采购物料");
}
int confirmedInbound = purchaseRequestMapper.countConfirmedInbound(existing.getId());
if(activeArrivalQuantity.signum()>0 && (existing.getFinalUnitPrice()==null?purchaseRequest.getFinalUnitPrice()!=null:purchaseRequest.getFinalUnitPrice()==null||existing.getFinalUnitPrice().compareTo(purchaseRequest.getFinalUnitPrice())!=0))
boolean firstQuote=activeArrivalQuantity.signum()>0&&!Boolean.TRUE.equals(existing.getPriceLocked())&&existing.getFinalUnitPrice()==null&&purchaseRequest.getFinalUnitPrice()!=null
&&confirmedInbound==0;
if(activeArrivalQuantity.signum()>0 && !firstQuote && (existing.getFinalUnitPrice()==null?purchaseRequest.getFinalUnitPrice()!=null:purchaseRequest.getFinalUnitPrice()==null||existing.getFinalUnitPrice().compareTo(purchaseRequest.getFinalUnitPrice())!=0))
throw new ServiceException("已有到货记录,请使用‘更正价格’核对并同步关联金额;未到货的采购可直接编辑报价");
PurchasePriceRules.requireEditablePrice(confirmedInbound,
existing.getFinalUnitPrice(), purchaseRequest.getFinalUnitPrice());
@ -185,6 +187,8 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
{
throw new ServiceException("采购明细已变化,请刷新后重试");
}
if(firstQuote)taskDatabase.update("update purchase_arrival set actual_unit_price=?,actual_amount=round(arrival_quantity*?,6),update_by=?,update_time=sysdate() where purchase_request_id=? and acceptance_status in (0,1)",
purchaseRequest.getFinalUnitPrice(),purchaseRequest.getFinalUnitPrice(),SecurityUtils.getUsername(),existing.getId());
itemCategories.recordUsage("PURCHASE",purchaseRequest.getId(),purchaseRequest.getCategory());
if(!Integer.valueOf(5).equals(existing.getPurchaseStatus())&&existing.getQuantity().compareTo(purchaseRequest.getQuantity())!=0){
BigDecimal accepted=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(existing.getId());

View File

@ -88,9 +88,7 @@ public class PurchaseSheetService
return readSubmission(prior);
}
PurchaseSheet saved = saveOnce(sheet);
var keys=new LinkedHashMap<String,Long>();
for(var row:sheet.getRows())if(row.getClientRowKey()!=null&&row.getClientRowKey().matches("[A-Za-z0-9_-]{1,100}")&&row.getId()!=null)keys.put(row.getClientRowKey(),row.getId());
saved.setClientRowIds(keys);
saved.setClientRowIds(clientRowIds(sheet.getRows()));
try {
// Receipt and business changes commit/roll back together. Responses are
// server-loaded sheet snapshots, never the arbitrary request properties.
@ -513,6 +511,17 @@ public class PurchaseSheetService
private void lockBatch(Long id) {
if (jdbc.queryForList("select id from purchase_batch where id=? and del_flag='0' for update", id).isEmpty()) throw new ServiceException("采购批次不存在或已删除");
}
static Map<String,Long> clientRowIds(List<PurchaseRequest> rows) {
var result=new LinkedHashMap<String,Long>();
for(var row:rows) {
String key=row.getClientRowKey();
// Legacy browser drafts used Math.random() with a decimal point.
if(key==null||row.getId()==null)continue;
if(!key.matches("[A-Za-z0-9_.-]{1,100}")||result.putIfAbsent(key,row.getId())!=null)
throw new ServiceException("采购草稿行标识无效或重复,请保留草稿后核对");
}
return result;
}
private void requirePermission(String action) {
if (!SecurityUtils.isAdmin() && !SecurityUtils.hasPermi("warehouse:purchase:manage")
&& !SecurityUtils.hasPermi("warehouse:purchase:" + action)) throw new ServiceException("没有相应采购操作权限");

View File

@ -9,7 +9,7 @@
<result column="is_default" property="isDefault"/><result column="scope_type" property="scopeType"/>
<result column="scope_key" property="scopeKey"/><result column="project_id" property="projectId"/>
<result column="source_version_id" property="sourceVersionId"/><result column="version" property="version"/>
<result column="create_time" property="createTime"/><result column="update_time" property="updateTime"/>
<result column="create_time" property="createTime"/><result column="update_time" property="updateTime"/><result column="create_by" property="createBy"/>
</resultMap>
<resultMap id="Line" type="com.ruoyi.production.domain.BomLine">
<id column="id" property="id"/><result column="bom_id" property="bomId"/><result column="item_id" property="itemId"/>
@ -27,6 +27,7 @@
<result column="default_version_tag" property="defaultVersionTag"/>
<result column="series_id" property="seriesId"/><result column="series_name" property="seriesName"/><result column="series_version" property="seriesVersion"/>
<result column="edition_tag" property="editionTag"/><result column="source_product_id" property="sourceProductId"/><result column="source_bom_id" property="sourceBomId"/>
<result column="create_by" property="createBy"/><result column="create_time" property="createTime"/><result column="update_time" property="updateTime"/>
</resultMap>
<resultMap id="ProjectProduct" type="com.ruoyi.production.domain.ProjectProduct">
<id column="id" property="id"/><result column="project_id" property="projectId"/><result column="item_id" property="itemId"/>

View File

@ -39,7 +39,7 @@
sum(case when pr.purchase_status not in (4,5) and pr.historical=0 then 1 else 0 end) open_count,
sum(case when exists(select 1 from purchase_arrival pa where pa.purchase_request_id=pr.id and pa.acceptance_status=0) then 1 else 0 end) pending_count,
sum(case when pr.purchase_status=3 then 1 else 0 end) partial_count,
sum(case when pr.price_locked=1 and pr.historical=0 and pr.purchase_status&lt;&gt;5 and pr.quantity&gt;coalesce((select sum(pa.arrival_quantity-pa.defective_quantity-pa.returned_quantity) from purchase_arrival pa where pa.purchase_request_id=pr.id and pa.acceptance_status in (0,1)),0) then 1 else 0 end) arrivable_count
sum(case when pr.historical=0 and pr.purchase_status&lt;&gt;5 and pr.quantity&gt;coalesce((select sum(pa.arrival_quantity-pa.defective_quantity-pa.returned_quantity) from purchase_arrival pa where pa.purchase_request_id=pr.id and pa.acceptance_status in (0,1)),0) then 1 else 0 end) arrivable_count
from purchase_batch pb
left join purchase_request pr on pr.purchase_batch_id = pb.id and pr.del_flag='0'
<if test="params.amountDisplay == true">and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or pr.final_unit_price is null or pr.final_unit_price&lt;&gt;0)</if>

View File

@ -132,7 +132,7 @@
<if test="notArrived != null and notArrived">and pr.historical=0 and pr.purchase_status&lt;&gt;5 and pr.quantity&gt;coalesce(pa.accepted_quantity,0)</if>
<if test="pendingRegistration != null and pendingRegistration">
and pr.historical=0 and pr.purchase_status&lt;&gt;5
and pr.price_locked=1 and pr.final_unit_price&gt;=0 and pb.supplier_id is not null
and pb.supplier_id is not null and pb.del_flag='0'
and pr.quantity&gt;coalesce(pa.accepted_quantity,0)+coalesce(pa.pending_quantity,0)
</if>
<if test="notReceived != null and notReceived">and pr.historical=0 and pr.purchase_status&lt;&gt;5 and pr.quantity&gt;coalesce((select sum(ir.in_num) from in_record ir where ir.purchase_request_id=pr.id and ir.in_status=1 and ir.receipt_root=0),0)</if>
@ -148,7 +148,7 @@
or applicant_user.nick_name like concat('%', #{applicantName}, '%'))
</if>
<if test="purchaseStatus != null">and pr.purchase_status = #{purchaseStatus}</if>
<if test="arrivalReady != null and arrivalReady">and pr.price_locked=1 and pb.supplier_id is not null and pr.historical=0 and pr.purchase_status&lt;&gt;5</if>
<if test="arrivalReady != null and arrivalReady">and pb.supplier_id is not null and pb.del_flag='0' and pr.historical=0 and pr.purchase_status&lt;&gt;5</if>
<if test="priceLocked != null">and pr.price_locked = #{priceLocked}</if>
<if test="pendingAcceptance != null and pendingAcceptance">and coalesce(pa.pending_quantity, 0) &gt; 0</if>
<if test="purchaseBatchNo != null and purchaseBatchNo != ''">and pr.purchase_batch_no like concat('%', #{purchaseBatchNo}, '%')</if>

View File

@ -24,6 +24,7 @@
"element-plus": "2.13.1",
"file-saver": "2.0.5",
"fuse.js": "7.1.0",
"heic-to": "1.6.7",
"js-beautify": "1.15.4",
"js-cookie": "3.0.5",
"jsencrypt": "3.3.2",
@ -5054,6 +5055,12 @@
"he": "bin/he"
}
},
"node_modules/heic-to": {
"version": "1.6.7",
"resolved": "https://registry.npmmirror.com/heic-to/-/heic-to-1.6.7.tgz",
"integrity": "sha512-GCPYNl86u6eZ7mr2aa+uQB+PrQOVKSBYfH8esovr8kh2c6EYQSDYIJ6uhXSmM2hPC8PdBVJ/Trn0jnfM9H9gvg==",
"license": "LGPL-3.0"
},
"node_modules/hookable": {
"version": "5.5.3",
"resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz",

View File

@ -37,6 +37,7 @@
"element-plus": "2.13.1",
"file-saver": "2.0.5",
"fuse.js": "7.1.0",
"heic-to": "1.6.7",
"js-beautify": "1.15.4",
"js-cookie": "3.0.5",
"jsencrypt": "3.3.2",

View File

@ -0,0 +1,177 @@
heic-to is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
heic-to is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
---------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -0,0 +1,5 @@
HEIC/HEIF browser conversion uses heic-to 1.6.7 (unmodified).
License: LGPL-3.0, see heic-to-LICENSE.txt.
Source and replacement/build instructions: https://github.com/hoppergee/heic-to/tree/v1.6.7
The upstream distribution bundles libheif and libde265; their corresponding source is linked in the upstream repository.
Photos are converted locally. No photo data is sent to these projects or their websites.

View File

@ -1,12 +1,14 @@
import {prepareArrivalPhoto} from '@/utils/arrival-photo-format'
import request from '@/utils/request'
export const ARRIVAL_PHOTO_LIMIT=9,ARRIVAL_PHOTO_BYTES=20*1024*1024
// The operating system may supply an incorrect MIME/extension; the server checks the actual bytes.
export function arrivalPhotoError(file){
if(!['image/jpeg','image/png','image/webp'].includes(file.type)||! /\.(jpe?g|png|webp)$/i.test(file.name||''))return '请选择 JPG、PNG 或 WebP 图片'
if(file.type==='image/svg+xml'||/\.svg$/i.test(file.name||'')||(!file.type?.startsWith('image/')&&!/\.(jpe?g|jfif|png|webp|gif|bmp|tiff?|heic|heif|avif)$/i.test(file.name||'')))return '请选择照片或图片文件'
if(!file.size||file.size>ARRIVAL_PHOTO_BYTES)return '每张照片不能超过20MB'
return ''
}
export function uploadArrivalPhoto(requestId,uploadId,file,signal){const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/'+requestId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}
export async function uploadArrivalPhoto(requestId,uploadId,file,signal){file=await prepareArrivalPhoto(file,signal);const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/'+requestId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}
export const removeArrivalPhoto=id=>request({url:'/warehouse/purchase/arrival/photos/'+id,method:'delete'})
export const readArrivalPhoto=(id,signal)=>request({url:'/warehouse/purchase/arrival/photos/'+id+'/content',responseType:'blob',signal})
export function supplementArrivalPhoto(arrivalId,uploadId,file,signal){const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/record/'+arrivalId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}
export async function supplementArrivalPhoto(arrivalId,uploadId,file,signal){file=await prepareArrivalPhoto(file,signal);const data=new FormData();data.append('file',file);data.append('uploadId',uploadId);return request({url:'/warehouse/purchase/arrival/photos/record/'+arrivalId,method:'post',headers:{'Content-Type':'multipart/form-data',repeatSubmit:false},data,signal,timeout:120000})}

View File

@ -6,9 +6,9 @@ export const listPurchaseDocuments = (type, id, signal) => request({ url: purcha
export const getPurchaseAcceptanceConfirmation = (id, signal) => request({url:`/warehouse/purchase/batch/${Number(id)}/acceptance-confirmation`,signal})
export const confirmPurchaseAcceptance = (id,data,signal) => request({url:`/warehouse/purchase/batch/${Number(id)}/acceptance-confirmation`,method:'post',data,signal})
export const savePurchaseDocumentNumber = (type, id, kind, data, signal) => request({ url: `${purchaseDocumentPath(type, id)}/${kind}/number`, method: 'put', data, signal })
export function uploadPurchaseDocument(type, id, kind, file, uploadId, signal) {
export function uploadPurchaseDocument(type, id, kind, file, uploadId, signal, onProgress) {
purchaseDocumentPath(type,id);purchaseDocumentId(uploadId)
return uploadFileResumable(file,{purpose:'purchase',targetId:Number(id),type,kind},{signal})
return uploadFileResumable(file,{purpose:'purchase',targetId:Number(id),type,kind},{signal,onProgress})
}
export const removePurchaseDocument = (type, id, fileId, signal) => request({ url: `${purchaseDocumentPath(type, id)}/files/${purchaseDocumentId(fileId)}`, method: 'delete', signal })
export async function readPurchaseDocument(type, id, fileId, signal) {

View File

@ -116,3 +116,5 @@ export const preparePurchaseSheet = (ids,batchId) => request({url:'/warehouse/pu
export const getUnbatchedSheet = ids => request({url:'/warehouse/purchase/sheet/unbatched',method:'get',params:{ids:ids.join(',')}})
export function updatePurchaseBatchRemark(id, remark) { return request({url: `/warehouse/purchase/batch/${id}/remark`, method: 'put', data: {remark}}) }
export const readyPurchaseArrival=id=>request({url:'/warehouse/purchase/arrival/'+id+'/ready-for-inbound',method:'put'})

View File

@ -2,7 +2,7 @@
<span v-if="compact" class="arrival-photos-trigger"><el-button v-if="canUpload||modelValue.length" link type="primary" :disabled="disabled&&!readonly" @click="open=true">{{ supplementable?'查看 / 补录照片':readonly?'查看照片':'到货照片' }}<span v-if="modelValue.length">({{ modelValue.length }})</span><span v-else>{{ supplementable?'(未上传)':'(必传)' }}</span></el-button><span v-else>—</span></span>
<component :is="compact?'el-dialog':'div'" v-if="!compact||open" v-model="open" :title="title||'到货照片'" width="min(720px,94vw)" append-to-body class="arrival-photos-dialog" :close-on-click-modal="!busy" :show-close="!busy" :close-on-press-escape="!busy">
<section class="arrival-photos" :aria-busy="busy">
<div v-if="canUpload" class="arrival-photos-toolbar"><input ref="input" type="file" accept="image/jpeg,image/png,image/webp" multiple hidden :disabled="disabled||busy" @change="choose"/><el-button :disabled="disabled||busy||modelValue.length>=9" :loading="busy" @click="input.click()"><el-icon><Upload/></el-icon>{{supplementable?'补录照片':'上传照片'}}</el-button><span>{{supplementable?'上传后自动保存':'必传,至少1张'}} · {{ modelValue.length }}/9 张 · 每张不超过20MB</span></div>
<div v-if="canUpload" class="arrival-photos-toolbar"><input ref="input" type="file" accept="image/*,.heic,.heif,.tif,.tiff" multiple hidden :disabled="disabled||busy" @change="choose"/><el-button :disabled="disabled||busy||modelValue.length>=9" :loading="busy" @click="input.click()"><el-icon><Upload/></el-icon>{{supplementable?'补录照片':'上传照片'}}</el-button><span>{{supplementable?'上传后自动保存':'必传,至少1张'}} · {{ modelValue.length }}/9 张 · 每张不超过20MB</span></div>
<div v-if="modelValue.length" class="arrival-photos-grid">
<article v-for="photo in modelValue" :key="photo.clientKey||photo.id" class="arrival-photo" :class="{'is-failed':photo.error}">
<el-image v-if="url(photo)" :src="url(photo)" fit="cover" :preview-src-list="previewUrls" :initial-index="Math.max(0,previewUrls.indexOf(url(photo)))" preview-teleported :alt="photo.name||'到货照片'"/>
@ -20,6 +20,7 @@
</component>
</template>
<script setup>
import {prepareArrivalPhoto} from '@/utils/arrival-photo-format'
import {computed,nextTick,onBeforeUnmount,ref,watch} from 'vue'
import {Upload} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
@ -37,7 +38,7 @@ function url(photo){return photo.localUrl&&ownedUrls.has(photo.localUrl)?photo.l
const previewUrls=computed(()=>props.modelValue.map(url).filter(Boolean))
function own(blob){const value=URL.createObjectURL(blob);ownedUrls.add(value);return value}
async function choose(event){const files=[...event.target.files];event.target.value='';if(props.disabled||busy.value)return;const values=[...props.modelValue];for(const raw of files){if(values.length>=9){ElMessage.warning('每次到货最多9张照片');break}const error=arrivalPhotoError(raw);if(error){ElMessage.warning(error);continue}try{values.push({clientKey:purchaseUploadId(),name:raw.name,raw,localUrl:own(raw),uploading:false})}catch(e){ElMessage.error(e.message);break}}emit('update:modelValue',values);await nextTick();for(const p of values.filter(p=>p.raw&&!p.id&&!p.error))await upload(p)}
async function upload(photo){if(props.disabled||disposed)return;const ctl=new AbortController();active.add(ctl);update(photo,{uploading:true,error:''});try{const result=await (props.supplementable?supplementArrivalPhoto(props.arrivalId,photo.clientKey,photo.raw,ctl.signal):uploadArrivalPhoto(props.requestId,photo.clientKey,photo.raw,ctl.signal));update(photo,{...result.data,uploading:false,error:''})}catch(e){if(!ctl.signal.aborted)update(photo,{uploading:false,error:e.message||'上传失败,请重试或移除'})}finally{active.delete(ctl)}}
async function upload(photo){if(props.disabled||disposed)return;const ctl=new AbortController();active.add(ctl);update(photo,{uploading:true,error:''});try{const prepared=await prepareArrivalPhoto(photo.raw,ctl.signal);if(prepared!==photo.raw)update(photo,{raw:prepared,name:prepared.name,localUrl:own(prepared)});const result=await (props.supplementable?supplementArrivalPhoto(props.arrivalId,photo.clientKey,prepared,ctl.signal):uploadArrivalPhoto(props.requestId,photo.clientKey,prepared,ctl.signal));update(photo,{...result.data,...(/\.(gif|bmp|tiff?)$/i.test(photo.name)?{localUrl:undefined}:{}),uploading:false,error:''})}catch(e){if(!ctl.signal.aborted)update(photo,{uploading:false,error:e.message||'上传失败,请重试或移除'})}finally{active.delete(ctl)}}
async function remove(photo){if(props.disabled||photo.uploading)return;try{if(photo.id)await removeArrivalPhoto(photo.id);if(disposed)return;emit('update:modelValue',props.modelValue.filter(p=>(p.clientKey||p.id)!==(photo.clientKey||photo.id)));if(photo.localUrl){URL.revokeObjectURL(photo.localUrl);ownedUrls.delete(photo.localUrl)}}catch(e){ElMessage.error(e.message||'移除失败,请重试')}}
async function load(photo){if(!photo.id||url(photo)||disposed||loading.value[photo.id])return;const ctl=new AbortController();active.add(ctl);loading.value={...loading.value,[photo.id]:true};loadErrors.value={...loadErrors.value,[photo.id]:''};try{const blob=await readArrivalPhoto(photo.id,ctl.signal);if(!/^image\/(jpeg|png|webp)$/.test(blob.type))throw Error('照片加载失败');if(!disposed&&!ctl.signal.aborted)resources.value={...resources.value,[photo.id]:own(blob)}}catch(e){if(!disposed&&!ctl.signal.aborted)loadErrors.value={...loadErrors.value,[photo.id]:e.message||'照片加载失败'}}finally{active.delete(ctl);if(!disposed)loading.value={...loading.value,[photo.id]:false}}}
watch(()=>[props.modelValue.map(p=>p.id||p.clientKey).join(','),open.value],()=>{if(!props.compact||open.value){props.modelValue.filter(p=>p.raw&&!p.id&&!url(p)).forEach(p=>{resources.value={...resources.value,[p.clientKey]:own(p.raw)}});props.modelValue.filter(p=>p.id&&!url(p)).forEach(load)}},{immediate:true})

View File

@ -0,0 +1,32 @@
<template>
<div class="batch-file-upload">
<input ref="picker" type="file" :multiple="limit!==1" :accept="accept" hidden :disabled="disabled||running||remaining<=0" @change="choose"/>
<el-button type="primary" :disabled="disabled||running||remaining<=0" :loading="running" @click="picker.click()">{{label}}</el-button>
<span class="batch-file-hint">{{limit===1?'选择一个文件':'可一次选择多个文件'}}</span>
<div v-if="jobs.length" class="batch-file-jobs" aria-live="polite">
<div class="batch-file-summary"><span>已上传 {{jobs.filter(j=>j.status==='done').length}} / {{jobs.length}}</span><el-button v-if="running" link @click="pause">暂停</el-button><el-button v-if="!running&&jobs.some(j=>j.status!=='done')" link type="primary" :disabled="disabled" @click="run">继续 / 重试未完成</el-button><el-button v-if="!running&&jobs.some(j=>j.status!=='done')" link :disabled="disabled" @click="cancelPending">取消未完成</el-button></div>
<div v-for="job in jobs" :key="job.id" class="batch-file-job"><span :title="job.file.name">{{job.file.name}}</span><el-progress v-if="job.status==='uploading'" :percentage="job.percent" :stroke-width="4"/><span :class="{'upload-failed':job.status==='failed'}">{{job.error||({waiting:'等待上传',uploading:'正在上传',done:'上传完成',paused:'已暂停'})[job.status]}}</span></div>
</div>
</div>
</template>
<script setup>
import {ref,shallowRef,onBeforeUnmount} from 'vue'
import {ElMessage} from 'element-plus'
import {purchaseUploadId} from '@/utils/purchase-documents'
const props=defineProps({upload:{type:Function,required:true},cancel:Function,validate:{type:Function,default:()=>''},accept:String,label:{type:String,default:'上传附件'},disabled:Boolean,remaining:{type:Number,default:Infinity},limit:{type:Number,default:Infinity}})
const emit=defineEmits(['busy','updated']),picker=ref(),jobs=shallowRef([]),running=ref(false)
let controller,disposed=false,paused=false
function refresh(){jobs.value=[...jobs.value]}
async function choose(event){const files=Array.from(event.target.files||[]);event.target.value='';if(!files.length||running.value||props.disabled)return;if(files.length>Math.min(props.remaining,props.limit)){ElMessage.warning(`本次最多可选择 ${Math.min(props.remaining,props.limit)} 个文件,请重新选择`);return}jobs.value=files.map(file=>({file,id:purchaseUploadId(),status:'waiting',percent:0,error:''}));await run()}
async function run(){if(running.value||props.disabled||disposed)return;running.value=true;paused=false;emit('busy',true);let changed=false
try{for(const job of jobs.value){if(disposed||paused)break;if(job.status==='done')continue;const reason=props.validate(job.file);if(reason){job.status='failed';job.error=reason;refresh();continue}job.status='uploading';job.error='';job.percent=0;controller=new AbortController();refresh()
try{await props.upload(job.file,job.id,controller.signal,state=>{if(!disposed){job.sessionId=state.sessionId||job.sessionId;job.percent=Math.max(0,Math.min(100,Number(state.percent)||0));refresh()}});job.status='done';job.percent=100;changed=true}
catch(error){job.status=controller.signal.aborted?'paused':'failed';job.error=controller.signal.aborted?'已暂停,可继续':error.message||'上传失败,请重试'}finally{refresh()}
}}finally{running.value=false;if(!disposed){emit('busy',false);if(changed)emit('updated')}}}
async function cancelPending(){if(running.value||props.disabled)return;running.value=true;emit('busy',true);try{for(const job of jobs.value.filter(j=>j.status!=='done')){try{if(job.sessionId&&props.cancel)await props.cancel(job.sessionId);jobs.value=jobs.value.filter(j=>j!==job)}catch(error){job.error=error.message||'取消失败,请重试';refresh()}}}finally{running.value=false;if(!disposed)emit('busy',false)}}
function pause(){paused=true;controller?.abort()}
onBeforeUnmount(()=>{disposed=true;pause()})
</script>
<style scoped>
.batch-file-upload{min-width:0}.batch-file-hint{margin-left:10px;font-size:12px;color:var(--el-text-color-secondary)}.batch-file-jobs{margin-top:10px;padding:8px 12px;background:var(--el-fill-color-light);border-radius:6px;max-height:230px;overflow:auto}.batch-file-summary{display:flex;justify-content:space-between;align-items:center;font-size:12px}.batch-file-job{display:grid;grid-template-columns:minmax(120px,1fr) minmax(80px,180px);gap:8px;align-items:center;padding:6px 0;font-size:12px}.batch-file-job>span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.batch-file-job:has(.el-progress){grid-template-columns:minmax(120px,1fr) 100px 90px}.upload-failed{color:var(--el-color-danger)}
</style>

Some files were not shown because too many files have changed in this diff Show More