feat(warehouse): 支持入库移库照片及库存图库

Web 与 App 支持选传最多 9 张、单张 50MB 照片,并与本次入库和移库事务绑定。库存图库按项目、物品、库区归集到货、入库和移库照片,支持来源筛选、缩略图及原图预览,校验只读权限和照片归属。附开发数据库结构脚本、更新说明和相关测试,同时纳入采购明细垂直居中修正。
This commit is contained in:
lixiaolong 2026-11-26 11:39:57 +08:00
parent 8f3ffaa1a9
commit 5bc252d129
34 changed files with 609 additions and 50 deletions

View File

@ -1,6 +1,6 @@
[
"到货照片按真实图片内容识别,不再因后缀不一致上传失败。",
"网页兼容苹果HEIC/HEIF原图,本地自动转换后上传。",
"增加GIF、BMP、TIFF等常见图片格式兼容。",
"手机相册优先使用兼容格式,保留批量补录和失败重试。"
]
"入库、移库支持拍照或从相册选图,照片选传。",
"每次最多9张、每张不超过50MB,支持批量办理。",
"库存增加照片入口,按到货、入库、移库分类回看。",
"缩略图快速浏览,点击查看原图,可核对单号和日期。"
]

View File

@ -106,7 +106,7 @@ export class ApiClient {
body: preparedBody === undefined ? undefined : multipart ? preparedBody as FormData : JSON.stringify(preparedBody)
});
if(options.responseType==='image'&&response.ok&&/^image\/(png|jpeg|webp)$/.test(response.headers.get('content-type')?.split(';')[0]||'')){
const limit=Math.max(1,Math.min(options.imageMaxBytes??6*1024*1024,20*1024*1024));
const limit=Math.max(1,Math.min(options.imageMaxBytes??6*1024*1024,50*1024*1024));
if(Number(response.headers.get('content-length')||0)>limit)throw new ApiError('图片超过预览大小限制,请在电脑端查看。',413);
const bytes=new Uint8Array(await response.arrayBuffer());
if(epoch!==this.generation)throw new ApiError('会话已切换,请重新查询。',409);

View File

@ -1,6 +1,6 @@
import {validDate,type Row} from './modules.ts';
export type OperationKind='use'|'move'|'receive'|'borrow'|'check'|'return';
export type OperationRow={source:Row;quantity:string;area:Row|null;stock?:Row|null;key:string;status:'editing'|'pending'|'success'|'failed'|'uncertain';error:string;payload?:RequestStep[]};
export type OperationRow={source:Row;quantity:string;area:Row|null;stock?:Row|null;key:string;status:'editing'|'pending'|'success'|'failed'|'uncertain';error:string;photos?:Row[];photosPending?:boolean;payload?:RequestStep[]};
export type RequestStep={path:string;method:string;body:Row};
export type OperationForm={date:string;remark:string;project:Row|null};
export const operationTitles:Record<OperationKind,string>={use:'物料领用',move:'移库',receive:'办理入库',borrow:'借用',check:'登记盘点',return:'归还库存'};
@ -14,6 +14,8 @@ export function validateOperation(kind:OperationKind,rows:OperationRow[],form:Op
for(let i=0;i<rows.length;i++){
const row=rows[i],label=`第 ${i+1} 项(${row.source.productName||row.source.itemName||'物品'})`;
if(row.status==='success'||row.payload)continue;
if(['receive','move'].includes(kind)&&(row.photosPending||(row.photos||[]).some(p=>!p.id||p.error)))return `${label}:请等待照片上传完成,或移除失败照片。`;
if((row.photos||[]).length>9)return `${label}:最多9张照片。`;
const quantity=Number(row.quantity);
if(!/^\d+(\.\d{1,4})?$/.test(row.quantity)||!Number.isFinite(quantity)||(kind==='check'?quantity<0:quantity<=0))return `${label}:请输入${kind==='check'?'不小于 0':'大于 0'}的数量,最多 4 位小数。`;
if(kind!=='check'&&quantity>available(kind,row))return `${label}:本次数量超过${kind==='return'?'未还数量或取料库存':'当前可用数量'}。`;
@ -30,7 +32,7 @@ export function validateOperation(kind:OperationKind,rows:OperationRow[],form:Op
return '';
}
export function operationPayload(kind:OperationKind,row:OperationRow,form:OperationForm):RequestStep[]{
const s=row.source,quantity=Number(row.quantity),base={quantity,key:row.key,date:form.date,remark:form.remark};
const s=row.source,quantity=Number(row.quantity),base={quantity,key:row.key,date:form.date,remark:form.remark,...(row.photos?.length?{photoIds:row.photos.map(p=>p.id)}:{})};
if(kind==='use')return [{path:'/warehouse/stock/out',method:'POST',body:{id:s.id,usageProjectId:s.projectId,outNum:quantity,outType:4,outNo:'MOUT-'+row.key,outTime:form.date+' 00:00:00',remark:form.remark}}];
if(kind==='move')return [{path:'/warehouse/stock/move',method:'POST',body:{...base,projectId:s.projectId,itemId:s.productId,fromAreaId:s.areaId,toAreaId:row.area?.id}}];
if(kind==='borrow')return [{path:'/project/loans',method:'POST',body:{...base,lenderProjectId:s.projectId,borrowerProjectId:form.project?.id,itemId:s.productId,fromAreaId:s.areaId,toAreaId:row.area?.id}}];
@ -38,7 +40,7 @@ export function operationPayload(kind:OperationKind,row:OperationRow,form:Operat
if(kind==='check')return [{path:'/warehouse/check',method:'POST',body:{projectId:s.projectId,productId:s.productId,areaId:s.areaId,realNum:quantity,businessDate:form.date,reason:form.remark,remark:form.remark}}];
return s.receiptRoot?[{path:`/warehouse/in/receive/${s.id}`,method:'POST',body:{...base,areaId:row.area?.id}}]:[
{path:'/warehouse/in',method:'PUT',body:{...s,areaId:row.area?.id,businessDate:form.date,remark:form.remark}},
{path:`/warehouse/in/confirm/${s.id}`,method:'PUT',body:{}}
{path:`/warehouse/in/confirm/${s.id}`,method:'PUT',body:row.photos?.length?{photoIds:row.photos.map(p=>p.id)}:{}}
];
}
/** Persist the frozen payload before sending. Only retryable rows reuse the exact identity/body. */

View File

@ -1,3 +1,4 @@
import {OperationPhotos} from './OperationPhotos';
import React,{useEffect,useRef,useState} from 'react';
import {KeyboardAvoidingView,Modal,Platform,ScrollView,View} from 'react-native';
import {Text} from '../typography';
@ -14,13 +15,13 @@ import {ItemIdentity,RecordMeta} from './ItemIdentity';
type Snapshot={rows:OperationRow[];form:OperationForm;preview:boolean};
export type BatchOperationProps={api:ApiClient;input:Row[];kind:OperationKind;scope:string;close:()=>void;done:()=>void};
export function BatchOperation({api,input,kind,scope,close,done}:BatchOperationProps){
const t=useTheme(),[rows,setRows]=useState<OperationRow[]>(()=>input.map(source=>({source,quantity:'',area:null,key:Crypto.randomUUID(),status:'editing',error:''}))),[form,setForm]=useState<OperationForm>({date:localDate(),remark:'',project:null});
const t=useTheme(),[rows,setRows]=useState<OperationRow[]>(()=>input.map(source=>({source,quantity:'',area:null,key:Crypto.randomUUID(),status:'editing',error:'',photos:[],photosPending:false}))),[form,setForm]=useState<OperationForm>({date:localDate(),remark:'',project:null});
const [areas,setAreas]=useState<Row[]>([]),[projects,setProjects]=useState<Row[]>([]),[stocks,setStocks]=useState<Row[]>([]),[ready,setReady]=useState(false),[loadError,setLoadError]=useState(''),[error,setError]=useState(''),[preview,setPreview]=useState(false),[busy,setBusy]=useState(false),[reload,setReload]=useState(0);
const lock=useRef(false),alive=useRef(true),snapshot={rows,form,preview},returnSource=kind==='return'?rows[0]?.source:undefined;
const attempted=rows.some(r=>r.payload),succeeded=rows.filter(r=>r.status==='success').length;
// One recoverable operation per action/account. Re-selecting a subset cannot
// silently create fresh identities for a previously uncertain batch.
const draft=useOperationDraft<Snapshot>({scope,suspendAutosave:busy,kind:'stock-'+kind,id:'active',value:snapshot,onRestore:value=>{setRows(value.rows.map(r=>r.status==='pending'?{...r,status:'uncertain'}:r));setForm(value.form);setPreview(value.preview||value.rows.some(r=>r.payload));},hasContent:value=>value.rows.some(r=>r.quantity||r.area||r.payload)||!!value.form.remark||!!value.form.project,isPending:value=>value.rows.some(r=>r.payload&&r.status!=='success')});
const draft=useOperationDraft<Snapshot>({scope,suspendAutosave:busy,kind:'stock-'+kind,id:'active',value:snapshot,onRestore:value=>{setRows(value.rows.map(r=>({...r,status:r.status==='pending'?'uncertain':r.status,photos:(r.photos||[]).map(p=>({...p,uri:undefined,...(!p.id?{error:'照片尚未上传,请移除后重新拍照'}:{})})),photosPending:false})));setForm(value.form);setPreview(value.preview||value.rows.some(r=>r.payload));},hasContent:value=>value.rows.some(r=>r.quantity||r.area||r.payload||r.photos?.length)||!!value.form.remark||!!value.form.project,isPending:value=>value.rows.some(r=>r.payload&&r.status!=='success')});
useEffect(()=>{alive.current=true;const ctl=new AbortController();setReady(false);setLoadError('');void(async()=>{try{
if(['receive','move','borrow','return'].includes(kind)){const result=await api.request<Row>('/warehouse/area/optionselect',{signal:ctl.signal});if(!ctl.signal.aborted)setAreas(result.data||[]);}
if(kind==='borrow'){const result=await api.request<Row>('/project/info/options',{signal:ctl.signal});if(!ctl.signal.aborted)setProjects(result.data||[]);}
@ -70,6 +71,7 @@ export function BatchOperation({api,input,kind,scope,close,done}:BatchOperationP
{kind==='return'&&<Note>未还 {row.source.outstandingQuantity} {row.source.unit||''}</Note>}
<Field label={kind==='check'?'实际盘点数量':'本次数量'} value={row.quantity} onChange={quantity=>changeRow(index,{quantity})} keyboard="decimal-pad"/>
{['move','receive','borrow','return'].includes(kind)&&<Choice label="目标库区" items={areas} value={row.area} onChange={area=>changeRow(index,{area})} nameKey="areaName"/>}
{['receive','move'].includes(kind)&&<OperationPhotos api={api} kind={kind==='receive'?'IN':'MOVE'} photos={row.photos||[]} disabled={busy||attempted} onChange={photos=>changeRow(index,{photos})} onPending={pending=>{setRows(old=>old[index]?.photosPending===pending?old:old.map((r,i)=>i===index?{...r,photosPending:pending}:r));}}/>}
{rows.length>1&&<Button title="移除此项" secondary onPress={()=>setRows(old=>old.filter((_,i)=>i!==index))}/>}
</>:<><Text style={{fontSize:16,lineHeight:23,fontWeight:'600',color:t.accent}}>{row.quantity} {row.source.unit||''}</Text>{!!row.area&&<Note>目标库区:{row.area.areaName||row.area.areaCode}</Note>}{kind==='check'&&<Note>账面 {row.source.stockNum} → 实盘 {row.quantity};确认盘点生效后才调整库存。</Note>}<Text style={{color:row.status==='success'?'#278357':row.error?'#bd3636':t.muted,fontSize:13,lineHeight:20}}>{row.status==='success'?'已成功':row.status==='pending'?'正在处理':row.status==='uncertain'?'结果待核对,不会自动重发':row.error||'待提交'}</Text></>}
</Card>)}

View File

@ -1,3 +1,5 @@
import {StockPhotos} from './StockPhotos';
import {OperationPhotoViewer} from './OperationPhotoViewer';
import React,{useCallback,useEffect,useRef,useState} from 'react';
import {ActivityIndicator,FlatList,Pressable,View} from 'react-native';
import {Text,TextInput} from '../typography';
@ -21,6 +23,8 @@ 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,photoLookup=false}:{api:ApiClient;module:Module;permissions:string[];canViewQuotes:boolean;scope:string;initialQuery?:Row;photoLookup?:boolean;onNavigate?:(key:string,query?:Row)=>void}){
const [stockPhotoRow,setStockPhotoRow]=useState<Row|null>(null);
const [operationPhotoRecord,setOperationPhotoRecord]=useState<{kind:'IN'|'MOVE';row:Row}|null>(null);
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);
@ -51,7 +55,9 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
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);
const pendingHistory=module.key==='pending'&&item.purchaseRequestId&&allows(permissions,['warehouse:purchase:list','warehouse:purchase:manage']);
if(!visible&&!pendingHistory)return null;
const stockPhotos=['stock','move','use'].includes(module.key)&&allows(permissions,['warehouse:stock:list']);
const inPhotos=module.key==='in'&&allows(permissions,['warehouse:in:list']);
if(!visible&&!pendingHistory&&!stockPhotos&&!inPhotos)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>}
@ -60,6 +66,8 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
{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==='in'&&<Button title="入库照片" secondary onPress={()=>setOperationPhotoRecord({kind:'IN',row:item})}/>}
{stockPhotos&&<Button title="库存照片" secondary onPress={()=>setStockPhotoRow(item)}/>}
{module.key==='pending'&&eligible(item)&&<Button title="办理入库" disabled={busy} onPress={()=>setOperation({row:item,kind:'receive'})}/>}
</View>;
};
@ -71,6 +79,8 @@ export function BusinessList({api,module,permissions,canViewQuotes,scope,initial
</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>}
{stockPhotoRow&&<StockPhotos api={api} row={stockPhotoRow} close={()=>setStockPhotoRow(null)}/>}
{operationPhotoRecord&&<OperationPhotoViewer api={api} {...operationPhotoRecord} close={()=>setOperationPhotoRecord(null)}/>}
<FlatList ref={list} data={rows} keyExtractor={(row,index)=>String(row.id||row.loanNo||index)} onScroll={event=>{offset.current=event.nativeEvent.contentOffset.y;const saved=remembered.get(cacheKey);if(saved)saved.offset=offset.current;}} scrollEventThrottle={100} onLayout={()=>{if(cached.current?.offset){list.current?.scrollToOffset({offset:cached.current.offset,animated:false});cached.current=undefined;}}} contentContainerStyle={{paddingHorizontal:14,paddingBottom:14,gap:10}}
refreshing={busy&&page===1} onRefresh={()=>void refresh()} ListEmptyComponent={!busy?<Note>{error?'查询失败,请重试。':module.key==='arrival'?'当前没有待办理的到货记录。':'当前条件下暂无记录。'}</Note>:<ActivityIndicator color={t.accent}/>}
renderItem={({item})=><View>{picking&&<Pressable accessibilityRole="checkbox" accessibilityState={{checked:selected.some(r=>r.id===item.id),disabled:!eligible(item)||busy}} accessibilityLabel={`选择 ${item.productName||item.materialName}`} disabled={!eligible(item)||busy} onPress={()=>toggle(item)} style={{flexDirection:'row',gap:6,alignItems:'center',padding:8}}><Icon name={selected.some(r=>r.id===item.id)?'checkbox':'square-outline'} size={21} color={eligible(item)?t.accent:t.muted}/><Text style={{fontSize:13,color:t.muted}}>{eligible(item)?'加入本次办理':'当前不可办理'}</Text></Pressable>}{module.key==='arrival'?<ArrivalCard item={item} queue={arrivalQueue}>{actions(item)}</ArrivalCard>:<RecordCard module={module} item={item} compactAmounts={compactAmounts} canViewQuotes={canViewQuotes}>{!picking&&actions(item)}</RecordCard>}</View>}

View File

@ -0,0 +1,12 @@
import React,{useEffect,useState} from 'react';
import {Modal,ScrollView,View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {Button,Heading,Note,s,useTheme} from '../ui';
import {OperationPhotos} from './OperationPhotos';
export function OperationPhotoViewer({api,kind,row,close}:{api:ApiClient;kind:'IN'|'MOVE';row:Row;close:()=>void}){
const t=useTheme(),[records,setRecords]=useState<Row[]>([]),[photos,setPhotos]=useState<Row[]>([]),[selected,setSelected]=useState<number|null>(kind==='IN'?row.id:null),[error,setError]=useState(''),[loading,setLoading]=useState(true);
useEffect(()=>{const ctl=new AbortController();setLoading(true);setError('');void(async()=>{try{if(selected){const result=await api.request<Row>(`/warehouse/operation-photos/${kind}/${selected}`,{signal:ctl.signal});if(!ctl.signal.aborted)setPhotos(result.data||[]);}else{const result=await api.request<Row>('/warehouse/operation-photos/moves',{query:{projectId:row.projectId,itemId:row.productId},signal:ctl.signal});if(!ctl.signal.aborted)setRecords(result.data||[]);}}catch(e){if(!ctl.signal.aborted)setError((e as Error).message);}finally{if(!ctl.signal.aborted)setLoading(false);}})();return()=>ctl.abort();},[api,kind,row.id,selected]);
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:16,justifyContent:'space-between'}]}><Heading>{kind==='IN'?'入库照片':'移库照片'}</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}>{loading?<Note>正在加载照片…</Note>:error?<Note>{error}</Note>:selected?<><OperationPhotos api={api} kind={kind} photos={photos} readonly/>{kind==='MOVE'&&<Button title="返回移库记录" secondary onPress={()=>setSelected(null)}/>}</>:<>{records.map(record=><Button key={record.id} title={`${record.event_no} · ${record.business_date||''} · ${record.quantity}`} secondary onPress={()=>setSelected(record.id)}/>)}{!records.length&&<Note>暂无已上传照片的移库记录</Note>}</>}</ScrollView></SafeAreaView></Modal>;
}

View File

@ -0,0 +1,59 @@
import React,{useEffect,useRef,useState} from 'react';
import {Image,Platform,Pressable,View} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as Crypto from 'expo-crypto';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {Button,Icon,Note,s} from '../ui';
import {ProtectedImage} from '../files';
export function OperationPhotos({api,kind,photos,onChange,onPending,readonly=false,disabled=false,arrivalId,supplemental=false}:{api:ApiClient;kind:'IN'|'MOVE';photos:Row[];onChange?:(photos:Row[])=>void;onPending?:(pending:boolean)=>void;readonly?:boolean;disabled?:boolean;arrivalId?:number;supplemental?:boolean}){
const canUpload=!readonly||supplemental;
const [working,setWorking]=useState(false),[error,setError]=useState('');
const current=useRef(photos),alive=useRef(true),locked=useRef(false),controller=useRef<AbortController|null>(null);
current.current=photos;
useEffect(()=>{alive.current=true;return()=>{alive.current=false;controller.current?.abort();};},[]);
useEffect(()=>{onPending?.(canUpload&&(working||photos.some(p=>!p.id||p.error)));},[working,photos,canUpload,onPending]);
const update=(values:Row[])=>{current.current=values;if(alive.current)onChange?.(values);};
async function upload(photo:Row){
if(disabled||!canUpload||locked.current||!photo.uri)return;locked.current=true;setWorking(true);setError('');const ctl=new AbortController();controller.current=ctl;
try{
const body=new FormData();body.append('uploadId',photo.clientKey);
if(Platform.OS==='web')body.append('file',await(await fetch(photo.uri)).blob(),photo.name);
else body.append('file',{uri:photo.uri,type:photo.contentType,name:photo.name} as unknown as Blob);
const result=await api.request<Row>(`/warehouse/operation-photos/${kind}`,{method:'POST',body,signal:ctl.signal,timeout:120000});
if(alive.current)update(current.current.map(p=>p.clientKey===photo.clientKey?{...p,...result.data,error:''}:p));
}catch(e){if(alive.current&&!ctl.signal.aborted)update(current.current.map(p=>p.clientKey===photo.clientKey?{...p,error:(e as Error).message||'上传失败'}:p));}
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('');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,preferredAssetRepresentationMode:ImagePicker.UIImagePickerPreferredAssetRepresentationMode?.Compatible,allowsMultipleSelection:true,selectionLimit:9-photos.length,exif:false});
if(result.canceled||!alive.current)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>50*1024*1024)){setError('每张照片不能超过50MB,请降低照片大小或重新拍摄。');continue;}
const extension=type==='image/png'?'png':type==='image/webp'?'webp':'jpg';
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);}
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('');
try{if(photo.id)await api.request(`/warehouse/operation-photos/${photo.id}`,{method:'DELETE'});if(alive.current)update(current.current.filter(p=>(p.clientKey||p.id)!==(photo.clientKey||photo.id)));}
catch(e){if(alive.current)setError((e as Error).message);}
finally{locked.current=false;if(alive.current)setWorking(false);}
}
return <View style={{gap:10}}><Note>操作照片{supplemental?`补录 · ${photos.length}/9 · 上传后自动保存`:readonly?` · ${photos.length} 张`:`(选填)· ${photos.length}/9 · 每张不超过50MB`}</Note>
{canUpload&&<View style={s.row}>{Platform.OS!=='web'&&<Button title="拍照" disabled={disabled||working||photos.length>=9} onPress={()=>void choose(true)}/>}<Button title={Platform.OS==='web'?'上传图片':'从相册选择'} secondary disabled={disabled||working||photos.length>=9} onPress={()=>void choose(false)}/></View>}
<View style={[s.row,{alignItems:'flex-start'}]}>{photos.map((photo,index)=><View key={photo.clientKey||photo.id} style={{width:120,gap:5}}>{photo.id?<ProtectedImage api={api} path={`/warehouse/operation-photos/${photo.id}/content`} label={`操作照片 ${index+1}`} maxBytes={50*1024*1024} gallery={photos.filter(p=>p.id).map((p,i)=>({path:`/warehouse/operation-photos/${p.id}/content`,label:`操作照片 ${i+1}`,maxBytes:50*1024*1024}))} initialIndex={photos.filter(p=>p.id).findIndex(p=>p.id===photo.id)}/>:photo.uri?<Image source={{uri:photo.uri}} style={{width:118,height:100,borderRadius:10}}/>:null}
{!!photo.error&&<><Note>{photo.error}</Note><Button title="重试上传" secondary disabled={disabled||working} onPress={()=>void upload(photo)}/></>}
{(!readonly||supplemental&&!photo.id)&&<Pressable accessibilityRole="button" accessibilityLabel={`移除第${index+1}张`} disabled={disabled||working} onPress={()=>void remove(photo)} style={{position:'absolute',top:0,right:0,minWidth:44,minHeight:44,alignItems:'center',justifyContent:'center'}}><View style={{backgroundColor:'#fff',borderRadius:12}}><Icon name="close-circle" color="#b42335" size={23}/></View></Pressable>}</View>)}</View>
{working&&<Note>正在处理照片,请稍候…</Note>}{!!error&&<Note>{error}</Note>}{readonly&&!photos.length&&<Note>本次操作未上传照片</Note>}
</View>;
}

View File

@ -0,0 +1,22 @@
import React,{useEffect,useState} from 'react';
import {Modal,ScrollView,View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import type {ApiClient} from '../core/network';
import type {Row} from '../core/modules';
import {Button,Card,Heading,Note,s,useTheme} from '../ui';
import {ProtectedImage} from '../files';
import {ItemIdentity,RecordMeta} from './ItemIdentity';
import {formatDateTime} from '../core/date-display';
const tabs=[['ALL','全部'],['ARRIVAL','到货'],['IN','入库'],['MOVE','移库']];
export function StockPhotos({api,row,close}:{api:ApiClient;row:Row;close:()=>void}){
const t=useTheme(),[kind,setKind]=useState('ALL'),[page,setPage]=useState(1),[photos,setPhotos]=useState<Row[]>([]),[total,setTotal]=useState(0),[loading,setLoading]=useState(true),[error,setError]=useState(''),[reload,setReload]=useState(0);
useEffect(()=>{const ctl=new AbortController();setLoading(true);setError('');setPhotos([]);void api.request<Row>(`/warehouse/stock/${row.id}/photos`,{query:{kind,pageNum:page,pageSize:12},signal:ctl.signal}).then(result=>{if(!ctl.signal.aborted){setPhotos(result.data.rows);setTotal(result.data.total);}}).catch(e=>{if(!ctl.signal.aborted)setError((e as Error).message);}).finally(()=>{if(!ctl.signal.aborted)setLoading(false);});return()=>ctl.abort();},[api,row.id,kind,page,reload]);
const gallery=photos.map(p=>({path:p.contentPath,label:p.name,maxBytes:50*1024*1024}));
const groups=new Map<string,{row:Row;photos:{photo:Row;index:number}[]}>();photos.forEach((photo,index)=>{const key=photo.kind+':'+photo.recordId;if(!groups.has(key))groups.set(key,{row:photo,photos:[]});groups.get(key)!.photos.push({photo,index});});
return <Modal visible animationType="slide" onRequestClose={close}><SafeAreaView style={[s.fill,{backgroundColor:t.bg}]}><View style={[s.row,{padding:14,justifyContent:'space-between'}]}><Heading>库存照片</Heading><Button title="关闭" secondary onPress={close}/></View><ScrollView contentContainerStyle={s.page}>
<Card><ItemIdentity item={row} quantity={row.stockNum} quantityLabel="当前库存"/><RecordMeta label="项目" value={row.projectName}/><RecordMeta label="库区" value={row.areaName}/></Card>
<Note>当前项目、物品、库区关联的业务照片,按上传时间从新到旧展示。</Note><View style={s.row}>{tabs.map(([value,label])=><Button key={value} title={label} secondary={kind!==value} onPress={()=>{setKind(value);setPage(1);}}/>)}</View>
{loading?<Note>正在加载照片…</Note>:error?<><Note>{error}</Note><Button title="重试" secondary onPress={()=>setReload(n=>n+1)}/></>:!photos.length?<Note>暂无相关照片,可在到货、入库或移库时上传。</Note>:<>{[...groups].map(([key,group])=><Card key={key}><Heading>{tabs.find(([kind])=>kind===group.row.kind)?.[1]}照片</Heading><Note>{group.row.documentNo} · {formatDateTime(group.row.businessDate)}</Note><View style={[s.row,{alignItems:'flex-start'}]}>{group.photos.map(({photo,index})=><ProtectedImage key={photo.kind+photo.id} api={api} path={photo.thumbnailPath} label={photo.name} maxBytes={256*1024} gallery={gallery} initialIndex={index}/>)}</View></Card>)}</>}
{!loading&&!error&&total>12&&<View style={[s.row,{justifyContent:'space-between'}]}><Button title="上一页" secondary disabled={page===1} onPress={()=>setPage(n=>n-1)}/><Note>{page}/{Math.ceil(total/12)} · 共{total}张</Note><Button title="下一页" secondary disabled={page*12>=total} onPress={()=>setPage(n=>n+1)}/></View>}
</ScrollView></SafeAreaView></Modal>;
}

View File

@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {operationPayload,validateOperation,runOperations} from '../src/core/stock-operations.ts';
const form={date:'2026-11-25',remark:'',project:null};
const row=()=>({source:{id:7,receiptRoot:true,inNum:5,stockNum:5,projectId:4,productId:3,areaId:1},area:{id:2},quantity:'2',key:'operation-1',status:'editing',error:''});
test('receipt and move accept no photos; each batch row carries only its own selected photo IDs',()=>{
for(const kind of ['move','receive']){
assert.equal(validateOperation(kind,[row()],form),'');assert.equal(operationPayload(kind,row(),form)[0].body.photoIds,undefined);
assert.deepEqual(operationPayload(kind,{...row(),photos:[{id:'photo-a'}]},form)[0].body.photoIds,['photo-a']);
assert.deepEqual(operationPayload(kind,{...row(),photos:[{id:'photo-b'}]},form)[0].body.photoIds,['photo-b']);
assert.ok(validateOperation(kind,[{...row(),photosPending:true}],form));assert.ok(validateOperation(kind,[{...row(),photos:[{error:'failed'}]}],form));assert.ok(validateOperation(kind,[{...row(),photos:Array.from({length:10},(_,i)=>({id:String(i)}))}],form));
}
const legacy={...row(),source:{...row().source,receiptRoot:false}};assert.deepEqual(operationPayload('receive',{...legacy,photos:[{id:'photo-a'}]},form)[1].body.photoIds,['photo-a']);
});
test('uncertain retries retain original photos and do not change the stock request',async()=>{
const calls=[];let rows=await runOperations('move',[{...row(),photos:[{id:'original'}]}],form,async(path,options)=>{calls.push(options.body);throw Error('timeout');},async()=>{});
rows[0].photos=[{id:'replacement'}];await runOperations('move',rows,form,async(path,options)=>calls.push(options.body),async()=>{});
assert.deepEqual(calls[0],calls[1]);assert.deepEqual(calls[1].photoIds,['original']);
});

View File

@ -29,14 +29,16 @@ public class InRecordController extends BaseController
{
@Autowired
private IInRecordService inRecordService;
@Autowired private com.ruoyi.warehouse.service.impl.WarehouseOperationPhotoService operationPhotos;
@Autowired private com.ruoyi.warehouse.service.impl.PendingReceiptService pending;
@PreAuthorize("@ss.hasPermi('warehouse:in:list')") @GetMapping("/pending-groups")
public AjaxResult pendingGroups(InRecord query,@org.springframework.web.bind.annotation.RequestParam(defaultValue="1") int pageNum,@org.springframework.web.bind.annotation.RequestParam(defaultValue="20") int pageSize){return success(pending.page(query,pageNum,pageSize));}
@PreAuthorize("@ss.hasPermi('warehouse:in:list')") @GetMapping("/pending-groups/{key}")
public AjaxResult pendingGroup(@PathVariable String key,InRecord query){return success(pending.group(key,query));}
public record ReceiptRequest(Long areaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark){}
public record ReceiptRequest(Long areaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark,java.util.List<String> photoIds){}
@PreAuthorize("@ss.hasPermi('warehouse:in:confirm')") @PostMapping("/receive/{id}") @Log(title="分次入库",businessType=BusinessType.UPDATE)
public AjaxResult receive(@PathVariable Long id,@RequestBody ReceiptRequest request){return toAjax(inRecordService.receive(id,request.areaId(),request.quantity(),request.key(),getUsername(),request.date(),request.remark()));}
@org.springframework.transaction.annotation.Transactional(rollbackFor=Exception.class)
public AjaxResult receive(@PathVariable Long id,@RequestBody ReceiptRequest request){int result=inRecordService.receive(id,request.areaId(),request.quantity(),request.key(),getUsername(),request.date(),request.remark());operationPhotos.bind("IN",operationPhotos.receiptId(request.key()),request.photoIds());return toAjax(result);}
@PreAuthorize("@ss.hasPermi('warehouse:in:list')")
@GetMapping("/list")
@ -94,9 +96,10 @@ public class InRecordController extends BaseController
@PreAuthorize("@ss.hasPermi('warehouse:in:confirm')")
@Log(title = "确认入库", businessType = BusinessType.UPDATE)
@PutMapping("/confirm/{id}")
public AjaxResult confirm(@PathVariable Long id)
@org.springframework.transaction.annotation.Transactional(rollbackFor=Exception.class)
public AjaxResult confirm(@PathVariable Long id,@RequestBody(required=false) java.util.Map<String,java.util.List<String>> request)
{
return toAjax(inRecordService.confirmInRecord(id, getUsername()));
int result=inRecordService.confirmInRecord(id, getUsername());operationPhotos.bind("IN",id,request==null?null:request.get("photoIds"));return toAjax(result);
}
@PreAuthorize("@ss.hasPermi('warehouse:in:remove')")

View File

@ -36,16 +36,18 @@ public class StockInfoController extends BaseController
@Autowired
private IStockLotService stockLotService;
@Autowired private com.ruoyi.warehouse.service.impl.WarehouseOperationPhotoService operationPhotos;
@Autowired private com.ruoyi.warehouse.service.impl.InventoryCostJournal journal;
public record MoveRequest(Long projectId,Long itemId,Long fromAreaId,Long toAreaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark) {}
public record MoveRequest(Long projectId,Long itemId,Long fromAreaId,Long toAreaId,java.math.BigDecimal quantity,String key,java.time.LocalDate date,String remark,java.util.List<String> photoIds) {}
@PreAuthorize("@ss.hasPermi('warehouse:stock:query')") @GetMapping("/events")
public AjaxResult events(Long projectId,Long itemId) { return success(journal.events(projectId,itemId)); }
@PreAuthorize("@ss.hasPermi('warehouse:stock:query')") @GetMapping("/adjustments")
public AjaxResult adjustments(Long projectId,Long itemId){return success(journal.adjustments(projectId,itemId));}
@PreAuthorize("@ss.hasPermi('warehouse:stock:out') and @ss.hasPermi('project:inventory:use')")
@PostMapping("/move") @Log(title="项目库存移库",businessType=BusinessType.UPDATE)
@org.springframework.transaction.annotation.Transactional(rollbackFor=Exception.class)
public AjaxResult move(@RequestBody MoveRequest request) {
return success(journal.move(request.projectId(),request.itemId(),request.fromAreaId(),request.toAreaId(),request.quantity(),request.key(),request.date(),request.remark()));
var events=journal.move(request.projectId(),request.itemId(),request.fromAreaId(),request.toAreaId(),request.quantity(),request.key(),request.date(),request.remark());operationPhotos.bind("MOVE",events.get(0).getId(),request.photoIds());return success(events);
}
@PreAuthorize("@ss.hasPermi('warehouse:stock:out') and @ss.hasPermi('project:inventory:use')")
@PostMapping("/move/{id}/revoke") @Log(title="撤销移库",businessType=BusinessType.UPDATE)

View File

@ -0,0 +1,12 @@
package com.ruoyi.web.controller.warehouse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.warehouse.service.impl.StockPhotoService;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
@RestController @RequestMapping("/warehouse/stock/{stockId}/photos")
public class StockPhotoController {
private final StockPhotoService photos;public StockPhotoController(StockPhotoService photos){this.photos=photos;}
@GetMapping public AjaxResult page(@PathVariable Long stockId,@RequestParam(defaultValue="ALL") String kind,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="24") int pageSize){return AjaxResult.success(photos.page(stockId,kind,pageNum,pageSize));}
@GetMapping("/{kind}/{id}/content") public ResponseEntity<byte[]> content(@PathVariable Long stockId,@PathVariable String kind,@PathVariable String id){var file=photos.content(stockId,kind,id);return ResponseEntity.ok().cacheControl(CacheControl.noStore()).contentType(MediaType.parseMediaType(file.type())).header("X-Content-Type-Options","nosniff").body(file.bytes());}
@GetMapping("/{kind}/{id}/thumbnail") public ResponseEntity<byte[]> thumbnail(@PathVariable Long stockId,@PathVariable String kind,@PathVariable String id){return ResponseEntity.ok().cacheControl(CacheControl.noStore()).contentType(MediaType.IMAGE_JPEG).header("X-Content-Type-Options","nosniff").body(photos.thumbnail(stockId,kind,id));}
}

View File

@ -0,0 +1,16 @@
package com.ruoyi.web.controller.warehouse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.warehouse.service.impl.WarehouseOperationPhotoService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.*;
@RestController @RequestMapping("/warehouse/operation-photos")
public class WarehouseOperationPhotoController {
private final WarehouseOperationPhotoService photos;
public WarehouseOperationPhotoController(WarehouseOperationPhotoService photos){this.photos=photos;}
@GetMapping("/moves") public AjaxResult moves(@RequestParam Long projectId,@RequestParam Long itemId){return AjaxResult.success(photos.moves(projectId,itemId));}
@PostMapping("/{kind}") public AjaxResult upload(@PathVariable String kind,@RequestParam String uploadId,@RequestParam MultipartFile file){return AjaxResult.success(photos.upload(kind,uploadId,file));}
@GetMapping("/{kind}/{recordId}") public AjaxResult list(@PathVariable String kind,@PathVariable Long recordId){return AjaxResult.success(photos.list(kind,recordId));}
@DeleteMapping("/{id}") public AjaxResult remove(@PathVariable String id){photos.remove(id);return AjaxResult.success();}
@GetMapping("/{id}/content") public ResponseEntity<byte[]> content(@PathVariable String id){var file=photos.content(id);return ResponseEntity.ok().contentType(MediaType.parseMediaType(file.type())).contentLength(file.bytes().length).cacheControl(CacheControl.noStore()).header("X-Content-Type-Options","nosniff").body(file.bytes());}
}

View File

@ -0,0 +1,33 @@
package com.ruoyi.warehouse.service.impl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.warehouse.mapper.StockInfoMapper;
import com.ruoyi.warehouse.domain.StockInfo;
import com.ruoyi.project.service.IProjectInfoService;
import org.junit.jupiter.api.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.*;
class StockPhotosTest {
JdbcTemplate db;StockInfoMapper stocks;IProjectInfoService projects;StockPhotoService service;WarehouseOperationPhotoService operations;org.mockito.MockedStatic<SecurityUtils> security;
final String a="11111111-1111-4111-8111-111111111111",b="22222222-2222-4222-8222-222222222222";
@BeforeEach void setup(){db=new JdbcTemplate(new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa",""));
db.execute("create table warehouse_operation_photo(id varchar(36),kind varchar(8),record_id bigint,name varchar(100),content_type varchar(32),byte_size int,create_time timestamp default current_timestamp)");
db.execute("create table purchase_arrival_photo(id varchar(36),arrival_id bigint,original_name varchar(100),content_type varchar(32),byte_size int,create_time timestamp default current_timestamp)");
db.execute("create table purchase_arrival(id bigint,arrival_no varchar(40),arrival_date date)");
db.execute("create table in_record(id bigint,parent_in_id bigint,arrival_id bigint,source_project_id bigint,product_id bigint,area_id bigint,in_status int,in_no varchar(40),business_date date)");
db.execute("create table inventory_cost_event(id bigint,project_id bigint,item_id bigint,area_id bigint,event_type varchar(20),source_id bigint,event_no varchar(40),business_date date,active int)");
stocks=mock(StockInfoMapper.class);projects=mock(IProjectInfoService.class);operations=mock(WarehouseOperationPhotoService.class);var stock=new StockInfo();stock.setId(1L);stock.setProjectId(4L);stock.setProductId(3L);stock.setAreaId(2L);when(stocks.selectStockInfoById(1L)).thenReturn(stock);
service=new StockPhotoService(db,stocks,projects,operations,mock(PurchaseArrivalPhotoService.class));security=mockStatic(SecurityUtils.class);security.when(()->SecurityUtils.hasPermi("warehouse:stock:list")).thenReturn(true);
db.update("insert into in_record values(7,null,9,4,3,2,1,'RK7',current_date),(8,null,null,5,3,2,1,'RK8',current_date)");db.update("insert into warehouse_operation_photo(id,kind,record_id,name,content_type,byte_size) values(?,'IN',7,'入库.jpg','image/jpeg',12),(?,'IN',8,'其他项目.jpg','image/jpeg',12)",a,b);
}
@AfterEach void close(){security.close();}
@Test void pageOnlyIncludesMatchingProjectItemAndAreaAndNeverLoadsOriginalBytes(){var page=service.page(1L,"ALL",1,24);assertEquals(1L,page.get("total"));var rows=(java.util.List<?>)page.get("rows");assertEquals(a,((Map<?,?>)rows.get(0)).get("id"));verifyNoInteractions(operations);verify(projects).requireProjectAccess(4L);assertEquals(0L,service.page(1L,"MOVE",1,24).get("total"));}
@Test void privateOriginalCannotBeRequestedForAnotherStockOrDraft(){assertThrows(ServiceException.class,()->service.content(1L,"IN",b));db.update("update warehouse_operation_photo set record_id=null where id=?",a);assertThrows(ServiceException.class,()->service.content(1L,"IN",a));verifyNoInteractions(operations);}
@Test void arrivalPhotoInheritedFromReceiptRootIsDeduplicatedAcrossPartialReceipts(){db.update("insert into purchase_arrival values(9,'DH9',current_date)");db.update("insert into purchase_arrival_photo(id,arrival_id,original_name,content_type,byte_size) values(?,9,'到货.jpg','image/jpeg',10)",b);db.update("insert into in_record values(10,7,null,4,3,2,1,'RK10',current_date),(11,7,null,4,3,2,1,'RK11',current_date)");assertEquals(1L,service.page(1L,"ARRIVAL",1,24).get("total"));db.update("update in_record set in_status=0");assertEquals(0L,service.page(1L,"ALL",1,24).get("total"));}
@Test void incomingMoveShowsSourceEvidenceAndInactiveMoveIsExcluded(){db.update("insert into inventory_cost_event values(20,4,3,1,'ISSUE',null,'LS20',current_date,1),(21,4,3,2,'RETURN',20,'LS21',current_date,1)");db.update("insert into warehouse_operation_photo(id,kind,record_id,name,content_type,byte_size) values(?,'MOVE',20,'移库.jpg','image/jpeg',10)",b);assertEquals(1L,service.page(1L,"MOVE",1,24).get("total"));db.update("update inventory_cost_event set active=0");assertEquals(0L,service.page(1L,"MOVE",1,24).get("total"));}
@Test void thumbnailIsBoundedCachedAndAuthorizationIsRechecked()throws Exception{var out=new java.io.ByteArrayOutputStream();javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(1000,500,java.awt.image.BufferedImage.TYPE_INT_RGB),"png",out);when(operations.contentForStock(a)).thenReturn(new WarehouseOperationPhotoService.Content(out.toByteArray(),"image/png","image.png"));byte[] thumb=service.thumbnail(1L,"IN",a);var image=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(thumb));assertTrue(image.getWidth()<=240);assertTrue(thumb.length<256*1024);assertArrayEquals(thumb,service.thumbnail(1L,"IN",a));verify(operations,times(1)).contentForStock(a);db.update("update in_record set in_status=0 where id=7");assertThrows(ServiceException.class,()->service.thumbnail(1L,"IN",a));}
@Test void readOnlyStockPermissionWorksButMissingPermissionIsDenied(){assertEquals(1L,service.page(1L,"IN",1,24).get("total"));security.when(()->SecurityUtils.hasPermi("warehouse:stock:list")).thenReturn(false);assertThrows(ServiceException.class,()->service.page(1L,"ALL",1,24));}
}

View File

@ -0,0 +1,55 @@
package com.ruoyi.warehouse.service.impl;
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.project.service.IProjectInfoService;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.*;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.mock.web.MockMultipartFile;
import java.nio.file.Path;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class WarehouseOperationPhotosTest {
@TempDir Path temp;JdbcTemplate db;TransactionTemplate tx;WarehouseOperationPhotoService service;org.mockito.MockedStatic<SecurityUtils> security;BusinessFileStorage storage;Map<String,byte[]> files=new HashMap<>();
final String a="11111111-1111-4111-8111-111111111111",b="22222222-2222-4222-8222-222222222222";
@BeforeEach void setup()throws Exception{
var ds=new DriverManagerDataSource("jdbc:h2:mem:"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1","sa","");db=new JdbcTemplate(ds);tx=new TransactionTemplate(new DataSourceTransactionManager(ds));
db.execute("create table sys_user(user_id bigint primary key)");db.update("insert into sys_user values(1)");
db.execute("create table warehouse_operation_photo(id varchar(36) primary key,kind varchar(8),record_id bigint,owner_id bigint,name varchar(255),content_type varchar(64),byte_size int,sha256 varchar(64),create_time timestamp default current_timestamp)");
db.execute("create table in_record(id bigint primary key,source_project_id bigint)");db.update("insert into in_record values(7,4)");
db.execute("create table inventory_cost_event(id bigint primary key,project_id bigint,event_type varchar(20),source_id bigint)");db.update("insert into inventory_cost_event values(9,4,'ISSUE',null),(10,4,'RETURN',9)");
storage=mock(BusinessFileStorage.class);doAnswer(inv->{files.put(inv.getArgument(0),inv.getArgument(1));return null;}).when(storage).save(anyString(),any(byte[].class),anyString(),any(Path.class));when(storage.read(anyString(),any(Path.class),anyInt())).thenAnswer(inv->files.get(inv.getArgument(0)));
service=new WarehouseOperationPhotoService(db,storage,mock(BusinessNumberService.class),mock(IProjectInfoService.class));new RuoYiConfig().setProfile(temp.toString());
security=mockStatic(SecurityUtils.class);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(true);
}
@AfterEach void close(){security.close();}
MockMultipartFile image()throws Exception{var out=new java.io.ByteArrayOutputStream();javax.imageio.ImageIO.write(new java.awt.image.BufferedImage(2,2,java.awt.image.BufferedImage.TYPE_INT_RGB),"png",out);return new MockMultipartFile("file","手机照片.jpg","image/jpeg",out.toByteArray());}
void upload(String kind,String id)throws Exception{var file=image();tx.execute(s->service.upload(kind,id,file));}
@Test void photosAreOptionalAndCommittedEvidenceIsReadableButImmutable()throws Exception{
tx.execute(s->{service.bind("IN",7L,null);return null;});assertTrue(service.list("IN",7L).isEmpty());
upload("IN",a);tx.execute(s->{service.bind("IN",7L,List.of(a));return null;});assertEquals(1,service.list("IN",7L).size());assertEquals("image/png",service.content(a).type());assertThrows(ServiceException.class,()->tx.execute(s->{service.remove(a);return null;}));
}
@Test void bindingFailureRollsBackAllSelectedPhotos()throws Exception{
upload("IN",a);assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("IN",7L,List.of(a,b));return null;}));assertNull(db.queryForObject("select record_id from warehouse_operation_photo where id=?",Long.class,a));
}
@Test void replayRequiresTheSamePhotosAndCrossOperationReuseIsRejected()throws Exception{
upload("MOVE",a);tx.execute(s->{service.bind("MOVE",9L,List.of(a));return null;});tx.execute(s->{service.bind("MOVE",9L,List.of(a));return null;});assertEquals(1,service.list("MOVE",10L).size());
assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("MOVE",9L,List.of());return null;}));assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("IN",7L,List.of(a));return null;}));
}
@Test void countDuplicateForeignAndPermissionGuardsAreEnforced()throws Exception{
upload("IN",a);assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("IN",7L,Collections.nCopies(10,a));return null;}));assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("IN",7L,List.of(a,a));return null;}));
security.when(SecurityUtils::getUserId).thenReturn(2L);assertThrows(ServiceException.class,()->service.content(a));assertThrows(ServiceException.class,()->tx.execute(s->{service.bind("IN",7L,List.of(a));return null;}));
security.when(()->SecurityUtils.hasPermi(anyString())).thenReturn(false);assertThrows(ServiceException.class,()->service.list("IN",7L));
}
@Test void invalidContentAndOver50MbAreRejectedAndValidRetriesAreIdempotent()throws Exception{
var tooBig=new MockMultipartFile("file","large.jpg","image/jpeg",new byte[]{1}){@Override public long getSize(){return 50L*1024*1024+1;}};
assertThrows(ServiceException.class,()->tx.execute(s->service.upload("IN",a,tooBig)));
assertThrows(ServiceException.class,()->tx.execute(s->service.upload("IN",a,new MockMultipartFile("file","fake.png","image/png",new byte[]{1,2,3}))));
upload("IN",a);upload("IN",a);assertEquals(1,db.queryForObject("select count(*) from warehouse_operation_photo",Integer.class));verify(storage,times(1)).save(anyString(),any(byte[].class),anyString(),any(Path.class));
}
}

View File

@ -89,6 +89,9 @@ public class PurchaseArrivalPhotoService {
catch(IOException e){throw new ServiceException("照片读取失败,请稍后重试");}
}
// Caller must first verify that the photo belongs to an authorized stock receipt.
Content contentForStock(String photoId){validId(photoId);var row=db.queryForMap("select * from purchase_arrival_photo where id=?",photoId);try{byte[] bytes=storage.read(key(photoId),path(photoId),MAX_BYTES);if(bytes.length!=number(row,"byte_size")||!digest(bytes).equals(row.get("sha256")))throw new IOException();return new Content(bytes,row.get("content_type").toString(),row.get("original_name").toString());}catch(IOException e){throw new ServiceException("照片读取失败");}}
@Transactional
public void removeDraft(String id){
permission(true);validId(id);

View File

@ -0,0 +1,48 @@
package com.ruoyi.warehouse.service.impl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.service.IProjectInfoService;
import com.ruoyi.warehouse.domain.StockInfo;
import com.ruoyi.warehouse.mapper.StockInfoMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
/** Scoped evidence gallery. Stock quantities and the original evidence remain untouched. */
@Service public class StockPhotoService {
private final Map<String,byte[]> thumbnails=Collections.synchronizedMap(new LinkedHashMap<String,byte[]>(128,.75f,true){@Override protected boolean removeEldestEntry(Map.Entry<String,byte[]> e){return size()>128;}});
private final java.util.concurrent.Semaphore thumbnailSlots=new java.util.concurrent.Semaphore(3);
private final String evidence;
private final JdbcTemplate db;private final StockInfoMapper stocks;private final IProjectInfoService projects;private final WarehouseOperationPhotoService operations;private final PurchaseArrivalPhotoService arrivals;
public StockPhotoService(JdbcTemplate db,StockInfoMapper stocks,IProjectInfoService projects,WarehouseOperationPhotoService operations,PurchaseArrivalPhotoService arrivals){this.db=db;this.stocks=stocks;this.projects=projects;this.operations=operations;this.arrivals=arrivals;
boolean mysql=Boolean.TRUE.equals(db.execute((org.springframework.jdbc.core.ConnectionCallback<Boolean>) c->c.getMetaData().getDatabaseProductName().equalsIgnoreCase("MySQL")));
// Imported receipt tables can use a different collation. Normalize only gallery text expressions.
this.evidence=mysql?java.util.regex.Pattern.compile("p\\.id\\b|p\\.original_name\\b|p\\.name\\b|p\\.content_type\\b|a\\.arrival_no\\b|ir\\.in_no\\b|e\\.event_no\\b").matcher(EVIDENCE).replaceAll(m->"CONVERT("+m.group()+" USING utf8mb4) COLLATE utf8mb4_unicode_ci"):EVIDENCE;
}
private StockInfo stock(Long id){if(!SecurityUtils.hasPermi("warehouse:stock:list"))throw new ServiceException("没有库存照片查看权限",403);StockInfo stock=stocks.selectStockInfoById(id);if(stock==null)throw new ServiceException("库存记录不存在",404);projects.requireProjectAccess(stock.getProjectId());return stock;}
private static final String EVIDENCE="select distinct p.id id,p.original_name name,p.content_type contentType,p.byte_size size,'ARRIVAL' kind,a.id recordId,a.arrival_no documentNo,a.arrival_date businessDate,p.create_time sort_time from purchase_arrival_photo p join purchase_arrival a on a.id=p.arrival_id join in_record ir on coalesce(ir.arrival_id,(select root.arrival_id from in_record root where root.id=ir.parent_in_id))=a.id where ir.source_project_id=? and ir.product_id=? and ir.area_id=? and ir.in_status=1 "
+"union all select p.id id,p.name,p.content_type,p.byte_size,'IN',ir.id,ir.in_no,ir.business_date,p.create_time from warehouse_operation_photo p join in_record ir on ir.id=p.record_id where p.kind='IN' and ir.source_project_id=? and ir.product_id=? and ir.area_id=? and ir.in_status=1 "
+"union all select p.id id,p.name,p.content_type,p.byte_size,'MOVE',e.id,e.event_no,e.business_date,p.create_time from warehouse_operation_photo p join inventory_cost_event e on (e.id=p.record_id or (e.source_id=p.record_id and e.event_type='RETURN')) where p.kind='MOVE' and e.project_id=? and e.item_id=? and e.area_id=? and e.active=1";
private java.util.List<Object> args(StockInfo s){var args=new ArrayList<Object>();for(int i=0;i<3;i++){args.add(s.getProjectId());args.add(s.getProductId());args.add(s.getAreaId());}return args;}
private String kind(String value){if(value==null||value.isBlank()||"ALL".equals(value))return "ALL";if(!Set.of("IN","MOVE","ARRIVAL").contains(value))throw new ServiceException("照片来源无效");return value;}
public Map<String,Object> page(Long stockId,String filter,int page,int size){StockInfo stock=stock(stockId);String selected=kind(filter);size=Math.max(1,Math.min(36,size));page=Math.max(1,page);var args=args(stock);String sql="select * from ("+evidence+") evidence";if(!"ALL".equals(selected)){sql+=" where kind=?";args.add(selected);}long total=db.queryForObject("select count(*) from ("+sql+") photos",Long.class,args.toArray());args.add(size);args.add((page-1L)*size);
var rows=db.queryForList(sql+" order by sort_time desc,kind,id desc limit ? offset ?",args.toArray());for(var row:rows){String path="/warehouse/stock/"+stockId+"/photos/"+row.get("kind")+"/"+row.get("id");row.put("contentPath",path+"/content");row.put("thumbnailPath",path+"/thumbnail");}
var identity=new LinkedHashMap<String,Object>();identity.put("productName",stock.getProductName());identity.put("brand",stock.getBrand());identity.put("spec",stock.getSpec());identity.put("projectName",stock.getProjectName());identity.put("areaName",stock.getAreaName());identity.put("unit",stock.getUnit());identity.put("stockNum",stock.getStockNum());return Map.of("rows",rows,"total",total,"pageNum",page,"pageSize",size,"stock",identity);
}
private void authorizePhoto(Long stockId,String source,String id){StockInfo stock=stock(stockId);String kind=kind(source);if("ALL".equals(kind)||id==null||!id.matches("[0-9a-f-]{36}"))throw new ServiceException("照片标识无效");var args=args(stock);args.add(kind);args.add(id);if(db.queryForObject("select count(*) from ("+evidence+") evidence where kind=? and id=?",Long.class,args.toArray())==0)throw new ServiceException("照片不属于本条库存的相关业务",404);}
private WarehouseOperationPhotoService.Content readPhoto(String kind,String id){if("ARRIVAL".equals(kind)){var file=arrivals.contentForStock(id);return new WarehouseOperationPhotoService.Content(file.bytes(),file.type(),file.name());}return operations.contentForStock(id);}
public WarehouseOperationPhotoService.Content content(Long stockId,String source,String id){authorizePhoto(stockId,source,id);return readPhoto(source,id);}
public byte[] thumbnail(Long stockId,String source,String id){authorizePhoto(stockId,source,id);String cacheKey=source+id;byte[] cached=thumbnails.get(cacheKey);if(cached!=null)return cached;
try{thumbnailSlots.acquire();}catch(InterruptedException e){Thread.currentThread().interrupt();throw new ServiceException("缩略图生成已取消");}
try{cached=thumbnails.get(cacheKey);if(cached!=null)return cached;byte[] result=makeThumbnail(readPhoto(source,id));thumbnails.put(cacheKey,result);return result;}finally{thumbnailSlots.release();}}
private byte[] makeThumbnail(WarehouseOperationPhotoService.Content file){BufferedImage image=null;
try(var input=new MemoryCacheImageInputStream(new ByteArrayInputStream(file.bytes()))){var readers=ImageIO.getImageReaders(input);if(readers.hasNext()){var reader=readers.next();try{reader.setInput(input,true,true);int sample=Math.max(1,Math.max(reader.getWidth(0),reader.getHeight(0))/240);var params=reader.getDefaultReadParam();params.setSourceSubsampling(sample,sample,0,0);image=reader.read(0,params);}finally{reader.dispose();}}}catch(Exception ignored){}
int width=image==null?160:Math.max(1,(int)(image.getWidth()*Math.min(1d,240d/Math.max(image.getWidth(),image.getHeight())))),height=image==null?120:Math.max(1,(int)(image.getHeight()*Math.min(1d,240d/Math.max(image.getWidth(),image.getHeight()))));var preview=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);var g=preview.createGraphics();try{g.setColor(Color.WHITE);g.fillRect(0,0,width,height);if(image!=null){g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);g.drawImage(image,0,0,width,height,null);}else{g.setColor(Color.GRAY);g.drawRect(52,28,54,54);g.drawString("IMAGE",59,101);}}finally{g.dispose();if(image!=null)image.flush();}
try(var out=new ByteArrayOutputStream()){ImageIO.write(preview,"jpg",out);preview.flush();return out.toByteArray();}catch(IOException e){throw new ServiceException("缩略图生成失败");}
}
}

View File

@ -0,0 +1,94 @@
package com.ruoyi.warehouse.service.impl;
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.project.service.IProjectInfoService;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;
/** Owner-private drafts are atomically bound to the immutable operation, never to aggregate stock. */
@Service
public class WarehouseOperationPhotoService {
public static final int MAX_BYTES=50*1024*1024,MAX_PHOTOS=9;
private final JdbcTemplate db;private final BusinessFileStorage storage;private final BusinessNumberService numbers;private final IProjectInfoService projects;
public WarehouseOperationPhotoService(JdbcTemplate db,BusinessFileStorage storage,BusinessNumberService numbers,IProjectInfoService projects){this.db=db;this.storage=storage;this.numbers=numbers;this.projects=projects;}
public record Content(byte[] bytes,String type,String name){}
private static void id(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("照片标识无效");}
private static void permission(String kind,boolean write){
boolean allowed=switch(kind){case "IN"->SecurityUtils.hasPermi(write?"warehouse:in:confirm":"warehouse:in:list");case "MOVE"->write?SecurityUtils.hasPermi("warehouse:stock:out")&&SecurityUtils.hasPermi("project:inventory:use"):SecurityUtils.hasPermi("warehouse:stock:query");default->false;};
if(!allowed)throw new ServiceException("没有操作照片的权限",403);
}
private static long number(Map<String,Object> r,String key){return ((Number)r.get(key)).longValue();}
private static String key(String id){return "purchase/warehouse-operation-"+id+".bin";}
private static Path path(String id){
var profile=Path.of(RuoYiConfig.getProfile()).toAbsolutePath().normalize();var root=profile.resolveSibling(".warehouse-operation-photos-private");
try{Files.createDirectories(root);if(Files.isSymbolicLink(root)||root.toRealPath().startsWith(Files.exists(profile)?profile.toRealPath():profile))throw new java.io.IOException();
// Keep older development files readable while removing them from the public upload directory.
var target=root.resolve(id+".bin");var legacy=profile.resolve("private/warehouse-operation-photos").resolve(id+".bin");
if(!Files.exists(target)&&Files.isRegularFile(legacy,LinkOption.NOFOLLOW_LINKS)&&legacy.toRealPath().startsWith(profile.toRealPath()))Files.move(legacy,target);
return target;
}catch(java.io.IOException e){throw new ServiceException("照片私有存储暂不可用");}
}
private static String hash(byte[] bytes){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));}catch(Exception e){throw new IllegalStateException(e);}}
private Map<String,Object> view(Map<String,Object> r){return Map.of("id",r.get("id"),"name",r.get("name"),"contentType",r.get("content_type"),"size",r.get("byte_size"));}
@Transactional(rollbackFor=Exception.class)
public Map<String,Object> upload(String kind,String uploadId,MultipartFile file){
permission(kind,true);id(uploadId);
if(file==null||file.isEmpty()||file.getSize()>MAX_BYTES)throw new ServiceException("每张照片不能为空且不能超过50MB");
byte[] bytes;try(var in=file.getInputStream()){bytes=in.readNBytes(MAX_BYTES+1);}catch(Exception e){throw new ServiceException("照片读取失败");}
if(bytes.length==0||bytes.length>MAX_BYTES)throw new ServiceException("每张照片不能超过50MB");
var prepared=ArrivalPhotoImages.prepare(bytes,MAX_BYTES);bytes=prepared.bytes();String digest=hash(bytes);
db.queryForList("select user_id from sys_user where user_id=? for update",SecurityUtils.getUserId());
var existing=db.queryForList("select * from warehouse_operation_photo where id=? for update",uploadId);
if(!existing.isEmpty()){var old=existing.get(0);if(number(old,"owner_id")!=SecurityUtils.getUserId()||!kind.equals(old.get("kind"))||!digest.equals(old.get("sha256")))throw new ServiceException("照片上传标识已被使用");return view(old);}
if(db.queryForObject("select count(*) from warehouse_operation_photo where owner_id=? and record_id is null",Integer.class,SecurityUtils.getUserId())>=90)throw new ServiceException("未提交照片较多,请先完成或移除已有照片");
String name=ArrivalPhotoImages.name(file.getOriginalFilename(),prepared.extension());
db.update("insert into warehouse_operation_photo(id,kind,owner_id,name,content_type,byte_size,sha256) values(?,?,?,?,?,?,?)",uploadId,kind,SecurityUtils.getUserId(),name,prepared.type(),bytes.length,digest);
// Reserve the unique ID before writing bytes, preventing concurrent requests from overwriting evidence.
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCompletion(int status){if(status!=STATUS_COMMITTED)storage.discardFailedUpload(key(uploadId),path(uploadId));}});
try{storage.save(key(uploadId),bytes,prepared.type(),path(uploadId));}catch(Exception e){throw new ServiceException("照片保存失败,请重试");}
return view(db.queryForMap("select * from warehouse_operation_photo where id=?",uploadId));
}
public Long receiptId(String requestKey){
String no=numbers.lookup("IN","receipt:"+requestKey);
var ids=db.queryForList("select id from in_record where in_no=? or in_no=?",Long.class,no,"RIN-"+UUID.nameUUIDFromBytes(requestKey.getBytes(java.nio.charset.StandardCharsets.UTF_8)));
if(ids.size()!=1)throw new ServiceException("未找到本次入库记录");return ids.get(0);
}
public void bind(String kind,Long recordId,List<String> input){
permission(kind,true);var ids=input==null?List.<String>of():new ArrayList<>(input);
if(ids.size()>MAX_PHOTOS||new HashSet<>(ids).size()!=ids.size())throw new ServiceException("每次操作最多9张照片,不能重复选择");ids.forEach(WarehouseOperationPhotoService::id);
var prior=db.queryForList("select id from warehouse_operation_photo where kind=? and record_id=? order by id",String.class,kind,recordId);
if(!prior.isEmpty()){if(!new TreeSet<>(prior).equals(new TreeSet<>(ids)))throw new ServiceException("重复提交的照片与原记录不一致");return;}
for(String photo:ids.stream().sorted().toList()){
var rows=db.queryForList("select * from warehouse_operation_photo where id=? for update",photo);
if(rows.isEmpty()||number(rows.get(0),"owner_id")!=SecurityUtils.getUserId()||!kind.equals(rows.get(0).get("kind"))||rows.get(0).get("record_id")!=null)throw new ServiceException("照片不存在、已被使用或不属于本次操作");
db.update("update warehouse_operation_photo set record_id=? where id=?",recordId,photo);
}
}
public List<Map<String,Object>> moves(Long projectId,Long itemId){permission("MOVE",false);projects.requireProjectAccess(projectId);return db.queryForList("select e.id,e.event_no,e.business_date,e.quantity from inventory_cost_event e where e.project_id=? and e.item_id=? and exists(select 1 from warehouse_operation_photo p where p.kind='MOVE' and p.record_id=e.id) order by e.id desc",projectId,itemId);}
public List<Map<String,Object>> list(String kind,Long recordId){permission(kind,false);requireRecord(kind,recordId);if("MOVE".equals(kind)){var event=db.queryForMap("select event_type,source_id from inventory_cost_event where id=?",recordId);if("RETURN".equals(event.get("event_type"))&&event.get("source_id")!=null)recordId=number(event,"source_id");}return db.queryForList("select * from warehouse_operation_photo where kind=? and record_id=? order by create_time,id",kind,recordId).stream().map(this::view).toList();}
private void requireRecord(String kind,Long recordId){
var rows=db.queryForList("IN".equals(kind)?"select source_project_id project_id from in_record where id=?":"select project_id from inventory_cost_event where id=?",recordId);
if(rows.isEmpty())throw new ServiceException("业务记录不存在",404);
if(rows.get(0).get("project_id")!=null)projects.requireProjectAccess(number(rows.get(0),"project_id"));
}
public Content content(String photoId){
id(photoId);var rows=db.queryForList("select * from warehouse_operation_photo where id=?",photoId);if(rows.isEmpty())throw new ServiceException("照片不存在",404);var row=rows.get(0);String kind=(String)row.get("kind");
if(row.get("record_id")==null){permission(kind,true);if(number(row,"owner_id")!=SecurityUtils.getUserId())throw new ServiceException("不能读取他人的草稿",403);}else{permission(kind,false);requireRecord(kind,number(row,"record_id"));}
try{byte[] bytes=storage.read(key(photoId),path(photoId),MAX_BYTES);if(bytes.length!=number(row,"byte_size")||!hash(bytes).equals(row.get("sha256")))throw new IllegalStateException();return new Content(bytes,(String)row.get("content_type"),(String)row.get("name"));}catch(Exception e){throw new ServiceException("照片读取失败");}
}
// Package-private: only StockPhotoService may call this after checking stock/photo membership.
Content contentForStock(String photoId){id(photoId);var row=db.queryForMap("select * from warehouse_operation_photo where id=?",photoId);try{byte[] bytes=storage.read(key(photoId),path(photoId),MAX_BYTES);if(bytes.length!=number(row,"byte_size")||!hash(bytes).equals(row.get("sha256")))throw new IllegalStateException();return new Content(bytes,(String)row.get("content_type"),(String)row.get("name"));}catch(Exception e){throw new ServiceException("照片读取失败");}}
@Transactional public void remove(String photoId){id(photoId);var rows=db.queryForList("select * from warehouse_operation_photo where id=? for update",photoId);if(rows.isEmpty())return;var row=rows.get(0);permission((String)row.get("kind"),true);if(number(row,"owner_id")!=SecurityUtils.getUserId()||row.get("record_id")!=null)throw new ServiceException("仅可移除自己未提交的照片",403);db.update("delete from warehouse_operation_photo where id=?",photoId);discard(photoId);}
private void discard(String photoId){TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){@Override public void afterCommit(){storage.discardFailedUpload(key(photoId),path(photoId));}});}
@Scheduled(fixedDelay=3600000,initialDelay=3600000) @Transactional public void expireDrafts(){for(String photoId:db.queryForList("select id from warehouse_operation_photo where record_id is null and create_time<date_sub(now(),interval 7 day) limit 100",String.class)){if(db.update("delete from warehouse_operation_photo where id=? and record_id is null and create_time<date_sub(now(),interval 7 day)",photoId)==1)discard(photoId);}}
}

View File

@ -20,8 +20,8 @@ export function delInRecord(id) {
return request({ url: '/warehouse/in/' + id, method: 'delete' })
}
export function confirmInRecord(id) {
return request({ url: '/warehouse/in/confirm/' + id, method: 'put' })
export function confirmInRecord(id, data) {
return request({ url: '/warehouse/in/confirm/' + id, method: 'put', data })
}
export function receiveInRecord(id, data) {

View File

@ -0,0 +1,10 @@
import request from '@/utils/request'
import {prepareArrivalPhoto} from '@/utils/arrival-photo-format'
export function operationPhotoError(file){
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 '请选择图片文件'
return !file.size||file.size>50*1024*1024?'每张照片不能超过50MB':''
}
export async function uploadOperationPhoto(kind,id,file,signal){file=await prepareArrivalPhoto(file,signal,undefined,50*1024*1024);const data=new FormData();data.append('file',file);data.append('uploadId',id);return request({url:'/warehouse/operation-photos/'+kind,method:'post',data,signal,timeout:120000,headers:{'Content-Type':'multipart/form-data',repeatSubmit:false}})}
export const removeOperationPhoto=id=>request({url:'/warehouse/operation-photos/'+id,method:'delete'})
export const readOperationPhoto=(id,signal)=>request({url:'/warehouse/operation-photos/'+id+'/content',responseType:'blob',signal})
export const listOperationPhotos=(kind,id)=>request({url:'/warehouse/operation-photos/'+kind+'/'+id})

View File

@ -0,0 +1,52 @@
<template>
<span v-if="compact" class="arrival-photos-trigger"><el-button v-if="canUpload||modelValue.length||recordId" link type="primary" :disabled="disabled&&!readonly" @click="open=true">{{ supplementable?'查看 / 补录照片':readonly?'查看照片':'操作照片' }}<span v-if="modelValue.length">({{ modelValue.length }})</span><span v-else-if="!readonly">{{ 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/*,.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?'上传后自动保存':'选传'}} · {{ modelValue.length }}/9 张 · 每张不超过50MB</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||'操作照片'"/>
<button v-else type="button" class="arrival-photo-placeholder" :disabled="loading[photo.id]" @click="load(photo)">{{ loading[photo.id]?'正在加载…':loadErrors[photo.id]?'加载失败,点击重试':'加载照片' }}</button>
<span class="arrival-photo-name" :title="photo.name">{{ photo.name }}</span>
<div v-if="photo.uploading" class="arrival-photo-status" role="status">正在上传…</div>
<div v-if="photo.error" class="arrival-photo-status is-error" role="alert">{{ photo.error }}<el-button v-if="photo.raw" link type="danger" :disabled="disabled||busy" @click="upload(photo)">重试</el-button></div>
<div v-if="loadErrors[photo.id]" class="arrival-photo-status is-error" role="alert">{{ loadErrors[photo.id] }}</div>
<el-button v-if="!readonly||supplementable&&!photo.id" class="arrival-photo-remove" size="small" :disabled="disabled||photo.uploading" @click="remove(photo)">移除</el-button>
</article>
</div>
<p v-else-if="readonly" class="arrival-photos-empty">本次操作未上传照片</p>
</section>
<template v-if="compact" #footer><el-button :disabled="busy" @click="open=false">完成</el-button></template>
</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'
import {operationPhotoError,uploadOperationPhoto,removeOperationPhoto,readOperationPhoto,listOperationPhotos} from '@/api/warehouse/operation-photos'
import {purchaseUploadId} from '@/utils/purchase-documents'
const props=defineProps({modelValue:{type:Array,default:()=>[]},kind:{type:String,required:true},recordId:[Number,String],readonly:Boolean,supplementable:Boolean,arrivalId:[Number,String],disabled:Boolean,compact:Boolean,title:String})
const emit=defineEmits(['update:modelValue','pending'])
const input=ref(),open=ref(false),resources=ref({}),loading=ref({}),loadErrors=ref({}),active=new Set(),ownedUrls=new Set()
let disposed=false,listSequence=0
const canUpload=computed(()=>!props.readonly||props.supplementable)
const busy=computed(()=>props.modelValue.some(p=>p.uploading)),pending=computed(()=>canUpload.value&&props.modelValue.some(p=>!p.id||p.uploading||p.error&&p.raw))
watch(pending,v=>emit('pending',v),{immediate:true})
function update(photo,patch){if(!disposed)emit('update:modelValue',props.modelValue.map(p=>(p.clientKey||p.id)===(photo.clientKey||photo.id)?{...p,...patch}:p))}
function url(photo){return photo.localUrl&&ownedUrls.has(photo.localUrl)?photo.localUrl:resources.value[photo.id||photo.clientKey]||''}
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=operationPhotoError(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 prepared=await prepareArrivalPhoto(photo.raw,ctl.signal,undefined,50*1024*1024);if(prepared!==photo.raw)update(photo,{raw:prepared,name:prepared.name,localUrl:own(prepared)});const result=await uploadOperationPhoto(props.kind,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 removeOperationPhoto(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 readOperationPhoto(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})
watch(()=>props.modelValue,rows=>{const ids=new Set(rows.map(p=>p.id||p.clientKey));resources.value=Object.fromEntries(Object.entries(resources.value).filter(([id])=>ids.has(id)));const keep=new Set([...rows.map(p=>p.localUrl),...Object.values(resources.value)]);for(const value of ownedUrls)if(!keep.has(value)){URL.revokeObjectURL(value);ownedUrls.delete(value)}})
onBeforeUnmount(()=>{disposed=true;active.forEach(c=>c.abort());ownedUrls.forEach(u=>URL.revokeObjectURL(u))})
watch(()=>[props.kind,props.recordId,open.value],async()=>{const sequence=++listSequence;if(props.readonly&&props.recordId&&(!props.compact||open.value)){try{const result=await listOperationPhotos(props.kind,props.recordId);if(!disposed&&sequence===listSequence)emit('update:modelValue',result.data||[])}catch(e){ElMessage.error(e.message||'照片加载失败')}}},{immediate:true})
defineExpose({pending,busy})
</script>
<style scoped>
.arrival-photos{width:100%;min-width:0}.arrival-photos-toolbar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:4px 0 12px}.arrival-photos-toolbar>span,.arrival-photos-empty{font-size:12px;color:var(--el-text-color-secondary)}.arrival-photos-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:12px}.arrival-photo{position:relative;min-width:0;padding:8px;border:1px solid var(--el-border-color-lighter);border-radius:8px;background:var(--el-bg-color)}.arrival-photo :deep(.el-image){display:block;width:100%;height:100px;border-radius:5px}.arrival-photo-name{display:block;font-size:12px;line-height:1.6;margin-top:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.arrival-photo-status{font-size:12px;line-height:1.6;color:var(--el-color-primary);overflow-wrap:anywhere}.arrival-photo-status .el-button{margin-left:6px}.is-error{color:var(--el-color-danger)}.is-failed{border-color:var(--el-color-danger-light-5)}.arrival-photo-remove{margin-top:6px;width:100%}.arrival-photo-placeholder{width:100%;height:100px;border:0;border-radius:5px;color:var(--el-text-color-secondary);background:var(--el-fill-color-light);cursor:pointer}.arrival-photos-trigger :deep(.el-button){white-space:normal;height:auto;line-height:1.5}
</style>

View File

@ -26,6 +26,7 @@
<el-input v-model="remark" maxlength="500" placeholder="选填,记录本次操作说明"/>
</el-form-item>
</el-form>
<p v-if="kind==='MOVE'" class="stock-card-meta">照片选填,每项最多9张,每张不超过50MB;不上传也可移库。</p>
<batch-progress v-if="runRows.length" :total="runRows.length" :completed="completedCount" :failed="failedCount" :running="saving" v-model:onlyFailed="onlyFailed"/>
<div v-else class="stock-quantity-toolbar"><span class="stock-selection-summary">待处理 <strong>{{ rows.length }}</strong> 项库存</span><el-button v-if="kind==='USE'&&!taskContext" type="primary" plain size="small" :disabled="saving||!fillableRows.length" @click="fillAvailableQuantities">全部填入可用数量</el-button></div>
</template>
@ -43,7 +44,7 @@
<el-form-item label="本次数量">
<el-input-number v-model="row.quantity" :min="0" :max="Number(row.stockNum)" :precision="4" :controls="false" :disabled="saving||row.done"/>
</el-form-item>
</el-form>
<el-form-item v-if="kind==='MOVE'" label="移库照片(选填)"><operation-photos kind="MOVE" v-model="row.photos" :disabled="saving||row.done" @pending="row.photosPending=$event"/></el-form-item></el-form>
<div v-if="kind==='ISSUE'" class="stock-card-meta">生产任务:{{ taskContext ? taskContext.item_name+' / '+taskContext.task_no : '-' }}</div>
<div v-if="row.result" class="stock-row-result" :class="{failed:row.failed}" role="status">{{ row.result }}</div>
</div>
@ -59,7 +60,7 @@
<el-table-column label="库存类型" width="110" show-overflow-tooltip>
<template #default="s">{{ s.row.finishedProduct ? '成品' : '物料 / 零件' }}</template>
</el-table-column>
<el-table-column prop="stockNum" :label="runRows.length?'操作前可用':'可用数量'" width="100" align="right" show-overflow-tooltip/>
<el-table-column v-if="kind==='MOVE'" label="移库照片(选填)" width="160" class-name="business-control-cell"><template #default="{row}"><operation-photos kind="MOVE" v-model="row.photos" :disabled="saving||row.done" compact @pending="row.photosPending=$event"/></template></el-table-column><el-table-column prop="stockNum" :label="runRows.length?'操作前可用':'可用数量'" width="100" align="right" show-overflow-tooltip/>
<el-table-column label="本次数量" width="160" align="right" class-name="business-control-cell">
<template #default="s">
<el-input-number v-model="s.row.quantity" :min="0" :max="Number(s.row.stockNum)" :precision="4" :controls="false" style="width:130px" :disabled="saving||s.row.done"/>
@ -88,6 +89,7 @@
</template>
</el-dialog></template>
<script>
import OperationPhotos from '@/components/OperationPhotos'
import {allows,productionAction} from '@/utils/business-permissions'
import { taskAction } from '@/api/production/tasks'
import { moveStock, outStock as sendOutStock } from '@/api/warehouse/stock'
@ -100,7 +102,7 @@ import { useCompactLayout } from '@/utils/use-compact-layout'
const outStock = data => sendOutStock({ ...data, outTime: data.outTime + ' 00:00:00' })
const labels={USE:'项目领用',ISSUE:'生产领料',MOVE:'移库',SCRAP_STOCK:'库存零件报废',SCRAP_FINISHED:'成品报废',DELIVERY:'成品交付'}
export default {
components:{BatchProgress,DialogWorkspace,ItemSummary},setup:useCompactLayout,
components:{OperationPhotos,BatchProgress,DialogWorkspace,ItemSummary},setup:useCompactLayout,
data:()=>({visible:false,saving:false,opening:false,fixedKind:false,onlyFailed:false,runRows:[],kind:'USE',rows:[],areas:[],date:'',reason:'',remark:'',recipient:'',toAreaId:undefined,taskContext:null}),
computed:{
operationTitle(){return labels[this.kind]||'库存操作'},
@ -119,8 +121,8 @@ export default {
if(this.saving||this.runRows.length||this.kind!=='USE'||this.taskContext)return
for(const row of this.fillableRows)row.quantity=Number(row.stockNum)
},
async open(input,requestedKind,task){if(this.saving||this.opening)return;this.opening=true;try{this.runRows=[];this.onlyFailed=false;if(!allows(this.$store.getters.permissions,productionAction))return this.$modal.msgWarning('没有此操作权限');this.taskContext=task||null;if(task&&task.status!=='OPEN')return this.$modal.msgWarning('请先恢复生产再领料');this.date=this.parseTime(new Date(),'{y}-{m}-{d}');this.reason='';this.remark='';this.recipient='';this.toAreaId=undefined;this.rows=(input||[]).filter(r=>Number(r.stockNum)>0 && (!task || (String(r.projectId)===String(task.project_id) && String(r.productId)!==String(task.item_id) && (task.needs||[]).some(n=>String(n.itemId)===String(r.productId))))).map(r=>({...r,quantity:Math.min(1,Number(r.stockNum)),taskId:task&&task.id,done:false,failed:false,result:'',key:`${Date.now()}-${r.id}-${Math.random().toString(36).slice(2)}`}));if(task)this.rows=allocateMaterials(this.rows,task.needs);if(!this.rows.length)return this.$modal.msgWarning('请选择库存数量大于零的记录');const kind=requestedKind||(task?'ISSUE':'USE');if(!this.operationOptions.some(item=>item.value===kind)){this.rows=[];return this.$modal.msgWarning(kind==='DELIVERY'||kind==='SCRAP_FINISHED'?'只有产品档案中的成品库存才能办理该操作':'所选库存类型不支持该操作')}this.kind=kind;this.fixedKind=!!requestedKind||!!task;this.areas=(await optionselectArea()).data||[];this.visible=true}finally{this.opening=false}},
async submit(retryOnly=false){if(this.saving)return;if(!this.operationOptions.some(item=>item.value===this.kind))return this.$modal.msgWarning('所选库存不支持该操作,请重新选择');if(!this.date)return this.$modal.msgWarning('请选择日期');if(this.kind==='MOVE'&&!this.toAreaId)return this.$modal.msgWarning(this.targetAreas.length?'请选择目标库区':'没有可用的其他库区');if(this.kind==='DELIVERY'&&!this.recipient.trim())return this.$modal.msgWarning('请填写交付接收方');if(this.kind.startsWith('SCRAP')&&!this.reason.trim())return this.$modal.msgWarning('请填写报废原因');const pending=(retryOnly===true?this.rows.filter(r=>r.failed):this.displayRows).filter(r=>!r.done&&Number(r.quantity)>0);if(!pending.length)return;this.runRows=pending;pending.forEach(r=>{r.failed=false;r.result='等待处理'});this.onlyFailed=false;this.saving=true;try{for(const r of pending){try{r.result='正在处理';if(!(r.quantity>0))throw new Error('请填写数量');if(this.kind==='ISSUE' && (!this.taskContext || this.taskContext.status!=='OPEN' || String(r.projectId)!==String(this.taskContext.project_id) || !(this.taskContext.needs||[]).some(n=>String(n.itemId)===String(r.productId))))throw new Error('所选库存不属于该任务用料');const data={projectId:r.projectId,itemId:r.productId,areaId:r.areaId,quantity:r.quantity,date:this.date,remark:this.remark,key:r.key};if(this.kind==='USE')await outStock({id:r.id,usageProjectId:r.projectId,outNum:r.quantity,outType:4,outNo:'BOUT-'+r.key,outTime:this.date,remark:this.remark});else if(this.kind==='MOVE')await moveStock({...data,fromAreaId:r.areaId,toAreaId:this.toAreaId,key:'MOVE:'+r.key});else await taskAction({...data,kind:this.kind,taskId:this.kind==='ISSUE'?r.taskId:undefined,reason:this.reason,recipient:this.recipient});r.done=true;r.result='已成功'}catch(e){r.failed=true;r.result=e.message||'未成功,请刷新核对'}}this.$emit('changed')}finally{this.saving=false}}
async open(input,requestedKind,task){if(this.saving||this.opening)return;this.opening=true;try{this.runRows=[];this.onlyFailed=false;if(!allows(this.$store.getters.permissions,productionAction))return this.$modal.msgWarning('没有此操作权限');this.taskContext=task||null;if(task&&task.status!=='OPEN')return this.$modal.msgWarning('请先恢复生产再领料');this.date=this.parseTime(new Date(),'{y}-{m}-{d}');this.reason='';this.remark='';this.recipient='';this.toAreaId=undefined;this.rows=(input||[]).filter(r=>Number(r.stockNum)>0 && (!task || (String(r.projectId)===String(task.project_id) && String(r.productId)!==String(task.item_id) && (task.needs||[]).some(n=>String(n.itemId)===String(r.productId))))).map(r=>({...r,quantity:Math.min(1,Number(r.stockNum)),taskId:task&&task.id,photos:[],photosPending:false,done:false,failed:false,result:'',key:`${Date.now()}-${r.id}-${Math.random().toString(36).slice(2)}`}));if(task)this.rows=allocateMaterials(this.rows,task.needs);if(!this.rows.length)return this.$modal.msgWarning('请选择库存数量大于零的记录');const kind=requestedKind||(task?'ISSUE':'USE');if(!this.operationOptions.some(item=>item.value===kind)){this.rows=[];return this.$modal.msgWarning(kind==='DELIVERY'||kind==='SCRAP_FINISHED'?'只有产品档案中的成品库存才能办理该操作':'所选库存类型不支持该操作')}this.kind=kind;this.fixedKind=!!requestedKind||!!task;this.areas=(await optionselectArea()).data||[];this.visible=true}finally{this.opening=false}},
async submit(retryOnly=false){if(this.saving)return;if(!this.operationOptions.some(item=>item.value===this.kind))return this.$modal.msgWarning('所选库存不支持该操作,请重新选择');if(!this.date)return this.$modal.msgWarning('请选择日期');if(this.kind==='MOVE'&&!this.toAreaId)return this.$modal.msgWarning(this.targetAreas.length?'请选择目标库区':'没有可用的其他库区');if(this.kind==='DELIVERY'&&!this.recipient.trim())return this.$modal.msgWarning('请填写交付接收方');if(this.kind.startsWith('SCRAP')&&!this.reason.trim())return this.$modal.msgWarning('请填写报废原因');const pending=(retryOnly===true?this.rows.filter(r=>r.failed):this.displayRows).filter(r=>!r.done&&Number(r.quantity)>0);if(!pending.length)return;if(this.kind==='MOVE'&&pending.some(r=>r.photosPending))return this.$modal.msgWarning('请等待照片上传完成,或移除失败照片');this.runRows=pending;pending.forEach(r=>{r.failed=false;r.result='等待处理'});this.onlyFailed=false;this.saving=true;try{for(const r of pending){try{r.result='正在处理';if(!(r.quantity>0))throw new Error('请填写数量');if(this.kind==='ISSUE' && (!this.taskContext || this.taskContext.status!=='OPEN' || String(r.projectId)!==String(this.taskContext.project_id) || !(this.taskContext.needs||[]).some(n=>String(n.itemId)===String(r.productId))))throw new Error('所选库存不属于该任务用料');const data={projectId:r.projectId,itemId:r.productId,areaId:r.areaId,quantity:r.quantity,date:this.date,remark:this.remark,key:r.key};if(this.kind==='USE')await outStock({id:r.id,usageProjectId:r.projectId,outNum:r.quantity,outType:4,outNo:'BOUT-'+r.key,outTime:this.date,remark:this.remark});else if(this.kind==='MOVE')await moveStock({...data,fromAreaId:r.areaId,toAreaId:this.toAreaId,key:'MOVE:'+r.key,photoIds:(r.photos||[]).map(p=>p.id)});else await taskAction({...data,kind:this.kind,taskId:this.kind==='ISSUE'?r.taskId:undefined,reason:this.reason,recipient:this.recipient});r.done=true;r.result='已成功'}catch(e){r.failed=true;r.result=e.message||'未成功,请刷新核对'}}this.$emit('changed')}finally{this.saving=false}}
}
}
</script>

View File

@ -813,7 +813,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.sheet-grid :deep(a.sheet-link:hover),.sheet-grid :deep(a.sheet-link:focus-visible){text-decoration:underline}
.sheet-grid :deep(.sheet-cell .el-select),.sheet-grid :deep(.sheet-cell .el-input-number){width:100%}
.sheet-grid :deep(.cell-invalid){outline:1px solid var(--el-color-danger);outline-offset:-1px;background:var(--el-color-danger-light-9)}
.sheet-grid :deep(.sheet-cell){cursor:cell;min-height:var(--cmvr-grid-height,28px);outline:none;user-select:none}
.sheet-grid :deep(.sheet-cell){display:flex;align-items:center;justify-content:center;cursor:cell;min-height:var(--cmvr-grid-height,28px);outline:none;user-select:none}
.sheet-grid :deep(.sheet-cell.cell-selected){background:var(--el-color-primary-light-9);box-shadow:inset 0 0 0 1px var(--el-color-primary-light-5)}
.sheet-grid :deep(.sheet-cell:focus){box-shadow:inset 0 0 0 2px var(--el-color-primary)}
.sheet-grid :deep(.sheet-cell input),.sheet-grid :deep(.sheet-cell textarea){user-select:text}

View File

@ -31,7 +31,7 @@
<el-empty v-if="!filteredRows.length&&!opening" description="没有符合条件的记录" :image-size="60"/>
</template>
<el-table v-else :data="pagedRows" class="batch-dialog-table" :height="tableHeight">
<el-table-column width="45" class-name="business-control-cell"><template #header><el-checkbox :model-value="allVisibleSelected" :indeterminate="someVisibleSelected" :disabled="saving||!selectableVisibleRows.length" @change="selectVisible"/></template><template #default="s"><el-checkbox v-model="s.row.chosen" :disabled="s.row.done||saving"/></template></el-table-column>
<el-table-column v-if="mode==='receipt'" label="入库照片" width="145" class-name="business-control-cell"><template #default="{row}"><operation-photos kind="IN" v-model="row.operationPhotos" :disabled="saving||row.done" compact @pending="row.operationPhotosPending=$event"/></template></el-table-column><el-table-column width="45" class-name="business-control-cell"><template #header><el-checkbox :model-value="allVisibleSelected" :indeterminate="someVisibleSelected" :disabled="saving||!selectableVisibleRows.length" @change="selectVisible"/></template><template #default="s"><el-checkbox v-model="s.row.chosen" :disabled="s.row.done||saving"/></template></el-table-column>
<el-table-column label="批次 / 来源" min-width="150" show-overflow-tooltip><template #default="s"><table-text :value="s.row.purchaseBatchNo||s.row.sourceNo||s.row.arrivalNo||'未分批'" /><table-text v-if="s.row.supplierName" class="secondary" :value="s.row.supplierName" /></template></el-table-column>
<el-table-column label="项目 / 物品" min-width="190"><template #default="s"><item-summary :name="s.row.productName || s.row.materialName" :brand="s.row.materialBrand || s.row.productBrand || s.row.brand" :spec="s.row.materialParams || s.row.productSpec || s.row.spec" :unit="s.row.unit" :context="s.row.sourceProjectName || s.row.projectName" /></template></el-table-column>
<el-table-column :label="remainingLabel" width="100" align="right" show-overflow-tooltip><template #default="s">{{ remainingQuantity(s.row) }} {{ s.row.unit }}</template></el-table-column>
@ -50,6 +50,7 @@
import { optionselectArea } from '@/api/warehouse/area'
import { getInRecord, receiveInRecord, updateInRecord, confirmInRecord } from '@/api/warehouse/inRecord'
import { addPurchaseArrival, acceptPurchaseArrival, listPurchaseArrival } from '@/api/warehouse/purchase'
import OperationPhotos from '@/components/OperationPhotos'
import ArrivalPhotos from '@/components/ArrivalPhotos'
import BatchProgress from '@/components/BatchProgress'
import DialogWorkspace from '@/components/DialogWorkspace'
@ -58,7 +59,7 @@ import TableText from '@/components/TableText'
import { useCompactLayout } from '@/utils/use-compact-layout'
export default {
props:{separateAcceptance:Boolean},
components:{ArrivalPhotos,BatchProgress,DialogWorkspace,ItemSummary,TableText},setup:useCompactLayout,
components:{OperationPhotos,ArrivalPhotos,BatchProgress,DialogWorkspace,ItemSummary,TableText},setup:useCompactLayout,
data:()=>({visible:false,saving:false,opening:false,mode:'receipt',rows:[],runRows:[],onlyFailed:false,areas:[],commonArea:undefined,date:'',remark:'',acceptAll:true,keyword:'',pageNum:1,pageSize:20}),
watch:{keyword(){this.pageNum=1;const visible=new Set(this.filteredRows);this.rows.forEach(r=>{if(!visible.has(r)&&!r.done)r.chosen=false})},onlyFailed(){this.pageNum=1},'filteredRows.length'(count){this.pageNum=Math.min(this.pageNum,Math.max(1,Math.ceil(count/this.pageSize)))}},
computed:{
@ -88,7 +89,7 @@ export default {
const arrivals=await Promise.all(requests.map(request=>listPurchaseArrival(request.id)))
this.rows=requests.flatMap((request,index)=>(arrivals[index].data||[]).filter(a=>Number(a.acceptanceStatus)===0).map(a=>({...request,arrivalIdCreated:a.id,arrivalNo:a.arrivalNo,photos:a.photos||[],quantity:Number(a.arrivalQuantity),maximum:Number(a.arrivalQuantity),defectiveQuantity:0,chosen:true,done:false,failed:false,result:''})))
} else {
this.rows=input.filter(r=>mode==='receipt'?Number(r.inStatus)===0:r.editable!==false&&Number(r.remainingQuantity)>0&&Number(r.purchaseStatus)!==5&&!r.historical).map(r=>({...r,quantity:mode==='receipt'?Number(r.inNum):0,maximum:Number(mode==='receipt'?r.inNum:r.remainingQuantity),chosen:true,done:false,failed:false,result:'',key:'batch-'+r.id+'-'+Date.now()+'-'+Math.random().toString(36).slice(2),arrivalIdCreated:null,photos:[],photosPending:false}))
this.rows=input.filter(r=>mode==='receipt'?Number(r.inStatus)===0:r.editable!==false&&Number(r.remainingQuantity)>0&&Number(r.purchaseStatus)!==5&&!r.historical).map(r=>({...r,quantity:mode==='receipt'?Number(r.inNum):0,maximum:Number(mode==='receipt'?r.inNum:r.remainingQuantity),chosen:true,done:false,failed:false,result:'',key:'batch-'+r.id+'-'+Date.now()+'-'+Math.random().toString(36).slice(2),operationPhotos:[],operationPhotosPending:false,arrivalIdCreated:null,photos:[],photosPending:false}))
}
if(mode==='arrival'&&this.rows.some(row=>!row.priceLocked))this.acceptAll=false
if(!this.rows.length){this.visible=false;this.$modal.msgWarning('没有可办理的记录')}
@ -103,7 +104,7 @@ export default {
const pending=(retryOnly===true?this.rows.filter(r=>r.failed&&!r.done):this.selectedRows).filter(r=>Number(r.quantity)>0)
if(!pending.length)return this.$modal.msgWarning('请填写本次实际数量')
if(this.mode==='arrival'&&pending.some(r=>!r.arrivalIdCreated&&!(r.photos||[]).some(p=>p.id))){pending.filter(r=>!r.arrivalIdCreated&&!(r.photos||[]).some(p=>p.id)).forEach(r=>{r.failed=true;r.result='请上传至少1张到货照片'});return this.$modal.msgWarning('每项登记到货至少需要1张照片,请先补全照片')}
if(pending.some(r=>r.photosPending))return this.$modal.msgWarning('有照片尚未上传完成,请重试或移除后继续')
if(pending.some(r=>r.photosPending||r.operationPhotosPending))return this.$modal.msgWarning('有照片尚未上传完成,请重试或移除后继续')
if(this.mode==='receipt'){
const missing=pending.filter(row=>!row.areaId)
if(missing.length){missing.forEach(row=>{row.failed=true;row.validationError='area';row.result='请选择库区'});return this.$modal.msgWarning('请先为 '+missing.length+' 项选择库区,可使用统一库区')}
@ -117,11 +118,11 @@ export default {
if(this.mode==='receipt') {
if(!row.areaId)throw new Error('请选择库区')
const current=(await getInRecord(row.id)).data
if(current.receiptRoot)await receiveInRecord(row.id,{areaId:row.areaId,quantity:row.quantity,key:row.key,date:this.date,remark:this.remark})
if(current.receiptRoot)await receiveInRecord(row.id,{areaId:row.areaId,quantity:row.quantity,key:row.key,date:this.date,remark:this.remark,photoIds:(row.operationPhotos||[]).map(p=>p.id)})
else{
if(row.quantity!==Number(current.inNum))throw new Error('历史或手工入库请整条确认')
if(Number(current.inStatus)===1){if(current.areaId!==row.areaId)throw new Error('该条已在其他库区入库,请核对')}
else{await updateInRecord({...current,areaId:row.areaId,businessDate:this.date,remark:this.remark});changed=true;await confirmInRecord(row.id)}
else{await updateInRecord({...current,areaId:row.areaId,businessDate:this.date,remark:this.remark});changed=true;await confirmInRecord(row.id,{photoIds:(row.operationPhotos||[]).map(p=>p.id)})}
}
} else {
if(!row.arrivalIdCreated){

View File

@ -1,10 +1,11 @@
<template><el-dialog title="移库" v-model="visible" width="min(520px,96vw)" append-to-body :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving">
<p>{{ form.projectName }} · {{ form.productName }} · {{ form.areaName }}</p>
<el-form label-width="auto" :disabled="saving"><el-form-item label="目标库区" :disabled="saving"><el-select v-model="form.toAreaId"><el-option v-for="a in areas.filter(a=>a.id!==form.fromAreaId)" :key="a.id" :label="a.areaName" :value="a.id"/></el-select></el-form-item><el-form-item label="数量" :disabled="saving"><el-input-number v-model="form.quantity" :min="0.0001" :max="Number(form.stockNum)" :precision="4"/></el-form-item></el-form>
<el-form label-width="auto" :disabled="saving"><el-form-item label="目标库区" :disabled="saving"><el-select v-model="form.toAreaId"><el-option v-for="a in areas.filter(a=>a.id!==form.fromAreaId)" :key="a.id" :label="a.areaName" :value="a.id"/></el-select></el-form-item><el-form-item label="数量" :disabled="saving"><el-input-number v-model="form.quantity" :min="0.0001" :max="Number(form.stockNum)" :precision="4"/></el-form-item><el-form-item label="移库照片(选填)"><operation-photos kind="MOVE" v-model="photos" :disabled="saving" @pending="photosPending=$event"/></el-form-item></el-form>
<template #footer><div ><el-button :disabled="saving" @click="visible=false">取消</el-button><el-button type="primary" :loading="saving" @click="save">确认移库</el-button></div></template>
</el-dialog></template>
<script>
import OperationPhotos from '@/components/OperationPhotos'
import { moveStock } from '@/api/warehouse/stock'
import { optionselectArea } from '@/api/warehouse/area'
export default {data:()=>({visible:false,saving:false,form:{},areas:[]}),methods:{async open(row){this.form={...row,projectId:row.projectId,itemId:row.productId,fromAreaId:row.areaId,toAreaId:undefined,quantity:1,key:`MOVE:${Date.now()}:${Math.random().toString(36).slice(2)}`};this.areas=(await optionselectArea()).data||[];this.visible=true},async save() { if(this.saving)return;if(!this.form.toAreaId||!(this.form.quantity>0))return this.$modal.msgWarning('请选择库区和数量');this.saving=true;try{await moveStock(this.form);this.visible=false;this.$emit('changed');this.$modal.msgSuccess('已移库')}finally{this.saving=false}}}}
export default {components:{OperationPhotos},data:()=>({visible:false,saving:false,photos:[],photosPending:false,form:{},areas:[]}),methods:{async open(row){this.photos=[];this.photosPending=false;this.form={...row,projectId:row.projectId,itemId:row.productId,fromAreaId:row.areaId,toAreaId:undefined,quantity:1,key:`MOVE:${Date.now()}:${Math.random().toString(36).slice(2)}`};this.areas=(await optionselectArea()).data||[];this.visible=true},async save() { if(this.saving)return;if(this.photosPending)return this.$modal.msgWarning('请等待照片上传完成,或移除失败照片');if(!this.form.toAreaId||!(this.form.quantity>0))return this.$modal.msgWarning('请选择库区和数量');this.saving=true;try{await moveStock({...this.form,photoIds:this.photos.map(p=>p.id)});this.visible=false;this.$emit('changed');this.$modal.msgSuccess('已移库')}finally{this.saving=false}}}}
</script>

View File

@ -7,16 +7,18 @@
<el-form-item label="备注" :disabled="saving"><el-input v-model="form.remark" maxlength="500"/></el-form-item>
<el-form-item label="库区" prop="areaId" :disabled="saving"><el-select v-model="form.areaId" filterable style="width:100%"><el-option v-for="area in areas" :key="area.id" :value="area.id" :label="area.areaName || area.areaCode" /></el-select></el-form-item>
<el-form-item label="本次数量" prop="quantity" :disabled="saving"><el-input-number v-model="form.quantity" :min="0.0001" :max="Number(record.inNum)" :precision="4" :disabled="!record.receiptRoot" /></el-form-item>
<el-form-item label="入库照片(选填)"><operation-photos kind="IN" v-model="photos" :disabled="saving" @pending="photosPending=$event"/></el-form-item>
</el-form>
<template #footer><div ><el-button :disabled="saving" @click="visible=false">取消</el-button><el-button type="primary" :loading="saving" @click="submit">确认入库</el-button></div></template>
</el-dialog>
</template>
<script>
import OperationPhotos from '@/components/OperationPhotos'
import { optionselectArea } from '@/api/warehouse/area'
import { getInRecord, receiveInRecord, updateInRecord, confirmInRecord } from '@/api/warehouse/inRecord'
export default {
name: 'ReceiptDialog',
data: () => ({ visible: false, saving: false, openSequence: 0, record: {}, areas: [], form: {}, rules: { areaId: [{ required: true, message: '请选择库区', trigger: 'change' }], quantity: [{ required: true, message: '请输入本次数量', trigger: 'change' }] } }),
name: 'ReceiptDialog',components:{OperationPhotos},
data: () => ({ visible: false, saving: false, photos:[],photosPending:false, openSequence: 0, record: {}, areas: [], form: {}, rules: { areaId: [{ required: true, message: '请选择库区', trigger: 'change' }], quantity: [{ required: true, message: '请输入本次数量', trigger: 'change' }] } }),
beforeUnmount() { this.openSequence++ },
methods: {
async open(row) {
@ -29,20 +31,21 @@ export default {
this.record = result.data
this.areas = options.data || []
this.form = { areaId: this.record.areaId, quantity: Number(this.record.inNum), date: this.record.businessDate || this.parseTime(new Date(),'{y}-{m}-{d}'), remark: this.record.remark || '', key: `receipt-${row.id}-${Date.now()}-${Math.random().toString(36).slice(2)}` }
this.visible = true
this.photos=[];this.photosPending=false;this.visible = true
this.$nextTick(() => this.$refs.form.clearValidate())
},
submit() {
this.$refs.form.validate(async valid => {
if (!valid || this.saving) return
if(this.photosPending)return this.$modal.msgWarning('请等待照片上传完成,或移除失败的照片')
if (!this.form.date) return this.$modal.msgWarning('请选择入库日期')
if (!(Number(this.form.quantity) > 0) || Number(this.form.quantity) > Number(this.record.inNum)) return this.$modal.msgWarning('入库数量须大于 0 且不超过待入库数量')
this.saving = true
try {
if (this.record.receiptRoot) await receiveInRecord(this.record.id, this.form)
if (this.record.receiptRoot) await receiveInRecord(this.record.id, {...this.form,photoIds:this.photos.map(p=>p.id)})
else {
await updateInRecord({ ...this.record, areaId: this.form.areaId, businessDate: this.form.date, remark: this.form.remark })
await confirmInRecord(this.record.id)
await confirmInRecord(this.record.id,{photoIds:this.photos.map(p=>p.id)})
}
this.visible = false
this.$modal.msgSuccess('入库成功')

View File

@ -0,0 +1,40 @@
<template>
<el-drawer v-model="visible" title="库存照片" size="min(860px,96vw)" append-to-body @closed="reset">
<div v-if="row" class="stock-photo-identity"><h3>{{row.productName}}</h3><p>{{[row.brand,row.spec].filter(Boolean).join(' · ')||'暂无品牌规格'}}</p><div><el-tag>{{row.projectName}}</el-tag><el-tag type="info">{{row.areaName}}</el-tag><span>库存 {{row.stockNum}} {{row.unit}}</span></div></div>
<p class="stock-photo-hint">查看当前项目、物品、库区关联的业务照片;按照片上传时间从新到旧展示。</p>
<el-radio-group v-model="kind" size="small" @change="filterChanged"><el-radio-button v-for="tab in tabs" :key="tab.value" :value="tab.value">{{tab.label}}</el-radio-button></el-radio-group>
<div v-if="error" class="stock-photo-error" role="alert">{{error}}<el-button link type="primary" @click="load">重试</el-button></div>
<div v-loading="loading" class="stock-photo-content">
<el-empty v-if="!loading&&!error&&!photos.length" description="暂无相关照片,可在到货、入库或移库时上传" :image-size="80"/>
<section v-for="group in groups" :key="group.key" class="stock-photo-group"><header><el-tag size="small" :type="group.kind==='ARRIVAL'?'info':group.kind==='IN'?'success':'warning'">{{label(group.kind)}}</el-tag><strong>{{group.documentNo}}</strong><span>{{$dateTime(group.businessDate)}}</span></header>
<div class="stock-photo-grid"><button v-for="photo in group.photos" :key="photo.kind+photo.id" type="button" class="stock-photo-tile" :aria-label="'预览'+photo.name" @click="preview(photo)"><el-image v-if="thumbs[photo.kind+photo.id]" :src="thumbs[photo.kind+photo.id]" fit="contain"/><span v-else class="stock-photo-placeholder">{{failedThumbs[photo.kind+photo.id]?'点击查看原图':'加载缩略图…'}}</span><span :title="photo.name">{{photo.name}}</span></button></div>
</section>
</div>
<el-pagination v-if="total>pageSize" v-model:current-page="page" :page-size="pageSize" :total="total" layout="total,prev,pager,next" @current-change="load"/>
<el-dialog v-model="previewOpen" title="照片预览" width="min(1000px,96vw)" append-to-body @closed="clearOriginal"><div v-loading="originalLoading" class="stock-photo-original"><el-image v-if="original" :src="original" fit="contain"/><p v-if="originalError" role="alert">{{originalError}}<el-button @click="preview(selected)">重试</el-button></p></div><template #footer><span>{{selected?.name}}</span><el-button @click="previewOpen=false">关闭</el-button></template></el-dialog>
</el-drawer>
</template>
<script setup>
import {computed,onBeforeUnmount,ref} from 'vue'
import request from '@/utils/request'
const tabs=[{value:'ALL',label:'全部'},{value:'ARRIVAL',label:'到货照片'},{value:'IN',label:'入库照片'},{value:'MOVE',label:'移库照片'}]
const label=kind=>tabs.find(t=>t.value===kind)?.label||kind
const visible=ref(false),row=ref(null),kind=ref('ALL'),page=ref(1),pageSize=24,total=ref(0),photos=ref([]),thumbs=ref({}),failedThumbs=ref({}),loading=ref(false),error=ref('')
const previewOpen=ref(false),original=ref(''),originalLoading=ref(false),originalError=ref(''),selected=ref(null)
let sequence=0,controller,previewController
const groups=computed(()=>{const result=new Map();for(const photo of photos.value){const key=photo.kind+':'+photo.recordId;if(!result.has(key))result.set(key,{...photo,key,photos:[]});result.get(key).photos.push(photo)}return [...result.values()]})
function clearThumbs(){for(const url of Object.values(thumbs.value))URL.revokeObjectURL(url);thumbs.value={};failedThumbs.value={}}
function clearOriginal(){previewController?.abort();if(original.value)URL.revokeObjectURL(original.value);original.value='';originalError.value=''}
function reset(){sequence++;controller?.abort();clearThumbs();clearOriginal();photos.value=[];previewOpen.value=false}
async function open(stock){reset();row.value=stock;kind.value='ALL';page.value=1;visible.value=true;await load()}
function filterChanged(){page.value=1;void load()}
async function load(){controller?.abort();controller=new AbortController();const ctl=controller,seq=++sequence;clearThumbs();photos.value=[];loading.value=true;error.value='';try{const result=await request({url:`/warehouse/stock/${row.value.id}/photos`,params:{kind:kind.value,pageNum:page.value,pageSize},signal:ctl.signal});if(seq!==sequence)return;photos.value=result.data.rows;total.value=result.data.total;loading.value=false;
// Three bounded thumbnail requests at a time; full-sized images only load on explicit preview.
const queue=[...photos.value];await Promise.all(Array.from({length:3},async()=>{while(queue.length&&!ctl.signal.aborted){const photo=queue.shift(),key=photo.kind+photo.id;try{const blob=await request({url:photo.thumbnailPath,responseType:'blob',signal:ctl.signal});if(seq===sequence)thumbs.value={...thumbs.value,[key]:URL.createObjectURL(blob)}}catch(e){if(seq===sequence&&!ctl.signal.aborted)failedThumbs.value={...failedThumbs.value,[key]:true}}}}));
}catch(e){if(seq===sequence&&!ctl.signal.aborted)error.value=e.message||'照片加载失败'}finally{if(seq===sequence)loading.value=false}}
async function preview(photo){if(!photo)return;clearOriginal();selected.value=photo;previewOpen.value=true;originalLoading.value=true;const ctl=new AbortController();previewController=ctl;try{const blob=await request({url:photo.contentPath,responseType:'blob',signal:ctl.signal,timeout:120000});if(!ctl.signal.aborted)original.value=URL.createObjectURL(blob)}catch(e){if(!ctl.signal.aborted)originalError.value=e.message||'原图加载失败'}finally{if(!ctl.signal.aborted)originalLoading.value=false}}
onBeforeUnmount(reset);defineExpose({open})
</script>
<style scoped>
.stock-photo-identity{padding:14px;border-radius:8px;background:var(--el-fill-color-light)}.stock-photo-identity h3{margin:0 0 6px;font-size:16px}.stock-photo-identity p,.stock-photo-hint{font-size:12px;color:var(--el-text-color-secondary);line-height:1.6}.stock-photo-identity>div{display:flex;gap:8px;align-items:center;flex-wrap:wrap;font-size:13px}.stock-photo-content{min-height:160px}.stock-photo-group{margin-top:20px}.stock-photo-group header{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;margin-bottom:10px}.stock-photo-group header span:last-child{color:var(--el-text-color-secondary)}.stock-photo-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:12px}.stock-photo-tile{padding:6px;background:var(--el-bg-color);border:1px solid var(--el-border-color-lighter);border-radius:8px;cursor:pointer;min-width:0;color:var(--el-text-color-regular)}.stock-photo-tile .el-image,.stock-photo-placeholder{display:flex;width:100%;height:112px;align-items:center;justify-content:center;background:var(--el-fill-color-extra-light);border-radius:4px;font-size:12px}.stock-photo-tile>span:last-child{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;margin-top:6px}.stock-photo-original{min-height:180px;text-align:center}.stock-photo-original .el-image{max-height:70vh}.stock-photo-error{padding:12px;color:var(--el-color-danger)}
</style>

View File

@ -39,14 +39,14 @@ export function convertHeic(file,signal){
worker.postMessage(file)
})
}
export async function prepareArrivalPhoto(file,signal,convert=convertHeic){
export async function prepareArrivalPhoto(file,signal,convert=convertHeic,maxBytes=20*1024*1024){
check(signal)
if(prepared.has(file))return prepared.get(file)
if(prepared.has(file)){const cached=prepared.get(file);if(cached.size>maxBytes)throw new Error(`转换后照片超过${maxBytes/1024/1024}MB`);return cached}
const header=await read(file.slice(0,128));check(signal)
const heic=isHeicHeader(header),avif=hasBrand(header,['avif','avis'])
if(!heic&&!avif)return file
const blob=await (heic?convert(file,signal):convertAvif(file));check(signal)
if(!blob?.size||blob.size>20*1024*1024)throw new Error('苹果照片转换后超过20MB,请缩小后上传')
if(!blob?.size||blob.size>maxBytes)throw new Error(`苹果照片转换后超过${maxBytes/1024/1024}MB,请缩小后上传`)
const result=new File([blob],(file.name||'到货照片').replace(/\.[^.]*$/,'')+(heic?'.jpg':'.png'),{type:heic?'image/jpeg':'image/png'})
prepared.set(file,result);return result
}

View File

@ -71,7 +71,7 @@
<pending-receipts v-if="pendingOnly" :groups="groupRows" :all-count="pendingItemTotal" :height="tableHeight" :query="pendingQuery" :can-receive="$canAll([['warehouse:in:confirm'],['warehouse:in:query']])" @selection-change="handleSelectionChange" @receive="handleConfirm" @batch="$refs.batchReceipt.open($event)"/>
<business-table :height="tableHeight" v-else v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" :selectable="canSelectPendingRecord" />
<el-table-column label="入库单号" align="center" prop="inNo" min-width="150" show-overflow-tooltip/>
<el-table-column label="入库照片" width="110" class-name="business-control-cell"><template #default="{row}"><operation-photos kind="IN" :record-id="row.id" v-model="row.operationPhotos" readonly compact/></template></el-table-column><el-table-column label="入库单号" align="center" prop="inNo" min-width="150" show-overflow-tooltip/>
<el-table-column label="库区" align="center" prop="areaName" min-width="110" class-name="business-status-cell">
<template #default="scope">
<span v-if="scope.row.areaId">{{ scope.row.areaName || scope.row.areaCode }}</span>
@ -167,6 +167,7 @@
import { runLatest, queryError } from '@/utils/query-session'
import { defineAsyncComponent } from 'vue'
import request from '@/utils/request'
import OperationPhotos from '@/components/OperationPhotos'
import { listInRecord, getInRecord, delInRecord, addInRecord, updateInRecord, confirmInRecord, revokeInRecord } from '@/api/warehouse/inRecord'
import { optionselectArea } from '@/api/warehouse/area'
import { optionselectProduct } from '@/api/warehouse/product'
@ -178,7 +179,7 @@ import PendingReceipts from '@/components/PendingReceipts'
export default {
name: 'InRecord',
props:{pendingOnly:Boolean,projectId:Number},
components: { PendingReceipts,SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),ReceiptDialog, WithdrawDialog: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Withdraw')), BatchReceipt: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')) },
components: { OperationPhotos, PendingReceipts,SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),ReceiptDialog, WithdrawDialog: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Withdraw')), BatchReceipt: defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')) },
dicts: ['wms_in_type', 'wms_in_status'],
data() {
return {

View File

@ -39,7 +39,7 @@
<el-table-column label="物品信息" min-width="300">
<template #default="scope"><item-summary :name="scope.row.productName" :brand="scope.row.brand" :category="scope.row.category" :spec="scope.row.spec" :unit="scope.row.unit" :kind="scope.row.finishedProduct ? 'finished' : 'material'" /></template>
</el-table-column>
<el-table-column label="当前库存" align="right" prop="stockNum" min-width="120" show-overflow-tooltip/>
<el-table-column label="照片" width="90" class-name="business-control-cell"><template #default="{row}"><el-button link type="primary" @click="$refs.stockPhotos.open(row)">查看照片</el-button></template></el-table-column><el-table-column label="当前库存" align="right" prop="stockNum" min-width="120" show-overflow-tooltip/>
<el-table-column label="平均单价" align="right" min-width="120" show-overflow-tooltip><template #default="scope">{{ scope.row.averageUnitCost == null ? '成本未知' : scope.row.averageUnitCost }}</template></el-table-column>
<el-table-column label="库存金额" align="right" min-width="120" show-overflow-tooltip><template #default="scope">{{ scope.row.stockAmount == null ? '成本未知' : scope.row.stockAmount }}</template></el-table-column>
<el-table-column label="最近盘库时间" align="center" prop="lastCheckTime" width="180" show-overflow-tooltip>
@ -96,7 +96,7 @@
<el-alert v-if="lotError" :title="lotError" type="error" :closable="false"><el-button link type="primary" @click="loadLots">重试</el-button></el-alert>
<el-tabs v-model="lotTab"><el-tab-pane label="库存流水" name="events">
<el-table v-loading="lotLoading" :data="lotList" border :height="historyTableHeight">
<el-table-column label="流水编号" min-width="160" show-overflow-tooltip><template #default="s">{{ s.row.eventNo || s.row.eventKey }}</template></el-table-column>
<el-table-column label="照片" width="100" class-name="business-control-cell"><template #default="{row}"><operation-photos kind="MOVE" :record-id="row.id" v-model="row.operationPhotos" readonly compact/></template></el-table-column><el-table-column label="流水编号" min-width="160" show-overflow-tooltip><template #default="s">{{ s.row.eventNo || s.row.eventKey }}</template></el-table-column>
<el-table-column :formatter="(row,column,value)=>$dateTime(value)" label="业务日期" prop="businessDate" width="105" show-overflow-tooltip/><el-table-column label="备注" prop="remark" min-width="140" show-overflow-tooltip/>
<el-table-column label="类型" show-overflow-tooltip min-width="100"><template #default="s">{{ { RECEIPT: '入库', ISSUE: '出库', RETURN: '退回' }[s.row.eventType] }}</template></el-table-column>
<el-table-column label="库区" show-overflow-tooltip min-width="100"><template #default="s">{{ areaOptions.find(a => a.id === s.row.areaId) && areaOptions.find(a => a.id === s.row.areaId).areaName }}</template></el-table-column>
@ -116,18 +116,21 @@
<el-form label-width="auto">
<el-form-item label="项目">{{ moveForm.projectName }}</el-form-item>
<el-form-item label="物品">{{ moveForm.productName }}</el-form-item>
<el-form-item label="源库区">{{ moveForm.areaName }}</el-form-item>
<el-form-item label="源库区">{{ moveForm.areaName }}</el-form-item><el-form-item label="移库照片(选填)"><operation-photos kind="MOVE" v-model="moveForm.photos" :disabled="moveSaving" @pending="moveForm.photosPending=$event"/></el-form-item>
<el-form-item label="目标库区"><el-select v-model="moveForm.toAreaId" filterable><el-option v-for="area in areaOptions.filter(a => a.id !== moveForm.fromAreaId)" :key="area.id" :label="areaLabel(area)" :value="area.id" /></el-select></el-form-item>
<el-form-item label="数量"><el-input-number v-model="moveForm.quantity" :precision="4" :min="0.0001" :max="Number(moveForm.stockNum)" /></el-form-item>
</el-form>
<template #footer><span ><el-button :disabled="moveSaving" @click="moveOpen=false">取消</el-button><el-button type="primary" :loading="moveSaving" @click="submitMove">确认移库</el-button></span></template>
</el-dialog>
<stock-photos ref="stockPhotos"/>
</template>
</business-list-page>
</template>
<script>
import StockPhotos from '@/components/StockPhotos'
import OperationPhotos from '@/components/OperationPhotos'
import { runLatest, invalidateQuery, queryError } from '@/utils/query-session'
import { defineAsyncComponent } from 'vue'
import { listStock, outStock, stockEvents, stockAdjustments, moveStock, revokeStockMove } from '@/api/warehouse/stock'
@ -137,7 +140,7 @@ import { projectOptions } from '@/api/project/project'
export default {
name: 'StockInfo',
props:{projectId:Number},
components: { StockCheckEntry:defineAsyncComponent(()=>import('@/views/warehouse/stockCheck')), ProjectLoans:defineAsyncComponent(()=>import('@/components/ProjectLoans')),ProductionAction: defineAsyncComponent(()=>import('@/components/Production/ActionDialog')), StockOperations: defineAsyncComponent(()=>import('@/components/Production/StockOperations')) },
components: { StockPhotos,OperationPhotos, StockCheckEntry:defineAsyncComponent(()=>import('@/views/warehouse/stockCheck')), ProjectLoans:defineAsyncComponent(()=>import('@/components/ProjectLoans')),ProductionAction: defineAsyncComponent(()=>import('@/components/Production/ActionDialog')), StockOperations: defineAsyncComponent(()=>import('@/components/Production/StockOperations')) },
dicts: ['wms_out_type'],
data() {
return {
@ -278,14 +281,15 @@ getList() {
})
},
handleMove(row) {
this.moveForm = { ...row, projectId: row.projectId, itemId: row.productId, fromAreaId: row.areaId, toAreaId: undefined, quantity: 1, key: 'MOVE:' + Date.now() + ':' + Math.random().toString(36).slice(2) }
this.moveForm = { ...row, photos:[],photosPending:false, projectId: row.projectId, itemId: row.productId, fromAreaId: row.areaId, toAreaId: undefined, quantity: 1, key: 'MOVE:' + Date.now() + ':' + Math.random().toString(36).slice(2) }
this.moveOpen = true
},
submitMove() {
if(this.moveSaving)return;
if(this.moveForm.photosPending)return this.$modal.msgWarning('请等待照片上传完成,或移除失败照片');
if (!this.moveForm.toAreaId || !this.moveForm.quantity) return this.$modal.msgWarning('请选择目标库区并填写数量')
this.moveSaving = true
moveStock(this.moveForm).then(() => { this.$modal.msgSuccess('移库成功'); this.moveOpen = false; this.getList() }).finally(() => { this.moveSaving = false })
moveStock({...this.moveForm,photoIds:(this.moveForm.photos||[]).map(p=>p.id)}).then(() => { this.$modal.msgSuccess('移库成功'); this.moveOpen = false; this.getList() }).finally(() => { this.moveSaving = false })
},
submitOut() {
if(this.saving)return;

View File

@ -0,0 +1,21 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Photos from '@/components/OperationPhotos/index.vue'
import {operationPhotoError} from '@/api/warehouse/operation-photos'
import request from '@/utils/request'
vi.mock('@/utils/request',()=>({default:vi.fn(async()=>({data:[]}))}))
let wrapper;afterEach(()=>{wrapper?.unmount();vi.clearAllMocks()})
it('validates image selection at exactly 50 MB without changing the arrival limit',()=>{
expect(operationPhotoError({type:'image/jpeg',name:'photo.jpg',size:50*1024*1024})).toBe('')
expect(operationPhotoError({type:'image/jpeg',size:50*1024*1024+1})).toContain('50MB')
expect(operationPhotoError({type:'image/svg+xml',name:'photo.svg',size:10})).toBeTruthy()
})
it('shows optional upload and nine-photo limit',()=>{
wrapper=mount(Photos,{props:{kind:'IN',modelValue:[]},global:{plugins:[ElementPlus]}})
expect(wrapper.text()).toContain('选传');expect(wrapper.text()).toContain('0/9');expect(wrapper.text()).toContain('50MB');expect(wrapper.find('input[type=file]').attributes('multiple')).toBeDefined()
})
it('does not fetch evidence for every history row before its viewer opens',async()=>{
wrapper=mount(Photos,{props:{kind:'MOVE',recordId:9,readonly:true,compact:true,modelValue:[]},global:{plugins:[ElementPlus]}})
await flushPromises();expect(request).not.toHaveBeenCalled();await wrapper.find('button').trigger('click');await flushPromises();expect(request).toHaveBeenCalledWith(expect.objectContaining({url:'/warehouse/operation-photos/MOVE/9'}))
})

View File

@ -2,6 +2,7 @@ import {afterEach,expect,it,vi} from 'vitest'
import {shallowMount} from '@vue/test-utils'
import Operations from '../../src/components/Production/StockOperations.vue'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
const api=vi.hoisted(()=>({outStock:vi.fn().mockResolvedValue({}),moveStock:vi.fn(),taskAction:vi.fn()}))
vi.mock('@/api/warehouse/stock',()=>({outStock:api.outStock,moveStock:api.moveStock}))
vi.mock('@/api/production/tasks',()=>({taskAction:api.taskAction}))

View File

@ -0,0 +1,18 @@
import {afterEach,expect,it,vi} from 'vitest'
import {mount,flushPromises} from '@vue/test-utils'
import ElementPlus from 'element-plus'
import Gallery from '@/components/StockPhotos/index.vue'
import request from '@/utils/request'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
let w;afterEach(()=>{w?.unmount();document.body.innerHTML='';vi.clearAllMocks()})
function render(){vi.stubGlobal('URL',{createObjectURL:vi.fn(()=> 'blob:thumb'),revokeObjectURL:vi.fn()});w=mount(Gallery,{attachTo:document.body,global:{plugins:[ElementPlus],mocks:{$dateTime:v=>v||'—'}}});return w}
it('loads nothing while the drawer is closed and downloads only bounded thumbnails until preview',async()=>{
const photo={id:'p',kind:'IN',recordId:7,name:'照片.jpg',documentNo:'RK7',businessDate:'2026-11-26',thumbnailPath:'/thumb',contentPath:'/original'};
request.mockImplementation(async options=>options.url==='/thumb'||options.url==='/original'?new Blob(['image'],{type:'image/jpeg'}):{data:{rows:[photo],total:1}});
render();await flushPromises();expect(request).not.toHaveBeenCalled();await w.vm.open({id:1,productName:'测试物品',projectName:'项目',areaName:'库区',stockNum:2});await flushPromises();
expect(request).toHaveBeenCalledWith(expect.objectContaining({url:'/warehouse/stock/1/photos',params:expect.objectContaining({kind:'ALL',pageNum:1,pageSize:24})}));expect(request.mock.calls.some(([q])=>q.url==='/original')).toBe(false);
const tile=document.querySelector('.stock-photo-tile');expect(tile.textContent).toContain('照片.jpg');tile.click();await flushPromises();expect(request.mock.calls.some(([q])=>q.url==='/original')).toBe(true);
})
it('empty stock evidence remains a readable state and source tabs are available',async()=>{
request.mockResolvedValue({data:{rows:[],total:0}});render();await w.vm.open({id:1,productName:'无照片物品'});await flushPromises();expect(document.body.textContent).toContain('暂无相关照片');for(const text of ['全部','到货照片','入库照片','移库照片'])expect(document.body.textContent).toContain(text);
})

View File

@ -0,0 +1,13 @@
-- Optional evidence for individual receipt / move operations; no business rows are rewritten.
CREATE TABLE IF NOT EXISTS warehouse_operation_photo (
id varchar(36) NOT NULL PRIMARY KEY,
kind varchar(8) NOT NULL,
record_id bigint DEFAULT NULL,
owner_id bigint NOT NULL,
name varchar(255) NOT NULL,
content_type varchar(64) NOT NULL,
byte_size int NOT NULL,
sha256 char(64) NOT NULL,
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_operation(kind,record_id), INDEX idx_draft(owner_id,record_id,create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;